Compare commits

...
Author SHA1 Message Date
atharvranjan 7c512afb2b Merge remote-tracking branch 'origin/main' into engineering/maintainer-build-readiness
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 10:33:13 -06:00
atharvranjan d2ad5808ab Address #425 review: recover idle environments and meet the #408 contract
- Accept wineserver -k exit 1 (nothing running) when -w then succeeds, so
  stop no longer fails and keeps its session marker.
- Configure shim overrides from build-shims/bin without --shims, as main does.
- Print the trace summary to stderr when --log is used.
- Refuse untested CrossOver builds unless --allow-untested-crossover is given.
- Record the original sign-off lines for the contributor work carried from #405.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 10:33:12 -06:00
atharvranjan 66804f25b4 Warn on untested CrossOver builds and record carried contributor work
run and bench warn, and records and doctor report crossover_build_tested,
because the launcher relies on observed CrossOver interfaces. Record the
contributor commits carried from #405 and label the D3D workloads as Track F
acceptance inputs.

Addresses review feedback on #425.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 10:24:10 -06:00
atharvranjan f34750f353 Credit carried contributor work and link documents left on #405
Includes work by Adeeb Rahman (ce9c10a) and Bartosz Szczepański (0427465)
carried from #405. Point comments at documents that were not migrated to
fixed commit URLs.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 09:52:50 -06:00
atharvranjan fadd742e63 Merge remote-tracking branch 'origin/main' into engineering/maintainer-build-readiness
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	launcher/crates/bx-cli/src/main.rs
2026-11-26 09:49:04 -06:00
atharvranjan d0d10c97cf Remove the implementation working log
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 09:47:21 -06:00
atharvranjan 25ba80e1eb Record checks after merging the xmem physical page work
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 09:43:29 -06:00
atharvranjan 78be10c187 Merge remote-tracking branch 'origin/main' into engineering/maintainer-build-readiness
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 09:42:33 -06:00
atharvranjan 9713018db6 Record full acceptance results after merging main
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 09:42:16 -06:00
atharvranjan 7451f0f2ae Pass DLL overrides and the backend as bin/wine options in bottle mode
CrossOver's bin/wine deletes WINEDLLOVERRIDES and applies a bottle's
[EnvironmentVariables] over the environment it was given, so bottle runs lost
the shim overrides and a saved backend replaced --backend. Pass them with
--dll and --env, and drop an inherited CX_ENV.

First reported by jelly013 on #425.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 09:27:38 -06:00
atharvranjan 1beef47c6f Merge remote-tracking branch 'origin/main' into engineering/maintainer-build-readiness
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	CHANGELOG.md
#	Cargo.toml
2026-11-26 09:27:38 -06:00
atharvranjan 6ff97b98ec Record the private bundle test in the implementation checkpoint
Part of #407.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 01:12:07 -06:00
atharvranjan 53c4380b3e Record clean-checkout acceptance results and the unverified on-screen checks
Part of #407.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 00:59:26 -06:00
atharvranjan c1e958194c Document maintainer testing and make unattended crash runs finish
Turn off Wine's crash dialog in new test bottles, soak Direct3D 12 in the
acceptance suite, report why the keyboard check failed, and add the testing
guide with its observed limitations.

Part of #407.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 00:45:17 -06:00
atharvranjan 1be97f2536 Require intended gates in negative controls and extend hybrid acceptance
Add the swapchain lifetime and Shader Model 6 checks to the suite, report
checks that did not run, identify the adapter and creation refcount in the
lifetime probe, and restore the #406 doctor information.

Part of #407.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 00:07:16 -06:00
atharvranjan a9d7bc000b Merge remote-tracking branch 'origin/main' into engineering/maintainer-build-readiness
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-25 23:51:14 -06:00
atharvranjan b9469aa22d Move the supervised hybrid runtime and Direct3D workloads onto the six-track layout
bx-cli now launches through one supervised engine (launcher/crates/bx-runtime)
carried from #405, keeping #406's shim, profile, prefix and log contracts and
leaving abi/ unchanged. Original workloads move under tests/conformance/.

Verified locally: fmt, clippy -D warnings, 67 workspace tests, arm64 bx-cli,
16 shim DLLs / 102 exports, and both live shim fixtures under CrossOver 26.3.

Part of #407.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 23:51:04 -06:00
atharvranjan bba0851e44 Record merged hybrid baseline verification and preserved donor work
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 23:27:03 -06:00
80 changed files with 8723 additions and 275 deletions

No files matched your search

+4
View File
@@ -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
+14
View File
@@ -9,7 +9,21 @@ exact revision and known limitations.
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### 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
- 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).
- 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).
Generated
+14
View File
@@ -7,6 +7,7 @@ name = "bx-cli"
version = "0.2.0"
dependencies = [
"bx-probe",
"bx-runtime",
"bx-telemetry",
"dxbc-accc",
]
@@ -15,6 +16,13 @@ dependencies = [
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"
@@ -29,3 +37,9 @@ dependencies = [
[[package]]
name = "dxbc-accc"
version = "0.2.0"
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+1
View File
@@ -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",
]
+2 -1
View File
@@ -185,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) |
---
+19 -1
View File
@@ -1,6 +1,24 @@
# Third-party notices
The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) currently has **zero external crates.io dependencies** and is original `GPL-3.0-or-later` source.
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.
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.
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).
## 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 |
| --- | --- | --- |
| 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)
+2
View File
@@ -8,6 +8,7 @@
- [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
@@ -21,6 +22,7 @@
- [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.
- [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
+8
View File
@@ -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 |
+185
View File
@@ -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/`.
@@ -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.
+5
View File
@@ -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
+1
View File
@@ -13,6 +13,7 @@ path = "src/main.rs"
bx-probe = { path = "../bx-probe" }
bx-telemetry = { path = "../bx-telemetry" }
dxbc-accc = { path = "../../../shader-transpiler/crates/dxbc-accc" }
bx-runtime = { path = "../bx-runtime" }
[lints]
workspace = true
+75 -273
View File
@@ -2,34 +2,14 @@
use std::collections::BTreeMap;
use std::env;
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
use std::process::ExitCode;
use bx_probe::{ShimTrack, classify_dll, probe_pe32_plus};
use bx_telemetry::summarize_jsonl;
use dxbc_accc::inspect_dxbc;
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";
const SAFE_CHILD_PATH: &str = "/usr/bin:/bin:/usr/sbin:/sbin";
const HOST_ENV_ALLOWLIST: &[&str] = &[
"HOME",
"USER",
"LOGNAME",
"TMPDIR",
"LANG",
"LC_ALL",
"TERM",
"DISPLAY",
"XPC_FLAGS",
"XPC_SERVICE_NAME",
];
fn print_usage() {
eprintln!(
"BetterXen Hybrid CLI (bx-cli)\n\
@@ -39,78 +19,11 @@ fn print_usage() {
bx-cli probe <pe32+_path> Classify PE32+ imports by BetterXen track (A-E)\n\
bx-cli shader <dxbc_blob_path> Classify a DXBC shader container (DXIL vs ACCC/FSPX)\n\
bx-cli trace <log.jsonl> Summarize bx_runtime_veh JSONL diagnostics\n\
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env]\n"
bx-cli run --exe <path> (--bottle <name> | --prefix <dir>) [--shims <dir>] [--profile lockhart|anaconda] [--log <path>] [supervisor options]\n\
bx-cli run --help Show supervised runtime commands and options\n"
);
}
fn run_capture(program: &str, args: &[&str]) -> Option<String> {
let out = Command::new(program).args(args).output().ok()?;
if out.status.success() {
Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
} else {
None
}
}
fn cmd_doctor() -> ExitCode {
let arch = run_capture("uname", &["-m"]).unwrap_or_else(|| "unknown".into());
let macos = run_capture("sw_vers", &["-productVersion"]).unwrap_or_else(|| "unknown".into());
let cpu = run_capture("sysctl", &["-n", "machdep.cpu.brand_string"])
.unwrap_or_else(|| "unknown".into());
let mem_bytes: u64 = run_capture("sysctl", &["-n", "hw.memsize"])
.and_then(|s| s.parse().ok())
.unwrap_or(0);
let mem_gb = mem_bytes / (1024 * 1024 * 1024);
let default_profile = if mem_gb >= 32 { "anaconda" } else { "lockhart" };
let crossover_ver = run_capture(
"defaults",
&[
"read",
"/Applications/CrossOver.app/Contents/Info.plist",
"CFBundleShortVersionString",
],
);
let d3dmetal_exists = Path::new(
"/Applications/CrossOver.app/Contents/SharedSupport/CrossOver/lib64/apple_gptk/external/D3DMetal.framework",
)
.exists();
let mingw = run_capture("which", &["x86_64-w64-mingw32-g++"]);
let rosetta = Command::new("pgrep")
.args(["-q", "oahd"])
.status()
.is_ok_and(|s| s.success());
println!("=== BetterXen Host Doctor ===");
println!("Host arch : {arch}");
println!("CPU : {cpu}");
println!("macOS : {macos}");
println!("Unified memory : {mem_gb} GiB (recommended profile: {default_profile})");
println!(
"Rosetta 2 (oahd) : {}",
if rosetta { "active" } else { "not detected" }
);
println!(
"CrossOver : {}",
crossover_ver.as_deref().unwrap_or("not installed")
);
println!(
"D3DMetal.fwk : {}",
if d3dmetal_exists {
"present"
} else {
"not found"
}
);
println!(
"mingw-w64 g++ : {}",
mingw
.as_deref()
.unwrap_or("missing (brew install mingw-w64)")
);
ExitCode::SUCCESS
}
fn cmd_probe(path: &str) -> ExitCode {
let data = match fs::read(path) {
Ok(d) => d,
@@ -171,20 +84,29 @@ fn cmd_trace(path: &str) -> ExitCode {
return ExitCode::FAILURE;
}
};
let summary = summarize_jsonl(&text);
println!("Trace events : {}", summary.total_lines);
println!(
print!("{}", render_trace(&text));
ExitCode::SUCCESS
}
fn render_trace(text: &str) -> String {
let mut out = String::new();
let summary = summarize_jsonl(text);
let _ = writeln!(out, "Trace events : {}", summary.total_lines);
let _ = writeln!(
out,
"{}",
format_clwb_line(summary.clwb_events, summary.clwb_trap_lower_bound)
);
println!("ADX illegal ops : {}", summary.adx_errors);
let _ = writeln!(out, "ADX illegal ops : {}", summary.adx_errors);
if !summary.unhandled_exceptions.is_empty() {
println!(
let _ = writeln!(
out,
"\nUnhandled exceptions ({}):",
summary.unhandled_exceptions.len()
);
for crash in summary.unhandled_exceptions {
println!(
let _ = writeln!(
out,
" code={} module_base={} + RVA={} RIP={}",
crash.exception_code.as_deref().unwrap_or("unknown"),
crash.module_base.as_deref().unwrap_or("unknown"),
@@ -194,172 +116,52 @@ fn cmd_trace(path: &str) -> ExitCode {
}
}
if !summary.unimpl_apis.is_empty() {
println!("\nUnimplemented APIs:");
let _ = writeln!(out, "\nUnimplemented APIs:");
for (api, count) in summary.unimpl_apis {
println!(" {count:5}x {api}");
let _ = writeln!(out, " {count:5}x {api}");
}
}
if !summary.unimpl_vtables.is_empty() {
println!("\nUnimplemented COM vtable slots:");
let _ = writeln!(out, "\nUnimplemented COM vtable slots:");
for (slot, count) in summary.unimpl_vtables {
println!(" {count:5}x {slot}");
let _ = writeln!(out, " {count:5}x {slot}");
}
}
ExitCode::SUCCESS
out
}
fn unix_to_wine_z_path(path: &Path) -> String {
let s = path.to_string_lossy();
format!("Z:{}", s.replace('/', "\\"))
}
fn collect_isolated_host_env<F>(mut lookup: F) -> BTreeMap<String, String>
where
F: FnMut(&str) -> Option<String>,
{
let mut env_map = BTreeMap::new();
env_map.insert("PATH".to_string(), SAFE_CHILD_PATH.to_string());
for &key in HOST_ENV_ALLOWLIST {
if let Some(val) = lookup(key) {
env_map.insert(key.to_string(), val);
}
}
env_map
}
fn cmd_run(args: &[String]) -> ExitCode {
let mut exe_path: Option<PathBuf> = None;
let mut shims_dir = PathBuf::from("build-shims/bin");
let mut profile = String::from("lockhart");
let mut bottle: Option<String> = None;
let mut wine_prefix: Option<PathBuf> = None;
let mut log_file: Option<PathBuf> = None;
let mut inherit_env = false;
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--exe" if i + 1 < args.len() => {
exe_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
"--shims" if i + 1 < args.len() => {
shims_dir = PathBuf::from(&args[i + 1]);
i += 2;
}
"--profile" if i + 1 < args.len() => {
profile = args[i + 1].clone();
i += 2;
}
"--bottle" if i + 1 < args.len() => {
bottle = Some(args[i + 1].clone());
i += 2;
}
"--prefix" if i + 1 < args.len() => {
wine_prefix = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
"--log" if i + 1 < args.len() => {
log_file = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
"--inherit-env" => {
inherit_env = true;
i += 1;
}
other => {
eprintln!("unknown argument: {other}");
return ExitCode::FAILURE;
}
}
}
let Some(exe) = exe_path else {
eprintln!("error: --exe <path> is required");
return ExitCode::FAILURE;
/// The `--log` value of a `run` invocation, ignoring anything after `--` (guest arguments).
fn run_log_path(args: &[String]) -> Option<&str> {
let args = match args.first().map(String::as_str) {
Some("hybrid") => &args[1..],
_ => args,
};
let cx_root = Path::new("/Applications/CrossOver.app/Contents/SharedSupport/CrossOver");
let wine_wrapper = cx_root.join("bin/wine");
let wineloader = cx_root.join("bin/wineloader");
if !wineloader.exists() {
eprintln!("error: CrossOver not found under /Applications/CrossOver.app");
return ExitCode::FAILURE;
if args.first().map(String::as_str) != Some("run") {
return None;
}
let mut options = args.iter().take_while(|a| *a != "--");
options.find(|a| *a == "--log")?;
options.next().map(String::as_str)
}
let abs_shims = fs::canonicalize(&shims_dir).unwrap_or(shims_dir);
let abs_exe = fs::canonicalize(&exe).unwrap_or(exe);
let wine_shims_path = unix_to_wine_z_path(&abs_shims);
let resolved_prefix =
wine_prefix.unwrap_or_else(|| PathBuf::from("/tmp/betterxen-wine-prefix"));
let mut cmd = if let Some(ref bname) = bottle {
let mut c = Command::new(&wine_wrapper);
c.args(["--bottle", bname]).arg(&abs_exe);
c
} else {
let _ = fs::create_dir_all(&resolved_prefix);
let mut c = Command::new(&wineloader);
c.arg(&abs_exe);
c
};
if !inherit_env {
cmd.env_clear();
for (k, v) in collect_isolated_host_env(|k| env::var(k).ok()) {
cmd.env(k, v);
}
}
if bottle.is_none() {
cmd.env("WINEPREFIX", &resolved_prefix)
.env("WINESERVER", cx_root.join("bin/wineserver"))
.env("WINELOADER", &wineloader)
.env(
"WINEDLLPATH",
format!(
"{}:{}",
cx_root.join("lib/wine").display(),
cx_root.join("lib64/wine").display()
),
)
.env(
"DYLD_FALLBACK_LIBRARY_PATH",
format!(
"{}:{}:/usr/lib",
cx_root.join("lib64").display(),
cx_root.join("lib").display()
),
);
}
cmd.env("ROSETTA_ADVERTISE_AVX", "1")
.env("WINEDLLOVERRIDES", SHIM_DLL_OVERRIDES)
.env("WINEPATH", &wine_shims_path)
.env("BX_PROFILE", &profile)
.env("WINEDEBUG", "-all");
if let Some(ref lf) = log_file {
let abs_log = if lf.is_absolute() {
lf.clone()
} else {
env::current_dir().unwrap_or_default().join(lf)
};
cmd.env("BX_LOG_FILE", unix_to_wine_z_path(&abs_log));
}
match cmd.status() {
Ok(st) if st.success() => ExitCode::SUCCESS,
Ok(st) => {
eprintln!("guest exited with status: {st}");
ExitCode::FAILURE
}
Err(e) => {
eprintln!("failed to launch CrossOver wine: {e}");
ExitCode::FAILURE
}
/// Runs the supervised engine and, when `--log` grew during the run, prints the log's summary
/// to stderr so stdout stays a single JSON record (#408).
fn cmd_runtime(args: &[String]) -> ExitCode {
let log = run_log_path(args);
let size = |path: &str| fs::metadata(path).map_or(0, |m| m.len());
let before = log.map_or(0, size);
let code = bx_runtime::cli::run_cli(args);
if let Some(path) = log
&& size(path) > before
&& let Ok(bytes) = fs::read(path)
{
// Guest text may not be valid UTF-8; a summary is still worth printing.
eprint!(
"\nTrace summary of {path} (whole log):\n{}",
render_trace(&String::from_utf8_lossy(&bytes))
);
}
code
}
fn cmd_shader(path: &str) -> ExitCode {
@@ -400,11 +202,19 @@ fn main() -> ExitCode {
return ExitCode::SUCCESS;
};
match sub.as_str() {
"doctor" => cmd_doctor(),
"--help" | "help" => {
print_usage();
ExitCode::SUCCESS
}
"--version" => {
println!("bx-cli {}", env!("CARGO_PKG_VERSION"));
ExitCode::SUCCESS
}
"doctor" | "host" | "receipt" | "crossover" | "toolchain" | "inspect" | "frames"
| "guard" | "run" | "bench" | "stop" | "hybrid" => cmd_runtime(&args),
"probe" if args.len() >= 2 => cmd_probe(&args[1]),
"shader" if args.len() >= 2 => cmd_shader(&args[1]),
"trace" if args.len() >= 2 => cmd_trace(&args[1]),
"run" => cmd_run(&args[1..]),
_ => {
print_usage();
ExitCode::FAILURE
@@ -417,30 +227,22 @@ mod tests {
use super::*;
#[test]
fn isolated_env_strips_secrets_and_pins_path() {
let host = BTreeMap::from([
("HOME", "/Users/tester"),
("USER", "tester"),
("PATH", "/custom/dev/bin:/usr/bin"),
("GH_TOKEN", "secret_token"),
("AWS_SECRET_ACCESS_KEY", "secret_aws"),
("CX_GRAPHICS_BACKEND", "wined3d"),
]);
let child = collect_isolated_host_env(|k| host.get(k).map(|s| (*s).to_string()));
assert_eq!(child.get("PATH").map(String::as_str), Some(SAFE_CHILD_PATH));
assert_eq!(child.get("HOME").map(String::as_str), Some("/Users/tester"));
assert_eq!(child.get("USER").map(String::as_str), Some("tester"));
assert!(!child.contains_key("GH_TOKEN"));
assert!(!child.contains_key("AWS_SECRET_ACCESS_KEY"));
assert!(!child.contains_key("CX_GRAPHICS_BACKEND"));
fn finds_the_run_log_but_not_guest_arguments() {
let args = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
let run = args(&["run", "--bottle", "b", "--log", "x.jsonl", "--exe", "a.exe"]);
assert_eq!(run_log_path(&run), Some("x.jsonl"));
let hybrid = args(&["hybrid", "run", "--log", "y.jsonl"]);
assert_eq!(run_log_path(&hybrid), Some("y.jsonl"));
let guest = args(&["run", "--bottle", "b", "--", "a.exe", "--log", "z"]);
assert_eq!(run_log_path(&guest), None);
assert_eq!(run_log_path(&args(&["bench", "--log", "x"])), None);
}
#[test]
fn converts_unix_path_to_wine_z_drive() {
assert_eq!(
unix_to_wine_z_path(Path::new("/tmp/bx-test.jsonl")),
"Z:\\tmp\\bx-test.jsonl"
);
fn renders_a_trace_summary() {
let out = render_trace("");
assert!(out.starts_with("Trace events : 0\n"));
assert!(out.contains("ADX illegal ops : 0\n"));
}
#[test]
+13
View File
@@ -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
+7
View File
@@ -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.
+928
View File
@@ -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)
);
}
}
+13
View File
@@ -0,0 +1,13 @@
//! Run a system tool and capture trimmed stdout. A missing tool or non-zero exit is `None`,
//! never a guessed value.
use std::process::Command;
pub fn run(program: &str, args: &[&str]) -> Option<String> {
let out = Command::new(program).args(args).output().ok()?;
if !out.status.success() {
return None;
}
let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
Some(s)
}
+162
View File
@@ -0,0 +1,162 @@
//! Discover installed CrossOver bundles and read standard bundle metadata.
//!
//! Only documented or standard macOS interfaces are used: the app bundle's `Info.plist`
//! (read through `plutil`), `lipo -archs` on the bundle's main executable, and the
//! `defaults` keys CodeWeavers documents in "Advanced CrossOver Mac Configuration"
//! (`BottleDir`, `ManagedBottleDirs` in `com.codeweavers.CrossOver`). Bundle internals such
//! as `Contents/SharedSupport` are NOT interpreted: they are undocumented and not a stable
//! interface (#350). The graphics backend of a bottle is deliberately not read.
use crate::cmdutil::run;
use crate::json::Json;
use std::path::{Path, PathBuf};
pub const BUNDLE_ID: &str = "com.codeweavers.CrossOver";
#[derive(Debug, Clone, PartialEq)]
pub struct Install {
pub path: PathBuf,
pub bundle_id: Option<String>,
pub short_version: Option<String>,
pub build_version: Option<String>,
pub executable_archs: Option<Vec<String>>,
pub minimum_macos: Option<String>,
}
/// Candidate bundle locations: standard application directories. Spotlight is consulted too.
pub fn candidate_paths(home: &Path) -> Vec<PathBuf> {
let mut v = vec![
PathBuf::from("/Applications/CrossOver.app"),
home.join("Applications/CrossOver.app"),
];
if let Some(found) = run(
"/usr/bin/mdfind",
&[&format!("kMDItemCFBundleIdentifier == '{BUNDLE_ID}'")],
) {
for line in found.lines().filter(|l| !l.is_empty()) {
let p = PathBuf::from(line);
if !v.contains(&p) {
v.push(p);
}
}
}
v
}
pub fn discover(candidates: &[PathBuf]) -> Vec<Install> {
candidates.iter().filter_map(|p| inspect(p)).collect()
}
/// Inspect one bundle. Returns None if the path has no readable `Contents/Info.plist`.
pub fn inspect(app: &Path) -> Option<Install> {
let plist = app.join("Contents/Info.plist");
if !plist.is_file() {
return None;
}
let json = run(
"/usr/bin/plutil",
&["-convert", "json", "-o", "-", plist.to_str()?],
)?;
let exe = crate::host_string(&json, "CFBundleExecutable");
let archs = exe.and_then(|e| {
let p = app.join("Contents/MacOS").join(e);
run("/usr/bin/lipo", &["-archs", p.to_str()?])
.map(|s| s.split_whitespace().map(String::from).collect())
});
Some(Install {
path: app.to_path_buf(),
bundle_id: crate::host_string(&json, "CFBundleIdentifier"),
short_version: crate::host_string(&json, "CFBundleShortVersionString"),
build_version: crate::host_string(&json, "CFBundleVersion"),
executable_archs: archs,
minimum_macos: crate::host_string(&json, "LSMinimumSystemVersion"),
})
}
/// A documented CrossOver preference, or None when unset or unreadable.
pub fn preference(key: &str) -> Option<String> {
run("/usr/bin/defaults", &["read", BUNDLE_ID, key])
}
impl Install {
pub fn to_json(&self) -> Json {
Json::obj(vec![
("path", Json::str(self.path.display().to_string())),
("bundle_id", Json::opt_str(self.bundle_id.clone())),
("short_version", Json::opt_str(self.short_version.clone())),
("build_version", Json::opt_str(self.build_version.clone())),
(
"executable_archs",
self.executable_archs.as_ref().map_or(Json::Null, |a| {
Json::Arr(a.iter().map(|s| Json::str(s.clone())).collect())
}),
),
("minimum_macos", Json::opt_str(self.minimum_macos.clone())),
(
"bundle_id_is_codeweavers_crossover",
Json::Bool(self.bundle_id.as_deref() == Some(BUNDLE_ID)),
),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
// A synthetic bundle written by the test: it proves the metadata path, not that
// any real CrossOver build has this layout.
fn fake_bundle(dir: &Path) -> PathBuf {
let app = dir.join("CrossOver.app");
fs::create_dir_all(app.join("Contents/MacOS")).unwrap();
fs::write(
app.join("Contents/Info.plist"),
r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>CFBundleExecutable</key><string>CrossOver</string>
<key>CFBundleIdentifier</key><string>com.codeweavers.CrossOver</string>
<key>CFBundleShortVersionString</key><string>99.1.2</string>
<key>CFBundleVersion</key><string>12345</string>
<key>LSMinimumSystemVersion</key><string>14.0</string>
</dict></plist>"#,
)
.unwrap();
// Copy a real system executable so `lipo -archs` has a Mach-O to read.
fs::copy("/usr/bin/true", app.join("Contents/MacOS/CrossOver")).unwrap();
app
}
#[test]
fn reads_bundle_metadata() {
if !cfg!(target_os = "macos") {
return;
}
let tmp = std::env::temp_dir().join(format!("bxhybrid-co-{}", std::process::id()));
let _ = fs::remove_dir_all(&tmp);
fs::create_dir_all(&tmp).unwrap();
let app = fake_bundle(&tmp);
let i = inspect(&app).expect("inspect");
assert_eq!(i.short_version.as_deref(), Some("99.1.2"));
assert_eq!(i.build_version.as_deref(), Some("12345"));
assert_eq!(i.minimum_macos.as_deref(), Some("14.0"));
assert_eq!(i.bundle_id.as_deref(), Some(BUNDLE_ID));
assert!(
i.executable_archs.as_ref().is_some_and(|a| !a.is_empty()),
"{:?}",
i.executable_archs
);
assert_eq!(discover(&[app.clone(), tmp.join("Missing.app")]).len(), 1);
fs::remove_dir_all(&tmp).unwrap();
}
#[test]
fn missing_or_plistless_bundle_is_none() {
let tmp = std::env::temp_dir().join(format!("bxhybrid-co2-{}", std::process::id()));
fs::create_dir_all(tmp.join("X.app/Contents")).unwrap();
assert!(inspect(&tmp.join("X.app")).is_none());
assert!(inspect(&tmp.join("Nope.app")).is_none());
fs::remove_dir_all(&tmp).unwrap();
}
}
+192
View File
@@ -0,0 +1,192 @@
//! Frame-time statistics from a list of frame intervals in milliseconds (issue #145).
//!
//! Percentiles use the nearest-rank method on the sorted intervals: the p-th percentile is
//! the value at rank ceil(p/100 * n) (1-based). "1 % low FPS" is 1000 divided by the 99th
//! percentile interval. These definitions are fixed here so reports are comparable; other
//! tools define lows differently (for example as the mean of the worst 1 %).
use crate::json::Json;
#[derive(Debug, Clone, PartialEq)]
pub struct FrameStats {
pub frames: usize,
pub total_ms: f64,
pub mean_ms: f64,
pub avg_fps: f64,
pub min_ms: f64,
pub max_ms: f64,
pub p50_ms: f64,
pub p95_ms: f64,
pub p99_ms: f64,
pub p999_ms: f64,
pub low_1pct_fps: f64,
pub low_01pct_fps: f64,
/// Frames longer than twice the median interval.
pub stutters: usize,
}
#[derive(Debug, PartialEq)]
pub enum FrameError {
Empty,
Invalid { index: usize, value: f64 },
Parse { line: usize, text: String },
}
impl std::fmt::Display for FrameError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FrameError::Empty => write!(f, "no frame intervals"),
FrameError::Invalid { index, value } => {
write!(
f,
"frame {index}: interval {value} is not a positive finite number of milliseconds"
)
}
FrameError::Parse { line, text } => {
write!(f, "line {line}: cannot parse {text:?} as milliseconds")
}
}
}
}
impl std::error::Error for FrameError {}
fn nearest_rank(sorted: &[f64], pct: f64) -> f64 {
let n = sorted.len();
let rank = ((pct / 100.0) * n as f64).ceil().max(1.0) as usize;
sorted[rank.min(n) - 1]
}
pub fn analyze(intervals_ms: &[f64]) -> Result<FrameStats, FrameError> {
if intervals_ms.is_empty() {
return Err(FrameError::Empty);
}
for (index, &value) in intervals_ms.iter().enumerate() {
if !value.is_finite() || value <= 0.0 {
return Err(FrameError::Invalid { index, value });
}
}
let mut sorted = intervals_ms.to_vec();
sorted.sort_by(|a, b| a.total_cmp(b));
let total: f64 = intervals_ms.iter().sum();
let n = sorted.len();
let p50 = nearest_rank(&sorted, 50.0);
let p99 = nearest_rank(&sorted, 99.0);
let p999 = nearest_rank(&sorted, 99.9);
Ok(FrameStats {
frames: n,
total_ms: total,
mean_ms: total / n as f64,
avg_fps: n as f64 / (total / 1000.0),
min_ms: sorted[0],
max_ms: sorted[n - 1],
p50_ms: p50,
p95_ms: nearest_rank(&sorted, 95.0),
p99_ms: p99,
p999_ms: p999,
low_1pct_fps: 1000.0 / p99,
low_01pct_fps: 1000.0 / p999,
stutters: intervals_ms.iter().filter(|&&v| v > 2.0 * p50).count(),
})
}
/// Parse one interval per line; blank lines and lines starting with `#` are skipped.
pub fn parse_intervals(text: &str) -> Result<Vec<f64>, FrameError> {
let mut out = Vec::new();
for (i, line) in text.lines().enumerate() {
let t = line.trim();
if t.is_empty() || t.starts_with('#') {
continue;
}
let v: f64 = t.parse().map_err(|_| FrameError::Parse {
line: i + 1,
text: t.to_string(),
})?;
out.push(v);
}
Ok(out)
}
impl FrameStats {
pub fn to_json(&self) -> Json {
Json::obj(vec![
("frames", Json::Num(self.frames as f64)),
("total_ms", Json::Num(self.total_ms)),
("mean_ms", Json::Num(self.mean_ms)),
("avg_fps", Json::Num(self.avg_fps)),
("min_ms", Json::Num(self.min_ms)),
("max_ms", Json::Num(self.max_ms)),
("p50_ms", Json::Num(self.p50_ms)),
("p95_ms", Json::Num(self.p95_ms)),
("p99_ms", Json::Num(self.p99_ms)),
("p999_ms", Json::Num(self.p999_ms)),
("low_1pct_fps", Json::Num(self.low_1pct_fps)),
("low_0_1pct_fps", Json::Num(self.low_01pct_fps)),
("stutters_over_2x_median", Json::Num(self.stutters as f64)),
("percentile_method", Json::str("nearest-rank")),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
// Expected values below are worked out by hand, not produced by analyze().
#[test]
fn known_answer_ten_frames() {
// Sorted: 10,10,10,10,10,10,10,10,20,100. Total 200 ms, n = 10.
let v = [10.0, 10.0, 10.0, 10.0, 20.0, 10.0, 10.0, 10.0, 100.0, 10.0];
let s = analyze(&v).unwrap();
assert_eq!(s.frames, 10);
assert_eq!(s.total_ms, 200.0);
assert_eq!(s.mean_ms, 20.0);
assert_eq!(s.avg_fps, 50.0);
assert_eq!(s.p50_ms, 10.0); // rank 5
assert_eq!(s.p95_ms, 100.0); // rank ceil(9.5) = 10
assert_eq!(s.p99_ms, 100.0);
assert_eq!(s.low_1pct_fps, 10.0);
assert_eq!(s.stutters, 1); // threshold is 2 * 10 = 20; 20 is not > 20, only 100 is.
}
#[test]
fn stutter_threshold_is_strict() {
let s = analyze(&[10.0, 10.0, 10.0, 20.0, 21.0]).unwrap();
assert_eq!(s.stutters, 1);
}
#[test]
fn one_frame_per_second() {
let s = analyze(&[1000.0, 1000.0]).unwrap();
assert_eq!(s.avg_fps, 1.0);
}
#[test]
fn rejects_bad_input() {
assert_eq!(analyze(&[]), Err(FrameError::Empty));
assert!(matches!(
analyze(&[1.0, 0.0]),
Err(FrameError::Invalid { index: 1, .. })
));
assert!(matches!(
analyze(&[f64::NAN]),
Err(FrameError::Invalid { .. })
));
assert!(matches!(analyze(&[-3.0]), Err(FrameError::Invalid { .. })));
}
#[test]
fn parses_text() {
assert_eq!(
parse_intervals("# c\n16.5\n\n 8 \n").unwrap(),
vec![16.5, 8.0]
);
assert_eq!(
parse_intervals("1\nabc\n"),
Err(FrameError::Parse {
line: 2,
text: "abc".into()
})
);
}
}
+228
View File
@@ -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"));
}
}
+114
View File
@@ -0,0 +1,114 @@
//! Minimal JSON value and writer. Output only; no parsing is needed by this crate.
#[derive(Debug, Clone, PartialEq)]
pub enum Json {
Null,
Bool(bool),
Num(f64),
Str(String),
Arr(Vec<Json>),
Obj(Vec<(String, Json)>),
}
impl Json {
pub fn str(s: impl Into<String>) -> Json {
Json::Str(s.into())
}
pub fn opt_str(s: Option<String>) -> Json {
s.map_or(Json::Null, Json::Str)
}
pub fn obj(fields: Vec<(&str, Json)>) -> Json {
Json::Obj(
fields
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect(),
)
}
pub fn render(&self) -> String {
let mut out = String::new();
self.write(&mut out, 0);
out.push('\n');
out
}
fn write(&self, out: &mut String, depth: usize) {
let pad = |out: &mut String, d: usize| out.push_str(&" ".repeat(d));
match self {
Json::Null => out.push_str("null"),
Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Json::Num(n) if n.is_finite() => {
if n.fract() == 0.0 && n.abs() < 1e15 {
out.push_str(&format!("{}", *n as i64));
} else {
out.push_str(&format!("{n}"));
}
}
// JSON has no NaN or infinity; refuse to invent a number.
Json::Num(_) => out.push_str("null"),
Json::Str(s) => escape(s, out),
Json::Arr(items) if items.is_empty() => out.push_str("[]"),
Json::Arr(items) => {
out.push_str("[\n");
for (i, item) in items.iter().enumerate() {
pad(out, depth + 1);
item.write(out, depth + 1);
out.push_str(if i + 1 < items.len() { ",\n" } else { "\n" });
}
pad(out, depth);
out.push(']');
}
Json::Obj(fields) if fields.is_empty() => out.push_str("{}"),
Json::Obj(fields) => {
out.push_str("{\n");
for (i, (k, v)) in fields.iter().enumerate() {
pad(out, depth + 1);
escape(k, out);
out.push_str(": ");
v.write(out, depth + 1);
out.push_str(if i + 1 < fields.len() { ",\n" } else { "\n" });
}
pad(out, depth);
out.push('}');
}
}
}
}
fn escape(s: &str, out: &mut String) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escapes_and_nests() {
let j = Json::obj(vec![
("a", Json::str("q\"\\\n\u{1}")),
(
"b",
Json::Arr(vec![Json::Num(1.0), Json::Num(0.5), Json::Null]),
),
("c", Json::Num(f64::NAN)),
]);
let r = j.render();
assert!(r.contains(r#""a": "q\"\\\n\u0001""#), "{r}");
assert!(r.contains("0.5"));
assert!(r.contains(r#""c": null"#));
}
}
+38
View File
@@ -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
}
+210
View File
@@ -0,0 +1,210 @@
//! Memory-pressure supervision of a child process.
//!
//! Adapted in concept from the memory guard in `mac/run-victory.sh` of
//! <https://github.com/skakwy/victory-mac> (author skakwy, GPL-3.0; commit 22b3f8e, used with
//! the author's permission): do not start a workload when little memory is free, and stop it
//! when system-wide free memory falls below a limit, because GPU memory is wired under
//! unified memory and a runaway workload can take the whole Mac down. This version is
//! reimplemented in Rust, stops the child with SIGTERM before SIGKILL, and reports why it
//! stopped. It supervises any command; it contains nothing game-specific.
//!
//! The reading is the "System-wide memory free percentage" line of `memory_pressure -Q`.
//! That line was observed on macOS 27.0 (build 26A428); its format is not a documented
//! stable interface, so an unreadable value is an error, never "assume enough memory".
use crate::cmdutil::run;
use std::process::{Child, Command};
use std::time::{Duration, Instant};
pub fn parse_free_percentage(output: &str) -> Option<u8> {
let line = output
.lines()
.find(|l| l.contains("System-wide memory free percentage"))?;
let digits: String = line
.split(':')
.nth(1)?
.trim()
.chars()
.take_while(|c| c.is_ascii_digit())
.collect();
let v: u8 = digits.parse().ok()?;
(v <= 100).then_some(v)
}
pub fn free_percentage() -> Option<u8> {
run("/usr/bin/memory_pressure", &["-Q"]).and_then(|o| parse_free_percentage(&o))
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Limits {
/// Refuse to start below this percent free.
pub min_start_free: u8,
/// Stop the child when free memory drops below this percent.
pub min_free: u8,
pub poll: Duration,
/// Time between SIGTERM and SIGKILL.
pub grace: Duration,
}
#[derive(Debug, PartialEq)]
pub enum Outcome {
/// The child ran to completion; `None` means it ended by a signal.
Exited(Option<i32>),
RefusedToStart {
free: u8,
need: u8,
},
StoppedLowMemory {
free: u8,
limit: u8,
},
/// Memory could not be read, so no guarantee can be given.
MemoryUnreadable,
SpawnFailed(String),
}
pub(crate) fn terminate(child: &mut Child, grace: Duration) {
let _ = Command::new("/bin/kill")
.args(["-TERM", &child.id().to_string()])
.status();
let t0 = Instant::now();
while t0.elapsed() < grace {
if matches!(child.try_wait(), Ok(Some(_))) {
return;
}
std::thread::sleep(Duration::from_millis(50));
}
let _ = child.kill();
let _ = child.wait();
}
/// Run `program` under `limits`, reading memory through `read_free`.
pub fn supervise(
program: &str,
args: &[String],
limits: Limits,
read_free: &mut dyn FnMut() -> Option<u8>,
) -> Outcome {
match read_free() {
None => return Outcome::MemoryUnreadable,
Some(free) if free < limits.min_start_free => {
return Outcome::RefusedToStart {
free,
need: limits.min_start_free,
};
}
Some(_) => {}
}
let mut child = match Command::new(program).args(args).spawn() {
Ok(c) => c,
Err(e) => return Outcome::SpawnFailed(format!("{program}: {e}")),
};
loop {
match child.try_wait() {
Ok(Some(status)) => return Outcome::Exited(status.code()),
Ok(None) => {}
Err(e) => return Outcome::SpawnFailed(e.to_string()),
}
match read_free() {
None => {
terminate(&mut child, limits.grace);
return Outcome::MemoryUnreadable;
}
Some(free) if free < limits.min_free => {
terminate(&mut child, limits.grace);
return Outcome::StoppedLowMemory {
free,
limit: limits.min_free,
};
}
Some(_) => {}
}
std::thread::sleep(limits.poll);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn limits() -> Limits {
Limits {
min_start_free: 50,
min_free: 20,
poll: Duration::from_millis(20),
grace: Duration::from_millis(500),
}
}
#[test]
fn parses_memory_pressure_output() {
let real = "The system has 25769803776 (1572864 pages with a page size of 16384).\nSystem-wide memory free percentage: 71%\n";
assert_eq!(parse_free_percentage(real), Some(71));
assert_eq!(
parse_free_percentage("System-wide memory free percentage: 100%"),
Some(100)
);
assert_eq!(
parse_free_percentage("System-wide memory free percentage: 101%"),
None
);
assert_eq!(
parse_free_percentage("System-wide memory free percentage: x"),
None
);
assert_eq!(parse_free_percentage("nothing"), None);
}
#[test]
fn refuses_to_start_when_low() {
let out = supervise("/usr/bin/true", &[], limits(), &mut || Some(30));
assert_eq!(out, Outcome::RefusedToStart { free: 30, need: 50 });
}
#[test]
fn unreadable_memory_is_an_error() {
assert_eq!(
supervise("/usr/bin/true", &[], limits(), &mut || None),
Outcome::MemoryUnreadable
);
}
#[test]
fn child_exit_code_is_reported() {
let out = supervise(
"/bin/sh",
&["-c".into(), "exit 7".into()],
limits(),
&mut || Some(90),
);
assert_eq!(out, Outcome::Exited(Some(7)));
}
#[test]
fn stops_child_when_memory_drops() {
let mut calls = 0;
let t0 = Instant::now();
let out = supervise("/bin/sleep", &["30".into()], limits(), &mut || {
calls += 1;
Some(if calls < 4 { 90 } else { 10 })
});
assert_eq!(
out,
Outcome::StoppedLowMemory {
free: 10,
limit: 20
}
);
assert!(
t0.elapsed() < Duration::from_secs(10),
"child was not stopped promptly"
);
}
#[test]
fn real_reading_is_available_on_macos() {
if cfg!(target_os = "macos") {
assert!(free_percentage().is_some());
}
}
}
+311
View File
@@ -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(&sections, 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(&sections, 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(_))));
}
}
+197
View File
@@ -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"));
}
}
+142
View File
@@ -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
+128
View File
@@ -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();
}
}
+5
View File
@@ -0,0 +1,5 @@
[toolchain]
channel = "1.100.0"
profile = "minimal"
components = ["rustfmt", "clippy"]
targets = ["aarch64-apple-darwin"]
+260
View File
@@ -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
+131
View File
@@ -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())
+102
View File
@@ -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}")
+44
View File
@@ -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"
+54
View File
@@ -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
+36
View File
@@ -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}")
+76
View File
@@ -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}")
+13
View File
@@ -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
+35
View File
@@ -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")
+38
View File
@@ -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}))
+14
View File
@@ -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"
+55
View File
@@ -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))
+68
View File
@@ -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))
+36
View File
@@ -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"
+24
View File
@@ -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"
+8
View File
@@ -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"
}
@@ -0,0 +1,74 @@
# D3D11 compute-buffer workload
This original fixture submits an unsigned 32-bit addition in a Direct3D 11 compute shader and verifies the GPU output through CPU staging readback. It requires a hardware device at feature level 11.0 and uses no game data.
## Expected output
The shader adds one plus the lane's position within a repeating 16-word sequence. Write an output index as `16b + r` with `0 ≤ r < 16`. Pattern 0 starts its block at `4096 + 65536b`. Pattern 1 starts at `−16 − 65536b`, represented modulo 2³². Each input is its block's base plus `r`. The expected output is the corresponding odd-number progression from base plus 1 to base plus 31, reduced modulo 2³². The C code lists both first-block progressions as constants. Subsequent blocks shift the expected progression by the signed block offset. The block tags distinguish writes whose indices differ by a multiple of 16. The second pattern exercises unsigned wraparound in its first block.
Each pattern runs with counts 0, 1, 63, 64, 65, 127, 128, 129, and 191. A zero count skips dispatch and checks that the entire buffer retains its initial sentinel. The other cases dispatch groups of 64. The structured buffers physically hold 192 words, so an erroneous write from a rounded-up tail would overwrite a sentinel inside the allocated buffer. Every run compares all 192 words, including undispatched slots. The negative control changes only the expected word for pattern 0, count 65, index 64 from `00041001` to `00041000`.
The digest is 32-bit FNV-1a over all 3,456 readback words, each fed as four bytes in little-endian order. Pattern 0 comes first, each pattern uses the count order above, and each buffer is traversed by ascending index. The analytic result is `6ce404b5`. The negative control should give exactly one mismatch with the same digest because it leaves the GPU inputs and work unchanged.
The executable returns 0 for a matching readback, 1 for mismatches, 2 for no feature-level-11.0 hardware device, 3 for another API failure, and 4 for invalid arguments.
## Build and run
Use the external llvm-mingw 20261117 UCRT macOS universal release pinned by the candidate in #384. Its archive SHA-256 is `98d340bbb8d46b09ad6886ffba88bd9d5415e131c316de48e6bd7647377446aa`. Clang and LLD are 23.1.6. The package ships both host slices and the recipe explicitly runs Clang as ARM64. The release includes LLVM's Apache-2.0 license with LLVM exceptions and dependency notices. See the archive's `LICENSE.TXT`. It is a build dependency and is supplied separately.
```sh
tests/conformance/optional/d3d11-compute/build.sh /absolute/path/to/llvm-mingw /absolute/path/to/vkd3d-compiler
```
The second dependency is WineHQ vkd3d-compiler 2.2 with libvkd3d-shader 2.2 (LGPL-2.1-or-later). The WineHQ 2.2 source archive used locally had SHA-256 `6f8cdbfc52e36eb74ab6aff42b1e958c3d9af912ab8f23d16d63711f2bab051b`. Use a native ARM64 build. The recipe compiles HLSL entry `main` to the `cs_5_0` profile in a tokenized DXBC container and embeds the resulting bytes in the executable. The guest gives those bytes directly to `CreateComputeShader`. Neither compiler is bundled or invoked by the guest.
Local compiler build inputs were the WineHQ release, Xcode Command Line Tools, pkgconf 2.5.1, Bison 3.8.2, system Flex, Vulkan-Headers `d4a196d8c84e032d27f999adcea3075517c1c97f` and SPIRV-Headers `3f17b2af6784bfa2c5aa5dbb8e0e74a607dd8b3b`. From the extracted vkd3d source, the local ARM64 build used:
```sh
PKG_CONFIG=/absolute/path/to/pkgconf SONAME_LIBVULKAN=libMoltenVK.dylib \
CPPFLAGS="-I$VULKAN_HEADERS/include -I$SPIRV_HEADERS/include" \
./configure --disable-tests --disable-demos
for grammar in hlsl preproc; do
bison -d -o "libs/vkd3d-shader/$grammar.tab.c" "libs/vkd3d-shader/$grammar.y"
done
make include/private/vkd3d_version.h
make -j2 vkd3d-compiler
```
The Vulkan soname satisfies configure's runtime-library setting for the broader vkd3d project. The compiler target links libvkd3d-shader and does not link Vulkan or MoltenVK. The default guest build output is `artifacts/hybrid-workloads/x86_64/d3d11-compute.exe`.
Use a fresh dedicated Windows 11 64-bit bottle and the evidence-saving runner from #398. The runner's backend selector is observed CrossOver behavior. Record the backend evidence from each run.
```sh
bx-cli run --bottle betterxen-issue-401 --backend dxvk \
--timeout 45 --expect 'PASS cases=' --out artifacts/issue-401/run-records \
-- "$PWD/artifacts/hybrid-workloads/x86_64/d3d11-compute.exe"
bx-cli run --bottle betterxen-issue-401 --backend dxvk \
--timeout 45 --expect 'PASS cases=' --out artifacts/issue-401/run-records \
-- "$PWD/artifacts/hybrid-workloads/x86_64/d3d11-compute.exe" --negative-control
```
The second command should return 1 and report one mismatch. A result without a guest exit code or completed readback is unavailable.
## Local evidence
Workload branch base: `566272082a74d8b45fcec37edd00f4f6703df3ab` (#384). The separate Rust 1.100.0 runner checkout used `e1b6a24a4f37360abb1f5c77bedbfd470cf1c720` (#398's persistence fix on #384). Host was an ARM64 Apple M2 Pro with 16 GiB and macOS 27.3 (26C5035r). CrossOver Preview was 20261111 (27.0.0.41303). The pinned archive checksum matched. Separate source and output directories produced identical DXBC (SHA-256 `af046791dce24119b0452d50cd30f69a2735de649161101cb5d0626625eebee0`) and x86-64 PE32+ executables (SHA-256 `2f92cd68266592039cdc4860a2c3896a15ddabb83dbecd0d1ed928599009095f`).
The default memory guard refused the first request at 49% free. Subsequent local runs used the runner's `--min-start-free 45` option with the default during-run floor. Run records are under ignored `artifacts/issue-401/precompiled-records/`. This is author-side verification. Independent derivation and CrossOver reproduction are pending.
| Requested backend | Evidence in the run record | Normal run | Negative control |
| --- | --- | --- | --- |
| D3DMetal | Inferred from the `AMD Compatibility Mode` adapter | Exit 0, zero mismatches | Exit 1, one mismatch |
| DXVK | DXVK banner and `Apple M2 Pro` adapter | Exit 0, zero mismatches | Exit 1, one mismatch |
All four completed runs read back 3,456 words and matched the independently calculated digest `6ce404b5`. The initial memory refusal was the only unavailable run in the final evidence set. The runner intentionally classifies a negative-control exit 1 as a workload failure.
## References
- [llvm-mingw 20261117 release](https://github.com/mstorsjo/llvm-mingw/releases/tag/20261117)
- [WineHQ vkd3d 2.2 release](https://list.winehq.org/hyperkitty/list/wine-announce%40list.winehq.org/thread/QBVNHPS2PLCJXA67ESIEY3XZP7BV4KRA/)
- [Microsoft compute shader creation and profile example](https://learn.microsoft.com/en-us/windows/win32/direct3d11/direct3d-11-advanced-stages-compute-create)
- [Microsoft structured-buffer resource](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-structuredbuffer)
- [Microsoft thread-group size and dispatch IDs](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-numthreads)
- [Microsoft CopyResource reference](https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11devicecontext-copyresource)
- [Microsoft Map reference](https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11devicecontext-map)
+28
View File
@@ -0,0 +1,28 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
set -eu
toolchain=${1:?usage: build.sh LLVM_MINGW_DIR VKD3D_COMPILER [OUTPUT_DIR]}
shader_compiler=${2:?supply the native vkd3d-compiler 2.2 executable}
src=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
out=${3:-"$src/../../artifacts/hybrid-workloads/x86_64"}
mkdir -p "$out"
version=$(arch -arm64 "$shader_compiler" --version)
case "$version" in
'vkd3d shader compiler version 2.2 using vkd3d-shader 2.2'*) ;;
*) printf 'Expected vkd3d-compiler and vkd3d-shader 2.2, got %s\n' "$version" >&2; exit 1 ;;
esac
# Compile original HLSL to D3D11-compatible shader model 5 tokenized bytecode.
arch -arm64 "$shader_compiler" -x hlsl -b dxbc-tpf -p cs_5_0 -e main \
-o "$out/compute.dxbc" "$src/compute.hlsl"
xxd -i < "$out/compute.dxbc" > "$out/compute_dxbc.inc"
arch -arm64 "$toolchain/bin/x86_64-w64-mingw32-clang" \
-std=c11 -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
-I "$out" "$src/compute.c" -o "$out/d3d11-compute.exe" -ld3d11 -ldxguid
description=$(file -b "$out/d3d11-compute.exe")
echo "$description"
case "$description" in
*PE32+*x86-64*) ;;
*) exit 1 ;;
esac
@@ -0,0 +1,198 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#define COBJMACROS
#include <d3d11.h>
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
static const unsigned char shader_bytecode[] = {
#include "compute_dxbc.inc"
};
enum { GROUP_WIDTH = 64, CAPACITY = 3 * GROUP_WIDTH, PATTERNS = 2 };
static const uint32_t sentinel = UINT32_C(0xcafef00d);
// Authored as base + residue. The second row crosses the 32-bit wrap boundary.
static const uint32_t inputs[PATTERNS][16] = {
{0x1000, 0x1001, 0x1002, 0x1003, 0x1004, 0x1005, 0x1006, 0x1007,
0x1008, 0x1009, 0x100a, 0x100b, 0x100c, 0x100d, 0x100e, 0x100f},
{0xfffffff0, 0xfffffff1, 0xfffffff2, 0xfffffff3,
0xfffffff4, 0xfffffff5, 0xfffffff6, 0xfffffff7,
0xfffffff8, 0xfffffff9, 0xfffffffa, 0xfffffffb,
0xfffffffc, 0xfffffffd, 0xfffffffe, 0xffffffff},
};
static const uint32_t expected[PATTERNS][16] = {
{0x1001, 0x1003, 0x1005, 0x1007, 0x1009, 0x100b, 0x100d, 0x100f,
0x1011, 0x1013, 0x1015, 0x1017, 0x1019, 0x101b, 0x101d, 0x101f},
{0xfffffff1, 0xfffffff3, 0xfffffff5, 0xfffffff7, 0xfffffff9, 0xfffffffb,
0xfffffffd, 0xffffffff, 1, 3, 5, 7, 9, 11, 13, 15},
};
#define CHECK(operation) do { \
HRESULT result = (operation); \
if (FAILED(result)) { \
printf("API_ERROR operation=%s hr=0x%08lx\n", #operation, (unsigned long)result); \
goto cleanup; \
} \
} while (0)
static int run_case(ID3D11Device *device, ID3D11DeviceContext *context,
UINT pattern, UINT count, int negative, uint32_t *digest,
UINT *mismatches) {
uint32_t input[CAPACITY], initial[CAPACITY];
const uint32_t params[4] = {count, 0, 0, 0};
ID3D11Buffer *source = NULL, *destination = NULL, *staging = NULL, *constants = NULL;
ID3D11ShaderResourceView *srv = NULL;
ID3D11UnorderedAccessView *uav = NULL;
int status = 3;
for (UINT i = 0; i < CAPACITY; ++i) {
input[i] = inputs[pattern][i % 16] ^ ((i / 16) << 16);
initial[i] = sentinel;
}
D3D11_BUFFER_DESC desc = {
.ByteWidth = sizeof input, .Usage = D3D11_USAGE_DEFAULT,
.BindFlags = D3D11_BIND_SHADER_RESOURCE,
.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED,
.StructureByteStride = sizeof(uint32_t),
};
D3D11_SUBRESOURCE_DATA data = {.pSysMem = input};
CHECK(ID3D11Device_CreateBuffer(device, &desc, &data, &source));
desc.BindFlags = D3D11_BIND_UNORDERED_ACCESS;
data.pSysMem = initial;
CHECK(ID3D11Device_CreateBuffer(device, &desc, &data, &destination));
desc = (D3D11_BUFFER_DESC){
.ByteWidth = sizeof initial, .Usage = D3D11_USAGE_STAGING,
.CPUAccessFlags = D3D11_CPU_ACCESS_READ,
};
CHECK(ID3D11Device_CreateBuffer(device, &desc, NULL, &staging));
desc = (D3D11_BUFFER_DESC){
.ByteWidth = sizeof params, .Usage = D3D11_USAGE_IMMUTABLE,
.BindFlags = D3D11_BIND_CONSTANT_BUFFER,
};
data.pSysMem = params;
CHECK(ID3D11Device_CreateBuffer(device, &desc, &data, &constants));
D3D11_SHADER_RESOURCE_VIEW_DESC read_view = {
.Format = DXGI_FORMAT_UNKNOWN, .ViewDimension = D3D11_SRV_DIMENSION_BUFFER,
.Buffer = {.NumElements = CAPACITY},
};
D3D11_UNORDERED_ACCESS_VIEW_DESC write_view = {
.Format = DXGI_FORMAT_UNKNOWN, .ViewDimension = D3D11_UAV_DIMENSION_BUFFER,
.Buffer = {.NumElements = CAPACITY},
};
CHECK(ID3D11Device_CreateShaderResourceView(device, (ID3D11Resource *)source, &read_view, &srv));
CHECK(ID3D11Device_CreateUnorderedAccessView(device, (ID3D11Resource *)destination, &write_view, &uav));
if (count) {
ID3D11DeviceContext_CSSetShaderResources(context, 0, 1, &srv);
ID3D11DeviceContext_CSSetUnorderedAccessViews(context, 0, 1, &uav, NULL);
ID3D11DeviceContext_CSSetConstantBuffers(context, 0, 1, &constants);
ID3D11DeviceContext_Dispatch(context, (count + GROUP_WIDTH - 1) / GROUP_WIDTH, 1, 1);
ID3D11ShaderResourceView *no_srv = NULL;
ID3D11UnorderedAccessView *no_uav = NULL;
ID3D11Buffer *no_buffer = NULL;
ID3D11DeviceContext_CSSetShaderResources(context, 0, 1, &no_srv);
ID3D11DeviceContext_CSSetUnorderedAccessViews(context, 0, 1, &no_uav, NULL);
ID3D11DeviceContext_CSSetConstantBuffers(context, 0, 1, &no_buffer);
}
ID3D11DeviceContext_CopyResource(context, (ID3D11Resource *)staging, (ID3D11Resource *)destination);
D3D11_MAPPED_SUBRESOURCE map;
CHECK(ID3D11DeviceContext_Map(context, (ID3D11Resource *)staging, 0, D3D11_MAP_READ, 0, &map));
const uint32_t *words = map.pData;
for (UINT i = 0; i < CAPACITY; ++i) {
uint32_t want = sentinel;
if (i < count) {
want = expected[pattern][i % 16];
// Input tags increase pattern 0 and decrease pattern 1 by whole 65536s.
want += pattern == 0 ? (i / 16) << 16 : 0u - ((i / 16) << 16);
if (negative && pattern == 0 && count == GROUP_WIDTH + 1 && i == GROUP_WIDTH)
want ^= 1u;
}
if (words[i] != want) {
if (*mismatches < 8)
printf("MISMATCH pattern=%u count=%u index=%u expected=%08" PRIx32
" actual=%08" PRIx32 "\n", pattern, count, i, want, words[i]);
++*mismatches;
}
for (unsigned shift = 0; shift < 32; shift += 8) {
*digest ^= (words[i] >> shift) & 0xffu;
*digest *= UINT32_C(16777619);
}
}
ID3D11DeviceContext_Unmap(context, (ID3D11Resource *)staging, 0);
status = 0;
cleanup:
if (uav) ID3D11UnorderedAccessView_Release(uav);
if (srv) ID3D11ShaderResourceView_Release(srv);
if (constants) ID3D11Buffer_Release(constants);
if (staging) ID3D11Buffer_Release(staging);
if (destination) ID3D11Buffer_Release(destination);
if (source) ID3D11Buffer_Release(source);
return status;
}
static void report_adapter(ID3D11Device *device) {
IDXGIDevice *dxgi = NULL;
IDXGIAdapter *adapter = NULL;
DXGI_ADAPTER_DESC desc;
if (SUCCEEDED(ID3D11Device_QueryInterface(device, &IID_IDXGIDevice, (void **)&dxgi))) {
if (SUCCEEDED(IDXGIDevice_GetAdapter(dxgi, &adapter))) {
if (SUCCEEDED(IDXGIAdapter_GetDesc(adapter, &desc)))
printf("adapter=%.127ls vendor=0x%x\n", desc.Description, desc.VendorId);
IDXGIAdapter_Release(adapter);
}
IDXGIDevice_Release(dxgi);
}
}
int main(int argc, char **argv) {
const int negative = argc == 2 && strcmp(argv[1], "--negative-control") == 0;
if (argc != 1 && !negative) {
puts("USAGE d3d11-compute.exe [--negative-control]");
return 4;
}
ID3D11Device *device = NULL;
ID3D11DeviceContext *context = NULL;
const D3D_FEATURE_LEVEL level = D3D_FEATURE_LEVEL_11_0;
HRESULT hr = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &level, 1,
D3D11_SDK_VERSION, &device, NULL, &context);
if (FAILED(hr)) {
printf("NO_DEVICE hr=0x%08lx\n", (unsigned long)hr);
return 2;
}
report_adapter(device);
ID3D11ComputeShader *shader = NULL;
int status = 3;
CHECK(ID3D11Device_CreateComputeShader(device, shader_bytecode,
sizeof shader_bytecode, NULL, &shader));
ID3D11DeviceContext_CSSetShader(context, shader, NULL, 0);
const UINT counts[] = {0, 1, 63, 64, 65, 127, 128, 129, 191};
const UINT count_cases = sizeof counts / sizeof counts[0];
uint32_t digest = UINT32_C(2166136261);
UINT mismatches = 0;
for (UINT pattern = 0; pattern < PATTERNS; ++pattern) {
for (UINT i = 0; i < count_cases; ++i) {
status = run_case(device, context, pattern, counts[i], negative, &digest, &mismatches);
if (status) goto cleanup;
}
}
printf("%s cases=%u words=%u mismatches=%u digest=%08" PRIx32 "\n",
mismatches ? "FAIL" : "PASS", PATTERNS * count_cases,
PATTERNS * count_cases * CAPACITY, mismatches, digest);
status = mismatches ? 1 : 0;
cleanup:
ID3D11DeviceContext_ClearState(context);
if (shader) ID3D11ComputeShader_Release(shader);
ID3D11DeviceContext_Release(context);
ID3D11Device_Release(device);
return status;
}
@@ -0,0 +1,15 @@
// SPDX-License-Identifier: GPL-3.0-or-later
StructuredBuffer<uint> inputWords : register(t0);
RWStructuredBuffer<uint> outputWords : register(u0);
cbuffer Parameters : register(b0)
{
uint count;
};
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID)
{
if (id.x < count)
outputWords[id.x] = inputWords[id.x] + (id.x & 15u) + 1u;
}
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "win-selfcheck-rust"
version = "0.1.0"
@@ -0,0 +1,10 @@
[package]
name = "win-selfcheck-rust"
version = "0.1.0"
edition = "2024"
license = "GPL-3.0-or-later"
publish = false
# Standalone: built for a Windows target by scripts/hybrid/build-windows-workloads.sh, not a
# member of the BetterXen workspace.
[workspace]
@@ -0,0 +1,44 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original BetterXen workload (issue #364): a Rust Windows console program that checks itself.
// Exercises thread-local storage and threads, which the contributor notes in
// https://github.com/MacosPorters/betterxen/blob/54264e23a417e861834ee879f810717385b91f58/docs/research/upstream-integration-audit.md report as the failure point of the plain
// `-gnu` Windows target. Exit 0 means every check passed.
use std::cell::Cell;
use std::sync::atomic::{AtomicU64, Ordering};
use std::thread;
thread_local! { static TLS: Cell<u64> = const { Cell::new(0) }; }
static TOTAL: AtomicU64 = AtomicU64::new(0);
fn main() {
println!("selfcheck-rust arch={} os={}", std::env::consts::ARCH, std::env::consts::OS);
let handles: Vec<_> = (1..=4u64)
.map(|n| {
thread::spawn(move || {
for _ in 0..1000 {
TLS.with(|c| c.set(c.get() + n));
}
let v = TLS.with(Cell::get);
TOTAL.fetch_add(v, Ordering::SeqCst);
v
})
})
.collect();
for (i, h) in handles.into_iter().enumerate() {
let got = h.join().expect("thread panicked");
let want = 1000 * (i as u64 + 1);
if got != want {
println!("FAIL tls thread {i}: got {got}, want {want}");
std::process::exit(1);
}
}
if TOTAL.load(Ordering::SeqCst) != 10_000 {
println!("FAIL total");
std::process::exit(2);
}
if TLS.with(Cell::get) != 0 {
println!("FAIL main-thread TLS was modified by other threads");
std::process::exit(3);
}
println!("PASS");
}
@@ -0,0 +1,5 @@
# SPDX-License-Identifier: GPL-3.0-or-later
add_executable(d3d11-clear d3d11_clear.c)
target_compile_options(d3d11-clear PRIVATE -Wall -Wextra -Werror)
target_link_options(d3d11-clear PRIVATE -Wl,--no-insert-timestamp)
target_link_libraries(d3d11-clear PRIVATE d3d11 dxgi)
@@ -0,0 +1,71 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original BetterXen workload (issue #365, first step): Direct3D 11 clear and readback.
// Creates a hardware device, clears a 64x64 RGBA8 render target to (0.25, 0.5, 0.75, 1.0),
// copies it to a staging texture, maps it, and checks every pixel. Expected bytes by the ideal
// FLOAT->UNORM rule (c*255, add 0.5, drop the fraction): 64, 128, 191, 255. The Direct3D data
// conversion rules also permit a tolerance of 0.6 unit-last-place on the integer side
// (D3D11/D3D12_FLOAT32_TO_INTEGER_TOLERANCE_IN_ULP = 0.6f), so a byte passes when it is
// within 0.6 of c*255. 0.5*255 = 127.5 is an exact tie, so both 127 and 128 are permitted.
// The program prints whether the result matched the ideal exactly. This corrects an earlier
// version that required exact equality, which was stricter than the specification.
// Exit codes: 0 pass, 1 wrong pixel, 2 no device (reported, not a pass), 3 other API failure.
#define COBJMACROS
#include <d3d11.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
// `--negative-control` expects a deliberately wrong colour; the program must then exit 1.
int main(int argc, char **argv) {
const int negative = argc > 1 && !strcmp(argv[1], "--negative-control");
ID3D11Device *dev = NULL;
ID3D11DeviceContext *ctx = NULL;
D3D_FEATURE_LEVEL got;
HRESULT hr = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, NULL, 0,
D3D11_SDK_VERSION, &dev, &got, &ctx);
if (FAILED(hr)) { printf("NO DEVICE hr=0x%08lx\n", (unsigned long)hr); return 2; }
printf("device ok feature_level=0x%x\n", (unsigned)got);
D3D11_TEXTURE2D_DESC d = {0};
d.Width = 64; d.Height = 64; d.MipLevels = 1; d.ArraySize = 1;
d.Format = DXGI_FORMAT_R8G8B8A8_UNORM; d.SampleDesc.Count = 1;
d.Usage = D3D11_USAGE_DEFAULT; d.BindFlags = D3D11_BIND_RENDER_TARGET;
ID3D11Texture2D *rt = NULL, *st = NULL;
if (FAILED(ID3D11Device_CreateTexture2D(dev, &d, NULL, &rt))) { printf("FAIL create rt\n"); return 3; }
d.Usage = D3D11_USAGE_STAGING; d.BindFlags = 0; d.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
if (FAILED(ID3D11Device_CreateTexture2D(dev, &d, NULL, &st))) { printf("FAIL create staging\n"); return 3; }
ID3D11RenderTargetView *rtv = NULL;
if (FAILED(ID3D11Device_CreateRenderTargetView(dev, (ID3D11Resource *)rt, NULL, &rtv))) {
printf("FAIL create rtv\n"); return 3;
}
const float color[4] = {0.25f, 0.5f, 0.75f, 1.0f};
ID3D11DeviceContext_ClearRenderTargetView(ctx, rtv, color);
ID3D11DeviceContext_CopyResource(ctx, (ID3D11Resource *)st, (ID3D11Resource *)rt);
D3D11_MAPPED_SUBRESOURCE m;
if (FAILED(ID3D11DeviceContext_Map(ctx, (ID3D11Resource *)st, 0, D3D11_MAP_READ, 0, &m))) {
printf("FAIL map\n"); return 3;
}
const unsigned char ideal[4] = {64, 128, 191, 255};
const float tol = 0.6f;
int bad = 0, inexact = 0;
for (UINT y = 0; y < 64; y++) {
const unsigned char *row = (const unsigned char *)m.pData + (size_t)y * m.RowPitch;
for (UINT x = 0; x < 64; x++) {
const unsigned char *p = row + x * 4;
int off_ideal = 0, off_tol = 0;
for (int ch = 0; ch < 4; ch++) {
if (p[ch] != ideal[ch] + (negative ? 100 : 0)) off_ideal = 1;
if (fabsf(color[ch] * 255.0f + (negative ? 100.0f : 0.0f) - (float)p[ch]) > tol) off_tol = 1;
}
if (off_ideal) inexact++;
if (off_tol) {
if (bad < 3) printf("pixel (%u,%u) = %u %u %u %u\n", x, y, p[0], p[1], p[2], p[3]);
bad++;
}
}
}
ID3D11DeviceContext_Unmap(ctx, (ID3D11Resource *)st, 0);
if (bad) { printf("FAIL %d wrong pixels\n", bad); return 1; }
printf("PASS 4096 pixels within tolerance; %d differ from the ideal rounding\n", inexact);
return 0;
}
@@ -0,0 +1,5 @@
# SPDX-License-Identifier: GPL-3.0-or-later
add_executable(d3d11-frameloop frameloop.c)
target_compile_options(d3d11-frameloop PRIVATE -Wall -Wextra -Werror)
target_link_options(d3d11-frameloop PRIVATE -Wl,--no-insert-timestamp)
target_link_libraries(d3d11-frameloop PRIVATE d3d11 dxgi dxguid d3dcompiler m)
@@ -0,0 +1,153 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original BetterXen workload (issue #365, #145): Direct3D 11 indexed triangle, shaders,
// offscreen render target and a sustained frame loop with per-frame GPU-completion timing.
//
// Pipeline: HLSL vertex and pixel shaders compiled at run time with D3DCompile, a vertex
// buffer (3 vertices), an index buffer (3 indices), a 640x360 RGBA8 render target, no window
// and no presentation. Each frame clears, draws, issues an event query and waits for it to
// complete; the interval between consecutive completions is printed as `frame_ms <value>`,
// one line per frame, so `betterxen-hybrid frames` can summarise them. This measures
// submit-to-completion of a trivial draw plus synchronisation, NOT presentation or realistic
// rendering cost.
//
// Correctness (read back once after the first frame): pixel (0,0) lies outside the triangle
// and must be the clear colour (0,0,0,255) exactly; the centre pixel must be the triangle
// colour (0.2, 0.4, 0.8, 1.0) within 0.6 of c*255 (the Direct3D float-to-UNORM tolerance).
// Usage: frameloop.exe [--negative-control] [frames] (default 300). Exit 0 pass, 1 wrong pixel, 2 no device,
// 3 other API failure.
#define COBJMACROS
#include <d3d11.h>
#include <d3dcompiler.h>
#include <dxgi.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char *VS =
"struct V { float2 p : POSITION; };\n"
"float4 main(V v) : SV_Position { return float4(v.p, 0, 1); }\n";
static const char *PS =
"float4 main() : SV_Target { return float4(0.2, 0.4, 0.8, 1.0); }\n";
#define CHECK(x, what) do { HRESULT hr_ = (x); if (FAILED(hr_)) { \
printf("FAIL %s hr=0x%08lx\n", what, (unsigned long)hr_); return 3; } } while (0)
static ID3DBlob *compile(const char *src, const char *target) {
ID3DBlob *code = NULL, *err = NULL;
HRESULT hr = D3DCompile(src, strlen(src), NULL, NULL, NULL, "main", target, 0, 0, &code, &err);
if (FAILED(hr)) {
printf("FAIL D3DCompile %s hr=0x%08lx %s\n", target, (unsigned long)hr,
err ? (const char *)ID3D10Blob_GetBufferPointer(err) : "");
return NULL;
}
return code;
}
int main(int argc, char **argv) {
// `--negative-control [frames]` expects a deliberately wrong centre colour and must exit 1.
const int negative = argc > 1 && !strcmp(argv[1], "--negative-control");
int frames = argc > 1 + negative ? atoi(argv[1 + negative]) : 300;
if (frames < 1) frames = 1;
ID3D11Device *dev = NULL;
ID3D11DeviceContext *ctx = NULL;
D3D_FEATURE_LEVEL fl;
HRESULT hr = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, NULL, 0,
D3D11_SDK_VERSION, &dev, &fl, &ctx);
if (FAILED(hr)) { printf("NO DEVICE hr=0x%08lx\n", (unsigned long)hr); return 2; }
printf("device ok feature_level=0x%x\n", (unsigned)fl);
{
IDXGIDevice *dd = NULL; IDXGIAdapter *ad = NULL; DXGI_ADAPTER_DESC desc;
if (SUCCEEDED(ID3D11Device_QueryInterface(dev, &IID_IDXGIDevice, (void **)&dd)) &&
SUCCEEDED(IDXGIDevice_GetAdapter(dd, &ad)) && SUCCEEDED(IDXGIAdapter_GetDesc(ad, &desc))) {
char name[128]; size_t i = 0;
for (; desc.Description[i] && i < 127; i++) name[i] = (char)desc.Description[i];
name[i] = 0;
printf("adapter=%s vendor=0x%x dedicated_vram_mb=%u\n", name, desc.VendorId,
(unsigned)(desc.DedicatedVideoMemory >> 20));
}
}
ID3DBlob *vsb = compile(VS, "vs_4_0"), *psb = compile(PS, "ps_4_0");
if (!vsb || !psb) return 3;
ID3D11VertexShader *vs; ID3D11PixelShader *ps; ID3D11InputLayout *il;
CHECK(ID3D11Device_CreateVertexShader(dev, ID3D10Blob_GetBufferPointer(vsb), ID3D10Blob_GetBufferSize(vsb), NULL, &vs), "vs");
CHECK(ID3D11Device_CreatePixelShader(dev, ID3D10Blob_GetBufferPointer(psb), ID3D10Blob_GetBufferSize(psb), NULL, &ps), "ps");
D3D11_INPUT_ELEMENT_DESC ied = {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0};
CHECK(ID3D11Device_CreateInputLayout(dev, &ied, 1, ID3D10Blob_GetBufferPointer(vsb), ID3D10Blob_GetBufferSize(vsb), &il), "layout");
// A triangle that covers the centre of the target and not the (0,0) corner pixel.
const float verts[6] = {-0.5f, -0.5f, 0.0f, 0.6f, 0.5f, -0.5f};
const unsigned short idx[3] = {0, 1, 2}; // clockwise in clip space (y up) = front face; D3D11 culls back faces by default
ID3D11Buffer *vb, *ib;
D3D11_BUFFER_DESC bd = {0}; D3D11_SUBRESOURCE_DATA sd = {0};
bd.ByteWidth = sizeof verts; bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; sd.pSysMem = verts;
CHECK(ID3D11Device_CreateBuffer(dev, &bd, &sd, &vb), "vb");
bd.ByteWidth = sizeof idx; bd.BindFlags = D3D11_BIND_INDEX_BUFFER; sd.pSysMem = idx;
CHECK(ID3D11Device_CreateBuffer(dev, &bd, &sd, &ib), "ib");
const UINT W = 640, H = 360;
D3D11_TEXTURE2D_DESC td = {0};
td.Width = W; td.Height = H; td.MipLevels = 1; td.ArraySize = 1;
td.Format = DXGI_FORMAT_R8G8B8A8_UNORM; td.SampleDesc.Count = 1;
td.Usage = D3D11_USAGE_DEFAULT; td.BindFlags = D3D11_BIND_RENDER_TARGET;
ID3D11Texture2D *rt, *st; ID3D11RenderTargetView *rtv;
CHECK(ID3D11Device_CreateTexture2D(dev, &td, NULL, &rt), "rt");
td.Usage = D3D11_USAGE_STAGING; td.BindFlags = 0; td.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
CHECK(ID3D11Device_CreateTexture2D(dev, &td, NULL, &st), "staging");
CHECK(ID3D11Device_CreateRenderTargetView(dev, (ID3D11Resource *)rt, NULL, &rtv), "rtv");
D3D11_QUERY_DESC qd = {D3D11_QUERY_EVENT, 0};
ID3D11Query *q; CHECK(ID3D11Device_CreateQuery(dev, &qd, &q), "query");
D3D11_VIEWPORT vp = {0, 0, (float)W, (float)H, 0, 1};
const float clear[4] = {0, 0, 0, 1};
UINT stride = 8, off = 0;
LARGE_INTEGER freq, prev, now, flushed; QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&flushed);
QueryPerformanceCounter(&prev);
for (int f = 0; f < frames; f++) {
ID3D11DeviceContext_OMSetRenderTargets(ctx, 1, &rtv, NULL);
ID3D11DeviceContext_RSSetViewports(ctx, 1, &vp);
ID3D11DeviceContext_ClearRenderTargetView(ctx, rtv, clear);
ID3D11DeviceContext_IASetInputLayout(ctx, il);
ID3D11DeviceContext_IASetPrimitiveTopology(ctx, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
ID3D11DeviceContext_IASetVertexBuffers(ctx, 0, 1, &vb, &stride, &off);
ID3D11DeviceContext_IASetIndexBuffer(ctx, ib, DXGI_FORMAT_R16_UINT, 0);
ID3D11DeviceContext_VSSetShader(ctx, vs, NULL, 0);
ID3D11DeviceContext_PSSetShader(ctx, ps, NULL, 0);
ID3D11DeviceContext_DrawIndexed(ctx, 3, 0, 0);
ID3D11DeviceContext_End(ctx, (ID3D11Asynchronous *)q);
ID3D11DeviceContext_Flush(ctx);
BOOL done = FALSE;
for (;;) { // busy-wait (keeps one core fully used); a failed query ends the run at once
HRESULT qr = ID3D11DeviceContext_GetData(ctx, (ID3D11Asynchronous *)q, &done, sizeof done, 0);
if (FAILED(qr)) { printf("FAIL event query hr=0x%08lx\n", (unsigned long)qr); return 3; }
if (qr == S_OK && done) break;
}
QueryPerformanceCounter(&now);
printf("frame_ms %.4f\n", (double)(now.QuadPart - prev.QuadPart) * 1000.0 / (double)freq.QuadPart);
if (now.QuadPart - flushed.QuadPart >= freq.QuadPart) { fflush(stdout); flushed = now; } // progress once a second
QueryPerformanceCounter(&prev); // after the print, so that its cost is in no interval
if (f == 0) {
ID3D11DeviceContext_CopyResource(ctx, (ID3D11Resource *)st, (ID3D11Resource *)rt);
D3D11_MAPPED_SUBRESOURCE m;
CHECK(ID3D11DeviceContext_Map(ctx, (ID3D11Resource *)st, 0, D3D11_MAP_READ, 0, &m), "map");
const unsigned char *c = (const unsigned char *)m.pData;
const unsigned char *k = c + (size_t)(H / 2) * m.RowPitch + (W / 2) * 4;
const float want[4] = {0.2f, 0.4f, 0.8f, 1.0f};
int bad = 0;
if (c[0] != 0 || c[1] != 0 || c[2] != 0 || c[3] != 255) {
printf("FAIL corner pixel = %u %u %u %u, want 0 0 0 255\n", c[0], c[1], c[2], c[3]); bad = 1;
}
for (int ch = 0; ch < 4; ch++)
if (fabsf(want[ch] * 255.0f + (negative ? 100.0f : 0.0f) - (float)k[ch]) > 0.6f) bad = 1;
printf("centre pixel = %u %u %u %u\n", k[0], k[1], k[2], k[3]);
ID3D11DeviceContext_Unmap(ctx, (ID3D11Resource *)st, 0);
if (bad) { printf("FAIL pixels\n"); return 1; }
QueryPerformanceCounter(&prev);
}
}
printf("PASS frames=%d\n", frames);
return 0;
}
@@ -0,0 +1,5 @@
# SPDX-License-Identifier: GPL-3.0-or-later
add_executable(d3d11-integrated integrated.c)
target_compile_options(d3d11-integrated PRIVATE -Wall -Wextra -Werror)
target_link_options(d3d11-integrated PRIVATE -Wl,--no-insert-timestamp)
target_link_libraries(d3d11-integrated PRIVATE d3d11 dxgi dxguid d3dcompiler psapi user32)
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Build the integrated workload with the pinned llvm-mingw (https://github.com/MacosPorters/betterxen/blob/54264e23a417e861834ee879f810717385b91f58/docs/research/hybrid-toolchain.md).
# tests/conformance/test_d3d11_integrated/build.sh <llvm-mingw-dir> [output-dir]
set -eu
TC=${1:?usage: build.sh LLVM_MINGW_DIR [OUTPUT_DIR]}
src=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
out=${2:-"$src/../../../artifacts/hybrid-workloads/x86_64"}
mkdir -p "$out"
"$TC/bin/x86_64-w64-mingw32-clang" -std=c11 -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
-o "$out/d3d11-integrated.exe" "$src/integrated.c" \
-ld3d11 -ldxgi -ldxguid -ld3dcompiler -lpsapi -luser32
description=$(file -b "$out/d3d11-integrated.exe")
echo "$description"
case "$description" in
*PE32+*x86-64*) ;;
*) exit 1 ;;
esac
+165
View File
@@ -0,0 +1,165 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Observe the integrated workload's window from macOS and compare what is on screen.
Runs the workload through `betterxen-hybrid run` with a hold period, finds its window with
CGWindowList, captures only that window with `screencapture -l`, converts the capture to sRGB
and samples the client area on a grid. This is evidence from outside the Windows program that
the final frame reached the macOS compositor; the program's own read-back cannot show that.
Needs the Screen Recording permission, `swift` and a logged-in GUI session. A missing
permission or window is a failure, never a pass.
usage: check_window.py RUNNER BOTTLE EXE [--fault NAME] [--keep PNG]
"""
import argparse
import struct
import subprocess
import sys
import tempfile
import time
import uuid
from pathlib import Path
FRAMES = 128
WINDOW_ID_SWIFT = """
import CoreGraphics
let all = CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]] ?? []
for w in all where (w[kCGWindowName as String] as? String) == "%s" {
print(w[kCGWindowNumber as String]!)
break
}
"""
TEX_A = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)]
TEX_B = [(255, 255, 0), (0, 255, 255), (255, 0, 255), (128, 128, 128)]
def expected(x, y, first_frame=False):
"""Final frame after FRAMES frames and the scripted input (quad B moved by +16, +32)."""
if y < 16:
marker = 1 if first_frame else FRAMES
return (marker & 255, marker >> 8, 77)
bx, by = (96, 96) if first_frame else (96 + 16, 96 + 32)
colour = None
if bx <= x < bx + 128 and by <= y < by + 128:
colour = TEX_B[(y - by) // 64 * 2 + (x - bx) // 64]
elif 32 <= x < 160 and 32 <= y < 160:
colour = TEX_A[(y - 32) // 64 * 2 + (x - 32) // 64]
if colour is None:
return (0, 0, 0)
r, g, b = colour
return (b, r, g)
def exists_off_screen(scratch, title):
"""True when macOS knows the window but is not showing it (another Space, minimised)."""
script = scratch / "window_any.swift"
script.write_text((WINDOW_ID_SWIFT % title).replace("[.optionOnScreenOnly]", "[.optionAll]"))
found = subprocess.run(["swift", str(script)], capture_output=True, text=True).stdout.strip()
return found.isdigit()
def read_bmp(path):
data = path.read_bytes()
if data[:2] != b"BM":
raise ValueError("not a BMP")
offset = struct.unpack_from("<I", data, 10)[0]
width, height = struct.unpack_from("<ii", data, 18)
bpp = struct.unpack_from("<H", data, 28)[0]
if bpp not in (24, 32):
raise ValueError(f"unsupported BMP depth {bpp}")
step = bpp // 8
stride = (width * step + 3) & ~3
def pixel(x, y):
row = height - 1 - y if height > 0 else y
at = offset + row * stride + x * step
return (data[at + 2], data[at + 1], data[at])
return width, abs(height), pixel
def compare(png, scratch, first_frame=False):
"""Return (samples, mismatches, first mismatch) for one capture."""
bmp = scratch / "capture.bmp"
subprocess.run(["/usr/bin/sips", "--matchTo", "/System/Library/ColorSync/Profiles/sRGB Profile.icc",
"-s", "format", "bmp", str(png), "--out", str(bmp)],
check=True, capture_output=True)
width, height, pixel = read_bmp(bmp)
scale = width / 256
top = height - round(256 * scale) # the title bar is above the client area
if scale < 1 or top < 0:
raise ValueError(f"unexpected capture size {width}x{height}")
samples, bad, first = 0, 0, None
for y in range(4, 256, 8):
for x in range(4, 256, 8):
if y > 236 and (x < 20 or x > 236):
continue # rounded window corners
got = pixel(int((x + 0.5) * scale), top + int((y + 0.5) * scale))
want = expected(x, y, first_frame)
samples += 1
if any(abs(g - w) > 6 for g, w in zip(got, want)):
bad += 1
first = first or (x, y, got, want)
return samples, bad, first
def main():
p = argparse.ArgumentParser()
p.add_argument("runner")
p.add_argument("bottle")
p.add_argument("exe")
# only faults that change the rendered image are meaningful here; "color" corrupts the
# program's expectation and leaves the screen correct
p.add_argument("--fault", choices=["blank", "depth", "stale"])
p.add_argument("--keep")
p.add_argument("--first-frame", action="store_true")
a = p.parse_args()
with tempfile.TemporaryDirectory() as tmp:
scratch = Path(tmp)
script = scratch / "window_id.swift"
title = "BetterXen capture " + uuid.uuid4().hex
script.write_text(WINDOW_ID_SWIFT % title)
workload = [a.exe, "--frames", str(FRAMES), "--hold-ms", "12000", "--window-title", title]
if a.first_frame:
workload = [a.exe, "--frames", str(FRAMES), "--hold-first-ms", "12000", "--window-title", title]
if a.fault:
workload += ["--fault", a.fault]
log = open(scratch / "run.json", "w+")
run = subprocess.Popen([a.runner, "run", "--bottle", a.bottle, "--timeout", "90", "--"] + workload,
stdout=log, stderr=subprocess.DEVNULL)
result, off_screen = None, False
deadline = time.time() + 60
while time.time() < deadline and run.poll() is None:
wid = subprocess.run(["swift", str(script)], capture_output=True, text=True).stdout.strip()
if wid.isdigit():
png = scratch / "window.png"
if subprocess.run(["/usr/sbin/screencapture", "-x", "-o", "-l" + wid, str(png)],
capture_output=True).returncode == 0 and png.exists():
result = compare(png, scratch, a.first_frame)
if a.keep:
Path(a.keep).write_bytes(png.read_bytes())
if result[1] == 0:
break
elif result is None and not off_screen:
off_screen = exists_off_screen(scratch, title)
time.sleep(0.5)
run.wait(timeout=120)
if result is None and off_screen:
print("FAIL window: the window exists but is not on the active Space; leave a desktop "
"(not a full-screen app) frontmost and rerun")
return 1
if result is None:
print("FAIL window: no window was captured (permission, GUI session or window missing)")
return 1
samples, bad, first = result
if bad:
print(f"FAIL window: {bad} of {samples} samples differ, first (x, y, got, want) = {first}")
return 1
which = "first" if a.first_frame else "final"
print(f"PASS window: {samples} of {samples} on-screen samples match the expected {which} frame")
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,750 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original BetterXen workload (issue #365): one Windows program that exercises runtime
// services and a presenting Direct3D 11 pipeline together, and verifies its own output.
//
// It is meant to be launched through `betterxen-hybrid run`. Every stage prints one line
// gate <name> pass|FAIL <detail>
// and the final line is `PASS integrated ...` only if every stage passed.
//
// Rendering, per frame:
// pass 1 two textured quads into an offscreen target with a depth buffer. The near quad B
// is drawn FIRST, so the far quad A is visible in the overlap only if depth is
// ignored. Arrow keys move quad B in 16-pixel steps.
// pass 2 a compute shader rotates the colour channels (r,g,b) -> (b,r,g) into a UAV and
// writes a 16-row band that encodes the frame number produced by a second thread.
// pass 3 a full-screen triangle copies that texture to the swapchain back buffer.
// The back buffer is read back before Present and compared, pixel by pixel and with zero
// tolerance, with an image computed here on the CPU from the authored texels and rectangles.
// All colour channels are 0, 128, 255 or an integer/255 value, so no rounding is involved.
//
// Limits of what this shows: the read-back proves the content handed to Present, and Present
// returning success proves the call was accepted. Neither proves what reached the screen.
// Input is delivered with PostMessage inside the Windows environment; it does not test the
// macOS keyboard path unless a person runs `--interactive`.
//
// usage: integrated.exe [--frames N] [--verify-every N] [--vsync] [--interactive]
// [--hold-ms N] [--max-growth-mb N]
// [--fault color|blank|stale|input|depth|crash|hang]
// crash and hang are for testing the supervisor: they happen after the first verified frame.
// Exit: 0 pass, 1 a verification failed, 2 no graphics device, 3 an API call failed.
#define COBJMACROS
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <psapi.h>
#include <d3d11.h>
#include <d3dcompiler.h>
#include <dxgi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define W 256
#define H 256
#define BAND 16
#define STEP 16
#define WORKERS 4
#define RELEASE(p, vt) do { if (p) { vt##_Release(p); (p) = NULL; } } while (0)
static int failures;
static LARGE_INTEGER qpc_freq, qpc_start;
static double now_ms(void) {
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return (double)(t.QuadPart - qpc_start.QuadPart) * 1000.0 / (double)qpc_freq.QuadPart;
}
static void gate(const char *name, int ok, const char *detail) {
printf("gate %s %s %s t_ms=%.1f\n", name, ok ? "pass" : "FAIL", detail, now_ms());
if (!ok) failures++;
}
#define API(x, what) do { HRESULT hr_ = (x); if (FAILED(hr_)) { \
printf("FAIL api %s hr=0x%08lx\n", what, (unsigned long)hr_); exit(3); } } while (0)
#define WIN(x, what) do { if (!(x)) { \
printf("FAIL api %s error=%lu\n", what, (unsigned long)GetLastError()); exit(3); } } while (0)
/* ---- runtime services ------------------------------------------------------------------ */
static DWORD tls_slot;
static CRITICAL_SECTION lock;
static volatile LONG interlocked_total;
static unsigned long long locked_total;
static DWORD WINAPI worker(LPVOID arg) {
const unsigned id = (unsigned)(uintptr_t)arg;
TlsSetValue(tls_slot, (LPVOID)(uintptr_t)(id + 1));
unsigned long long local = 0;
for (unsigned i = 1; i <= 10000; i++) {
local += i;
InterlockedIncrement(&interlocked_total);
Sleep(0);
}
EnterCriticalSection(&lock);
locked_total += local * (uintptr_t)TlsGetValue(tls_slot);
LeaveCriticalSection(&lock);
return (uintptr_t)TlsGetValue(tls_slot) == id + 1 ? 0 : 1;
}
static void check_threads(void) {
HANDLE t[WORKERS];
InitializeCriticalSection(&lock);
tls_slot = TlsAlloc();
WIN(tls_slot != TLS_OUT_OF_INDEXES, "TlsAlloc");
for (unsigned i = 0; i < WORKERS; i++) {
t[i] = CreateThread(NULL, 0, worker, (LPVOID)(uintptr_t)i, 0, NULL);
WIN(t[i], "CreateThread");
}
int ok = WaitForMultipleObjects(WORKERS, t, TRUE, 60000) == WAIT_OBJECT_0;
for (unsigned i = 0; i < WORKERS; i++) {
DWORD code = 99;
ok = ok && GetExitCodeThread(t[i], &code) && code == 0;
CloseHandle(t[i]);
}
/* each worker sums 1..10000 = 50005000, weighted by id+1: 1+2+3+4 = 10 */
ok = ok && locked_total == 500050000ULL && interlocked_total == WORKERS * 10000;
TlsFree(tls_slot);
DeleteCriticalSection(&lock);
gate("runtime.threads", ok, "workers=4 tls critical_section interlocked wait");
}
static volatile LONG faults_seen;
static unsigned char *fault_page;
static LONG CALLBACK on_fault(EXCEPTION_POINTERS *e) {
const EXCEPTION_RECORD *r = e->ExceptionRecord;
if (r->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && r->NumberParameters >= 2 &&
r->ExceptionInformation[0] == 1 && r->ExceptionInformation[1] == (ULONG_PTR)fault_page) {
DWORD old;
InterlockedIncrement(&faults_seen);
if (VirtualProtect(fault_page, 4096, PAGE_READWRITE, &old)) return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
static void check_memory(void) {
const size_t n = 16u << 20;
unsigned char *p = VirtualAlloc(NULL, n, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
WIN(p, "VirtualAlloc");
for (size_t i = 0; i < n; i += 997) p[i] = (unsigned char)(i * 31);
int ok = 1;
for (size_t i = 0; i < n; i += 997) ok = ok && p[i] == (unsigned char)(i * 31);
MEMORY_BASIC_INFORMATION mi;
DWORD old = 0;
ok = ok && VirtualProtect(p, 4096, PAGE_READONLY, &old) && old == PAGE_READWRITE;
ok = ok && VirtualQuery(p, &mi, sizeof mi) == sizeof mi && mi.Protect == PAGE_READONLY;
gate("runtime.memory", ok, "alloc=16MiB protect query");
fault_page = p;
PVOID h = AddVectoredExceptionHandler(1, on_fault);
WIN(h, "AddVectoredExceptionHandler");
*(volatile unsigned char *)p = 0x5a; /* faults once, handler makes the page writable */
const int caught = faults_seen == 1 && p[0] == 0x5a;
RemoveVectoredExceptionHandler(h);
gate("runtime.exceptions", caught, "write to read-only page handled and resumed");
VirtualFree(p, 0, MEM_RELEASE);
}
static void check_time(void) {
const double a = now_ms();
const ULONGLONG ta = GetTickCount64();
Sleep(50);
const double d = now_ms() - a;
const ULONGLONG td = GetTickCount64() - ta;
char msg[96];
snprintf(msg, sizeof msg, "sleep=50ms qpc=%.1fms tick=%llums", d, td);
/* timer granularity may shorten by a tick; a loaded host may lengthen a lot */
gate("runtime.time", d >= 45.0 && d < 5000.0 && td >= 30, msg);
}
static void check_files(void) {
char tmp[MAX_PATH], dir[MAX_PATH + 64], a[MAX_PATH + 72], b[MAX_PATH + 72];
DWORD length = GetTempPathA(sizeof tmp, tmp);
WIN(length > 0 && length < sizeof tmp, "GetTempPath within buffer");
int written = snprintf(dir, sizeof dir, "%sbx-integrated-%lu", tmp, (unsigned long)GetCurrentProcessId());
WIN(written > 0 && (size_t)written < sizeof dir, "temporary directory path within buffer");
WIN(CreateDirectoryA(dir, NULL), "CreateDirectory");
snprintf(a, sizeof a, "%s\\a.bin", dir);
snprintf(b, sizeof b, "%s\\b.bin", dir);
static unsigned char out[65536], in[65536];
for (size_t i = 0; i < sizeof out; i++) out[i] = (unsigned char)(i ^ (i >> 7));
DWORD n = 0;
HANDLE f = CreateFileA(a, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
WIN(f != INVALID_HANDLE_VALUE, "CreateFile write");
int ok = WriteFile(f, out, sizeof out, &n, NULL) && n == sizeof out && FlushFileBuffers(f);
CloseHandle(f);
ok = ok && MoveFileA(a, b) && GetFileAttributesA(a) == INVALID_FILE_ATTRIBUTES;
f = CreateFileA(b, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
ok = ok && f != INVALID_HANDLE_VALUE;
if (f != INVALID_HANDLE_VALUE) {
LARGE_INTEGER pos = {.QuadPart = 4096};
ok = ok && ReadFile(f, in, sizeof in, &n, NULL) && n == sizeof in && !memcmp(in, out, sizeof in);
ok = ok && SetFilePointerEx(f, pos, NULL, FILE_BEGIN) && ReadFile(f, in, 16, &n, NULL) &&
n == 16 && !memcmp(in, out + 4096, 16);
CloseHandle(f);
}
ok = DeleteFileA(b) && ok;
ok = RemoveDirectoryA(dir) && ok;
gate("runtime.files", ok, "create write flush rename read seek delete in GetTempPath");
}
/* ---- window, input and the frame producer thread --------------------------------------- */
static int off_x, off_y, keys_seen, quit_requested;
static LRESULT CALLBACK wndproc(HWND h, UINT m, WPARAM w, LPARAM l) {
if (m == WM_KEYDOWN) {
if (w == VK_ESCAPE) quit_requested = 1;
else {
int dx = w == VK_RIGHT ? STEP : w == VK_LEFT ? -STEP : 0;
int dy = w == VK_DOWN ? STEP : w == VK_UP ? -STEP : 0;
if (dx || dy) {
keys_seen++;
off_x += dx;
off_y += dy;
if (off_x < -64) off_x = -64;
if (off_x > 32) off_x = 32;
if (off_y < -64) off_y = -64;
if (off_y > 32) off_y = 32;
}
}
return 0;
}
if (m == WM_CLOSE) { quit_requested = 1; return 0; }
return DefWindowProcA(h, m, w, l);
}
static void pump(void) {
MSG msg;
while (PeekMessageA(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessageA(&msg);
}
}
static HANDLE ev_request, ev_ready;
static volatile LONG producer_stop;
static unsigned requested_frame, produced_value;
static DWORD WINAPI producer(LPVOID unused) {
(void)unused;
for (;;) {
if (WaitForSingleObject(ev_request, INFINITE) != WAIT_OBJECT_0) return 1;
if (producer_stop) return 0;
produced_value = (requested_frame + 1) & 0xffff; /* never 0, so a stale 0 is visible */
SetEvent(ev_ready);
}
}
/* ---- expected image (CPU, independent of the shaders) ---------------------------------- */
static const unsigned char TEX_A[4][4] = {
{255, 0, 0, 255}, {0, 255, 0, 255}, {0, 0, 255, 255}, {255, 255, 255, 255}};
static const unsigned char TEX_B[4][4] = {
{255, 255, 0, 255}, {0, 255, 255, 255}, {255, 0, 255, 255}, {128, 128, 128, 255}};
static void expected_pixel(int x, int y, unsigned marker, int bx, int by, int wrong, unsigned char out[4]) {
if (y < BAND) {
out[0] = (unsigned char)(marker & 255);
out[1] = (unsigned char)(marker >> 8);
out[2] = 77;
out[3] = 255;
return;
}
const unsigned char *c = NULL;
/* quad B is nearer, so it wins wherever it covers the pixel */
if (x >= bx && x < bx + 128 && y >= by && y < by + 128)
c = TEX_B[((y - by) / 64) * 2 + (x - bx) / 64];
else if (x >= 32 && x < 160 && y >= 32 && y < 160)
c = TEX_A[((y - 32) / 64) * 2 + (x - 32) / 64];
out[0] = c ? c[2] : 0;
out[1] = c ? c[0] : 0;
out[2] = c ? c[1] : 0;
out[3] = 255;
if (wrong && c == TEX_A[0]) out[0] ^= 255; /* negative control: one texel region */
}
/* ---- Direct3D -------------------------------------------------------------------------- */
static const char *HLSL =
"cbuffer C : register(b0) { float2 offset; uint marker; uint pad; };\n"
"Texture2D tex : register(t0); SamplerState smp : register(s0);\n"
"struct VI { float3 p : POSITION; float2 uv : TEXCOORD; };\n"
"struct VO { float4 p : SV_Position; float2 uv : TEXCOORD; };\n"
"VO vs_quad(VI v) { VO o; o.p = float4(v.p.xy + offset, v.p.z, 1); o.uv = v.uv; return o; }\n"
"float4 ps_quad(VO i) : SV_Target { return tex.Sample(smp, i.uv); }\n"
"float4 vs_full(uint id : SV_VertexID) : SV_Position {\n"
" float2 uv = float2((id << 1) & 2, id & 2);\n"
" return float4(uv * float2(2, -2) + float2(-1, 1), 0, 1); }\n"
"float4 ps_full(float4 p : SV_Position) : SV_Target { return tex.Load(int3(p.xy, 0)); }\n"
"RWTexture2D<unorm float4> dst : register(u0);\n"
"[numthreads(8, 8, 1)] void cs_main(uint3 id : SV_DispatchThreadID) {\n"
" if (id.y < 16) { dst[id.xy] = float4((marker & 255) / 255.0, (marker >> 8) / 255.0, 77 / 255.0, 1); return; }\n"
" float4 c = tex.Load(int3(id.xy, 0));\n"
" dst[id.xy] = float4(c.b, c.r, c.g, 1); }\n";
static ID3DBlob *compile(const char *entry, const char *target) {
ID3DBlob *code = NULL, *err = NULL;
HRESULT hr = D3DCompile(HLSL, strlen(HLSL), NULL, NULL, NULL, entry, target, 0, 0, &code, &err);
if (FAILED(hr)) {
printf("FAIL api D3DCompile %s hr=0x%08lx %s\n", entry, (unsigned long)hr,
err ? (const char *)ID3D10Blob_GetBufferPointer(err) : "");
exit(3);
}
if (err) ID3D10Blob_Release(err);
return code;
}
typedef struct { float x, y, z, u, v; } Vertex;
typedef struct { float ox, oy; unsigned marker, pad; } Constants;
static void quad(Vertex *v, int x0, int y0, float z) {
const float l = x0 / 128.0f - 1.0f, r = (x0 + 128) / 128.0f - 1.0f;
const float t = 1.0f - y0 / 128.0f, b = 1.0f - (y0 + 128) / 128.0f;
v[0] = (Vertex){l, t, z, 0, 0};
v[1] = (Vertex){r, t, z, 1, 0};
v[2] = (Vertex){l, b, z, 0, 1};
v[3] = (Vertex){r, b, z, 1, 1};
}
/* Working set in MiB. Wine on macOS (CrossOver 26.3) returns PrivateUsage = 0 and an implausible
* PagefileUsage, so only the working set is used; a zero reading is "unavailable", never "no growth". */
static double working_set_mb(void) {
PROCESS_MEMORY_COUNTERS m;
memset(&m, 0, sizeof m);
if (!GetProcessMemoryInfo(GetCurrentProcess(), &m, sizeof m) || !m.WorkingSetSize) return -1.0;
return (double)m.WorkingSetSize / (1024.0 * 1024.0);
}
static ID3D11Texture2D *texture(ID3D11Device *dev, UINT w, UINT h, DXGI_FORMAT fmt, UINT bind,
D3D11_USAGE usage, UINT cpu, const void *init) {
D3D11_TEXTURE2D_DESC d = {.Width = w, .Height = h, .MipLevels = 1, .ArraySize = 1, .Format = fmt,
.SampleDesc = {1, 0}, .Usage = usage, .BindFlags = bind,
.CPUAccessFlags = cpu};
D3D11_SUBRESOURCE_DATA s = {.pSysMem = init, .SysMemPitch = w * 4};
ID3D11Texture2D *t = NULL;
API(ID3D11Device_CreateTexture2D(dev, &d, init ? &s : NULL, &t), "CreateTexture2D");
return t;
}
/* Four independent BC1 blocks: endpoint 0 is red, green, blue, white in RGB565;
all sixteen indices are zero. Thus an 8x8 point-sampled texture has precisely
the same quadrant colours as the original uncompressed 2x2 TEX_A. No encoder
or decoder supplies these expectations. Only exact endpoints are tested.
https://learn.microsoft.com/windows/win32/direct3d10/d3d10-graphics-programming-guide-resources-block-compression */
static ID3D11Texture2D *bc1_texture(ID3D11Device *dev, int corrupt) {
unsigned char blocks[32] = {
0x00,0xf8,0,0,0,0,0,0, 0xe0,0x07,0,0,0,0,0,0,
0x1f,0x00,0,0,0,0,0,0, 0xff,0xff,0,0,0,0,0,0};
if (corrupt) { blocks[0]=0xe0; blocks[1]=0x07; } /* red becomes green */
D3D11_TEXTURE2D_DESC d = {.Width=8,.Height=8,.MipLevels=1,.ArraySize=1,.Format=DXGI_FORMAT_BC1_UNORM,
.SampleDesc={1,0},.Usage=D3D11_USAGE_IMMUTABLE,.BindFlags=D3D11_BIND_SHADER_RESOURCE};
D3D11_SUBRESOURCE_DATA initial = {.pSysMem=blocks,.SysMemPitch=16,.SysMemSlicePitch=32};
ID3D11Texture2D *result=NULL;
API(ID3D11Device_CreateTexture2D(dev,&d,&initial,&result),"BC1 texture");
return result;
}
/* Create, fill, copy, read back and release resources; returns 1 if the contents survived. */
static int churn(ID3D11Device *dev, ID3D11DeviceContext *ctx, unsigned seed) {
static unsigned data[256 * 256];
for (unsigned i = 0; i < 256 * 256; i++) data[i] = i * 2654435761u + seed;
ID3D11Texture2D *src = texture(dev, 256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D11_BIND_SHADER_RESOURCE,
D3D11_USAGE_DEFAULT, 0, data);
ID3D11Texture2D *dst = texture(dev, 256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D11_USAGE_STAGING,
D3D11_CPU_ACCESS_READ, NULL);
ID3D11DeviceContext_CopyResource(ctx, (ID3D11Resource *)dst, (ID3D11Resource *)src);
D3D11_MAPPED_SUBRESOURCE m;
API(ID3D11DeviceContext_Map(ctx, (ID3D11Resource *)dst, 0, D3D11_MAP_READ, 0, &m), "Map churn");
int ok = 1;
for (unsigned y = 0; y < 256; y++)
ok = ok && !memcmp((const char *)m.pData + (size_t)y * m.RowPitch, data + y * 256, 1024);
ID3D11DeviceContext_Unmap(ctx, (ID3D11Resource *)dst, 0);
ID3D11Texture2D_Release(src);
ID3D11Texture2D_Release(dst);
return ok;
}
int main(int argc, char **argv) {
int frames = 600, verify_every = 30, vsync = 0, interactive = 0, hold_ms = 0, max_growth = 64, bc1 = 0, hold_first_ms = 0;
const char *fault = "";
const char *window_title = "BetterXen integrated workload";
setvbuf(stdout, NULL, _IONBF, 0); /* the supervisor detects stalls from output growth */
QueryPerformanceFrequency(&qpc_freq);
QueryPerformanceCounter(&qpc_start);
for (int i = 1; i < argc; i++) {
const char *a = argv[i], *v = i + 1 < argc ? argv[i + 1] : NULL;
if (!strcmp(a, "--vsync")) vsync = 1;
else if (!strcmp(a, "--interactive")) interactive = 1;
else if (!strcmp(a, "--bc1")) bc1 = 1;
else if (!strcmp(a, "--frames") && v) frames = atoi(v), i++;
else if (!strcmp(a, "--verify-every") && v) verify_every = atoi(v), i++;
else if (!strcmp(a, "--hold-ms") && v) hold_ms = atoi(v), i++;
else if (!strcmp(a, "--hold-first-ms") && v) hold_first_ms = atoi(v), i++;
else if (!strcmp(a, "--window-title") && v) window_title = v, i++;
else if (!strcmp(a, "--max-growth-mb") && v) max_growth = atoi(v), i++;
else if (!strcmp(a, "--fault") && v &&
(!strcmp(v, "color") || !strcmp(v, "blank") || !strcmp(v, "stale") ||
!strcmp(v, "input") || !strcmp(v, "depth") || !strcmp(v, "crash") || !strcmp(v, "hang") || !strcmp(v,"bc1")))
fault = v, i++;
else { printf("FAIL usage: unknown or incomplete argument %s\n", a); return 3; }
}
if (frames < 64 || verify_every < 1) { printf("FAIL usage: --frames >= 64, --verify-every >= 1\n"); return 3; }
check_threads();
check_memory();
check_time();
check_files();
WNDCLASSA wc = {.lpfnWndProc = wndproc, .hInstance = GetModuleHandleA(NULL),
.lpszClassName = "BetterXenIntegrated"};
WIN(RegisterClassA(&wc), "RegisterClass");
RECT r = {0, 0, W, H};
AdjustWindowRect(&r, WS_OVERLAPPEDWINDOW, FALSE);
HWND hwnd = CreateWindowA(wc.lpszClassName, window_title,
WS_OVERLAPPEDWINDOW | WS_VISIBLE, 64, 64, r.right - r.left,
r.bottom - r.top, NULL, NULL, wc.hInstance, NULL);
WIN(hwnd, "CreateWindow");
pump();
DXGI_SWAP_CHAIN_DESC sd = {.BufferDesc = {.Width = W, .Height = H, .Format = DXGI_FORMAT_R8G8B8A8_UNORM},
.SampleDesc = {1, 0}, .BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT,
.BufferCount = 2, .OutputWindow = hwnd, .Windowed = TRUE,
.SwapEffect = DXGI_SWAP_EFFECT_DISCARD};
ID3D11Device *dev = NULL;
ID3D11DeviceContext *ctx = NULL;
IDXGISwapChain *swap = NULL;
D3D_FEATURE_LEVEL fl, want = D3D_FEATURE_LEVEL_11_0;
HRESULT hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &want, 1,
D3D11_SDK_VERSION, &sd, &swap, &dev, &fl, &ctx);
if (FAILED(hr)) { printf("NO DEVICE hr=0x%08lx\n", (unsigned long)hr); return 2; }
{
IDXGIDevice *dd = NULL;
IDXGIAdapter *ad = NULL;
DXGI_ADAPTER_DESC desc;
if (SUCCEEDED(ID3D11Device_QueryInterface(dev, &IID_IDXGIDevice, (void **)&dd)) &&
SUCCEEDED(IDXGIDevice_GetAdapter(dd, &ad)) && SUCCEEDED(IDXGIAdapter_GetDesc(ad, &desc))) {
char name[128];
size_t i = 0;
for (; i < 127 && desc.Description[i]; i++) name[i] = (char)desc.Description[i];
name[i] = 0;
printf("adapter=%s vendor=0x%x\n", name, desc.VendorId);
}
RELEASE(ad, IDXGIAdapter);
RELEASE(dd, IDXGIDevice);
}
ID3D11Texture2D *back = NULL;
API(IDXGISwapChain_GetBuffer(swap, 0, &IID_ID3D11Texture2D, (void **)&back), "GetBuffer");
ID3D11RenderTargetView *back_rtv = NULL, *off_rtv = NULL;
API(ID3D11Device_CreateRenderTargetView(dev, (ID3D11Resource *)back, NULL, &back_rtv), "back rtv");
ID3D11Texture2D *off = texture(dev, W, H, DXGI_FORMAT_R8G8B8A8_UNORM,
D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE,
D3D11_USAGE_DEFAULT, 0, NULL);
ID3D11Texture2D *post = texture(dev, W, H, DXGI_FORMAT_R8G8B8A8_UNORM,
D3D11_BIND_UNORDERED_ACCESS | D3D11_BIND_SHADER_RESOURCE,
D3D11_USAGE_DEFAULT, 0, NULL);
ID3D11Texture2D *depth = texture(dev, W, H, DXGI_FORMAT_D32_FLOAT, D3D11_BIND_DEPTH_STENCIL,
D3D11_USAGE_DEFAULT, 0, NULL);
ID3D11Texture2D *staging = texture(dev, W, H, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D11_USAGE_STAGING,
D3D11_CPU_ACCESS_READ, NULL);
ID3D11Texture2D *ta = bc1 ? bc1_texture(dev,!strcmp(fault,"bc1")) : texture(dev, 2, 2, DXGI_FORMAT_R8G8B8A8_UNORM, D3D11_BIND_SHADER_RESOURCE,
D3D11_USAGE_IMMUTABLE, 0, TEX_A);
ID3D11Texture2D *tb = texture(dev, 2, 2, DXGI_FORMAT_R8G8B8A8_UNORM, D3D11_BIND_SHADER_RESOURCE,
D3D11_USAGE_IMMUTABLE, 0, TEX_B);
ID3D11DepthStencilView *dsv = NULL;
ID3D11ShaderResourceView *off_srv, *post_srv, *ta_srv, *tb_srv;
ID3D11UnorderedAccessView *post_uav = NULL;
API(ID3D11Device_CreateRenderTargetView(dev, (ID3D11Resource *)off, NULL, &off_rtv), "off rtv");
API(ID3D11Device_CreateDepthStencilView(dev, (ID3D11Resource *)depth, NULL, &dsv), "dsv");
API(ID3D11Device_CreateShaderResourceView(dev, (ID3D11Resource *)off, NULL, &off_srv), "off srv");
API(ID3D11Device_CreateShaderResourceView(dev, (ID3D11Resource *)post, NULL, &post_srv), "post srv");
API(ID3D11Device_CreateShaderResourceView(dev, (ID3D11Resource *)ta, NULL, &ta_srv), "a srv");
API(ID3D11Device_CreateShaderResourceView(dev, (ID3D11Resource *)tb, NULL, &tb_srv), "b srv");
API(ID3D11Device_CreateUnorderedAccessView(dev, (ID3D11Resource *)post, NULL, &post_uav), "uav");
Vertex verts[8];
quad(verts, 96, 96, 0.25f); /* B, near, vertices 0..3 */
quad(verts + 4, 32, 32, 0.5f); /* A, far, vertices 4..7 */
const unsigned short indices[6] = {0, 1, 2, 2, 1, 3};
ID3D11Buffer *vb, *ib, *cb;
D3D11_BUFFER_DESC bd = {.ByteWidth = sizeof verts, .BindFlags = D3D11_BIND_VERTEX_BUFFER};
D3D11_SUBRESOURCE_DATA init = {.pSysMem = verts};
API(ID3D11Device_CreateBuffer(dev, &bd, &init, &vb), "vb");
bd.ByteWidth = sizeof indices;
bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
init.pSysMem = indices;
API(ID3D11Device_CreateBuffer(dev, &bd, &init, &ib), "ib");
bd.ByteWidth = sizeof(Constants);
bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
API(ID3D11Device_CreateBuffer(dev, &bd, NULL, &cb), "cb");
D3D11_SAMPLER_DESC smpd = {.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT,
.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP,
.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP,
.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP,
.ComparisonFunc = D3D11_COMPARISON_NEVER, .MaxLOD = D3D11_FLOAT32_MAX};
ID3D11SamplerState *sampler;
API(ID3D11Device_CreateSamplerState(dev, &smpd, &sampler), "sampler");
D3D11_DEPTH_STENCIL_DESC dsd = {.DepthEnable = strcmp(fault, "depth") != 0,
.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL,
.DepthFunc = D3D11_COMPARISON_LESS};
ID3D11DepthStencilState *depth_state;
API(ID3D11Device_CreateDepthStencilState(dev, &dsd, &depth_state), "depth state");
D3D11_QUERY_DESC qd = {D3D11_QUERY_EVENT, 0};
ID3D11Query *query;
API(ID3D11Device_CreateQuery(dev, &qd, &query), "query");
gate("graphics.init", 1, "window swapchain targets depth textures buffers views states");
ID3DBlob *b_vsq = compile("vs_quad", "vs_5_0"), *b_psq = compile("ps_quad", "ps_5_0");
ID3DBlob *b_vsf = compile("vs_full", "vs_5_0"), *b_psf = compile("ps_full", "ps_5_0");
ID3DBlob *b_cs = compile("cs_main", "cs_5_0");
#define PTR(b) ID3D10Blob_GetBufferPointer(b)
#define LEN(b) ID3D10Blob_GetBufferSize(b)
ID3D11VertexShader *vsq, *vsf;
ID3D11PixelShader *psq, *psf;
ID3D11ComputeShader *cs;
ID3D11InputLayout *layout;
API(ID3D11Device_CreateVertexShader(dev, PTR(b_vsq), LEN(b_vsq), NULL, &vsq), "vs quad");
API(ID3D11Device_CreatePixelShader(dev, PTR(b_psq), LEN(b_psq), NULL, &psq), "ps quad");
API(ID3D11Device_CreateVertexShader(dev, PTR(b_vsf), LEN(b_vsf), NULL, &vsf), "vs full");
API(ID3D11Device_CreatePixelShader(dev, PTR(b_psf), LEN(b_psf), NULL, &psf), "ps full");
API(ID3D11Device_CreateComputeShader(dev, PTR(b_cs), LEN(b_cs), NULL, &cs), "cs");
const D3D11_INPUT_ELEMENT_DESC ied[2] = {
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}};
API(ID3D11Device_CreateInputLayout(dev, ied, 2, PTR(b_vsq), LEN(b_vsq), &layout), "input layout");
ID3D10Blob_Release(b_vsq);
ID3D10Blob_Release(b_psq);
ID3D10Blob_Release(b_vsf);
ID3D10Blob_Release(b_psf);
ID3D10Blob_Release(b_cs);
gate("shader.compile", 1, "vs ps cs compiled and created (shader model 5.0)");
ev_request = CreateEventA(NULL, FALSE, FALSE, NULL);
ev_ready = CreateEventA(NULL, FALSE, FALSE, NULL);
WIN(ev_request && ev_ready, "CreateEvent");
HANDLE prod = CreateThread(NULL, 0, producer, NULL, 0, NULL);
WIN(prod, "CreateThread producer");
/* Scripted input: right, right, down, left, down, delivered at fixed frames. */
static const WPARAM script[5] = {VK_RIGHT, VK_RIGHT, VK_DOWN, VK_LEFT, VK_DOWN};
int injected = 0, verified = 0, bad_frames = 0, presented = 0, churns = 0, churn_ok = 1;
unsigned long long digest = 1469598103934665603ULL; /* FNV-1a over verified pixels */
double mem_warm = -1.0, mem_peak = 0.0, prev = now_ms();
const int warmup = frames / 5;
const D3D11_VIEWPORT vp = {0, 0, W, H, 0, 1};
const float black[4] = {0, 0, 0, 1};
const UINT stride = sizeof(Vertex), zero = 0;
ID3D11ShaderResourceView *no_srv = NULL;
ID3D11UnorderedAccessView *no_uav = NULL;
ID3D11RenderTargetView *no_rtv = NULL;
int f = 0;
for (; f < frames && !quit_requested; f++) {
if (!interactive && strcmp(fault, "input") && injected < 5 && f == (injected + 1) * (frames / 8)) {
WIN(PostMessageA(hwnd, WM_KEYDOWN, script[injected], 0), "PostMessage");
injected++;
}
pump();
requested_frame = (unsigned)f;
SetEvent(ev_request);
WIN(WaitForSingleObject(ev_ready, 10000) == WAIT_OBJECT_0, "producer handoff");
const unsigned marker = produced_value;
const int bx = 96 + off_x, by = 96 + off_y;
Constants k = {off_x / 128.0f, -off_y / 128.0f, strcmp(fault, "stale") ? marker : 1u, 0};
ID3D11DeviceContext_UpdateSubresource(ctx, (ID3D11Resource *)cb, 0, NULL, &k, 0, 0);
/* pass 1 */
ID3D11DeviceContext_OMSetRenderTargets(ctx, 1, &off_rtv, dsv);
ID3D11DeviceContext_OMSetDepthStencilState(ctx, depth_state, 0);
ID3D11DeviceContext_ClearRenderTargetView(ctx, off_rtv, black);
ID3D11DeviceContext_ClearDepthStencilView(ctx, dsv, D3D11_CLEAR_DEPTH, 1.0f, 0);
ID3D11DeviceContext_RSSetViewports(ctx, 1, &vp);
ID3D11DeviceContext_IASetInputLayout(ctx, layout);
ID3D11DeviceContext_IASetPrimitiveTopology(ctx, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
ID3D11DeviceContext_IASetVertexBuffers(ctx, 0, 1, &vb, &stride, &zero);
ID3D11DeviceContext_IASetIndexBuffer(ctx, ib, DXGI_FORMAT_R16_UINT, 0);
ID3D11DeviceContext_VSSetShader(ctx, vsq, NULL, 0);
ID3D11DeviceContext_VSSetConstantBuffers(ctx, 0, 1, &cb);
ID3D11DeviceContext_PSSetShader(ctx, psq, NULL, 0);
ID3D11DeviceContext_PSSetSamplers(ctx, 0, 1, &sampler);
if (strcmp(fault, "blank")) {
ID3D11DeviceContext_PSSetShaderResources(ctx, 0, 1, &tb_srv);
ID3D11DeviceContext_DrawIndexed(ctx, 6, 0, 0); /* B first, with the input offset */
Constants fixed = k;
fixed.ox = fixed.oy = 0.0f;
ID3D11DeviceContext_UpdateSubresource(ctx, (ID3D11Resource *)cb, 0, NULL, &fixed, 0, 0);
ID3D11DeviceContext_PSSetShaderResources(ctx, 0, 1, &ta_srv);
ID3D11DeviceContext_DrawIndexed(ctx, 6, 0, 4);
}
/* pass 2 */
ID3D11DeviceContext_OMSetRenderTargets(ctx, 1, &no_rtv, NULL);
ID3D11DeviceContext_CSSetShader(ctx, cs, NULL, 0);
ID3D11DeviceContext_CSSetConstantBuffers(ctx, 0, 1, &cb);
ID3D11DeviceContext_CSSetShaderResources(ctx, 0, 1, &off_srv);
ID3D11DeviceContext_CSSetUnorderedAccessViews(ctx, 0, 1, &post_uav, NULL);
ID3D11DeviceContext_Dispatch(ctx, W / 8, H / 8, 1);
ID3D11DeviceContext_CSSetUnorderedAccessViews(ctx, 0, 1, &no_uav, NULL);
ID3D11DeviceContext_CSSetShaderResources(ctx, 0, 1, &no_srv);
/* pass 3 */
ID3D11DeviceContext_OMSetRenderTargets(ctx, 1, &back_rtv, NULL);
ID3D11DeviceContext_IASetInputLayout(ctx, NULL);
ID3D11DeviceContext_VSSetShader(ctx, vsf, NULL, 0);
ID3D11DeviceContext_PSSetShader(ctx, psf, NULL, 0);
ID3D11DeviceContext_PSSetShaderResources(ctx, 0, 1, &post_srv);
ID3D11DeviceContext_Draw(ctx, 3, 0);
ID3D11DeviceContext_PSSetShaderResources(ctx, 0, 1, &no_srv);
const int check = f == 0 || f == frames - 1 || f % verify_every == 0 ||
(injected && f == injected * (frames / 8) + 1);
if (check) {
ID3D11DeviceContext_CopyResource(ctx, (ID3D11Resource *)staging, (ID3D11Resource *)back);
D3D11_MAPPED_SUBRESOURCE m;
API(ID3D11DeviceContext_Map(ctx, (ID3D11Resource *)staging, 0, D3D11_MAP_READ, 0, &m), "Map");
int mismatches = 0;
for (int y = 0; y < H; y++) {
const unsigned char *row = (const unsigned char *)m.pData + (size_t)y * m.RowPitch;
for (int x = 0; x < W; x++) {
unsigned char e[4];
expected_pixel(x, y, marker, bx, by, !strcmp(fault, "color"), e);
if (memcmp(row + x * 4, e, 4)) {
if (!mismatches++)
printf("mismatch frame=%d x=%d y=%d got=%u,%u,%u,%u want=%u,%u,%u,%u\n", f, x, y,
row[x * 4], row[x * 4 + 1], row[x * 4 + 2], row[x * 4 + 3], e[0], e[1], e[2], e[3]);
}
for (int c = 0; c < 4; c++) digest = (digest ^ row[x * 4 + c]) * 1099511628211ULL;
}
}
ID3D11DeviceContext_Unmap(ctx, (ID3D11Resource *)staging, 0);
verified++;
if (mismatches) bad_frames++;
}
ID3D11DeviceContext_End(ctx, (ID3D11Asynchronous *)query);
API(IDXGISwapChain_Present(swap, (UINT)vsync, 0), "Present");
presented++;
BOOL done = FALSE;
const double wait_start = now_ms();
for (;;) {
HRESULT status=ID3D11DeviceContext_GetData(ctx,(ID3D11Asynchronous *)query,&done,sizeof done,0);
API(status,"GPU event query");
if (status==S_OK && done) break;
WIN(now_ms() - wait_start < 10000.0, "GPU completion within 10 s");
Sleep(0);
}
if (f == 0) {
char msg[96];
snprintf(msg, sizeof msg, "pixels=%d mismatched_frames=%d present=ok", W * H, bad_frames);
gate("frame.first", bad_frames == 0, msg);
if (!strcmp(fault, "crash")) *(volatile int *)0 = 1;
if (!strcmp(fault, "hang")) Sleep(INFINITE);
const double until=now_ms()+hold_first_ms;
while (now_ms()<until && !quit_requested) { pump(); Sleep(10); }
}
if (f % 100 == 50) {
churn_ok = churn(dev, ctx, (unsigned)f) && churn_ok;
churns++;
}
const double t = now_ms();
printf("frame_ms %.4f\n", t - prev);
prev = t;
if (f == warmup) mem_warm = working_set_mb();
if (f % 50 == 0) {
const double mb = working_set_mb();
if (mb > mem_peak) mem_peak = mb;
}
}
char msg[200];
snprintf(msg, sizeof msg, "presented=%d verified=%d mismatched=%d digest=%016llx", presented, verified,
bad_frames, digest);
gate("frame.continuous", presented == f && (interactive || presented == frames) && bad_frames == 0, msg);
if (bc1) gate("textures.bc1", verified > 0 && bad_frames == 0, "RGB565 endpoints sampled through graphics, compute and presentation; exact RGBA readback");
snprintf(msg, sizeof msg, "cycles=%d", churns);
gate("resources.churn", churn_ok && (interactive || churns > 0 || frames <= 50), msg);
if (interactive) {
snprintf(msg, sizeof msg, "keys_seen=%d offset=%d,%d (person-driven, not scripted)", keys_seen, off_x, off_y);
gate("input", keys_seen > 0 && bad_frames == 0, msg);
} else {
/* by hand: right,right,down,left,down = (+16, +32) */
snprintf(msg, sizeof msg, "posted=%d received=%d offset=%d,%d want=16,32 (PostMessage)", injected,
keys_seen, off_x, off_y);
gate("input", injected == 5 && keys_seen == 5 && off_x == 16 && off_y == 32 && bad_frames == 0, msg);
}
const double mem_end = working_set_mb();
if (mem_end > mem_peak) mem_peak = mem_end;
snprintf(msg, sizeof msg, "working_set_mb_after_warmup=%.1f end=%.1f peak_sampled=%.1f bound_growth=%d", mem_warm,
mem_end, mem_peak, max_growth);
gate("memory.bounded", mem_warm > 0 && mem_end > 0 && mem_end - mem_warm <= max_growth, msg);
/* keep presenting the last image so an outside observer can capture the window */
if (hold_ms > 0) {
printf("holding hold_ms=%d\n", hold_ms);
const double until = now_ms() + hold_ms;
while (now_ms() < until && !quit_requested) {
pump();
ID3D11DeviceContext_OMSetRenderTargets(ctx, 1, &back_rtv, NULL);
ID3D11DeviceContext_PSSetShaderResources(ctx, 0, 1, &post_srv);
ID3D11DeviceContext_Draw(ctx, 3, 0);
API(IDXGISwapChain_Present(swap, 1, 0), "Present hold");
Sleep(10);
}
}
producer_stop = 1;
SetEvent(ev_request);
int clean = WaitForSingleObject(prod, 10000) == WAIT_OBJECT_0;
CloseHandle(prod);
CloseHandle(ev_request);
CloseHandle(ev_ready);
ID3D11DeviceContext_ClearState(ctx);
ID3D11DeviceContext_Flush(ctx);
RELEASE(query, ID3D11Query);
RELEASE(depth_state, ID3D11DepthStencilState);
RELEASE(sampler, ID3D11SamplerState);
RELEASE(layout, ID3D11InputLayout);
RELEASE(cs, ID3D11ComputeShader);
RELEASE(psf, ID3D11PixelShader);
RELEASE(vsf, ID3D11VertexShader);
RELEASE(psq, ID3D11PixelShader);
RELEASE(vsq, ID3D11VertexShader);
RELEASE(cb, ID3D11Buffer);
RELEASE(ib, ID3D11Buffer);
RELEASE(vb, ID3D11Buffer);
RELEASE(post_uav, ID3D11UnorderedAccessView);
RELEASE(tb_srv, ID3D11ShaderResourceView);
RELEASE(ta_srv, ID3D11ShaderResourceView);
RELEASE(post_srv, ID3D11ShaderResourceView);
RELEASE(off_srv, ID3D11ShaderResourceView);
RELEASE(dsv, ID3D11DepthStencilView);
RELEASE(off_rtv, ID3D11RenderTargetView);
RELEASE(back_rtv, ID3D11RenderTargetView);
RELEASE(tb, ID3D11Texture2D);
RELEASE(ta, ID3D11Texture2D);
RELEASE(staging, ID3D11Texture2D);
RELEASE(depth, ID3D11Texture2D);
RELEASE(post, ID3D11Texture2D);
RELEASE(off, ID3D11Texture2D);
RELEASE(back, ID3D11Texture2D);
RELEASE(swap, IDXGISwapChain);
RELEASE(ctx, ID3D11DeviceContext);
const ULONG refs = ID3D11Device_Release(dev);
clean = DestroyWindow(hwnd) && clean;
pump();
snprintf(msg, sizeof msg, "producer_joined window_destroyed device_refs_after_release=%lu", (unsigned long)refs);
gate("shutdown", clean && refs == 0, msg);
if (failures) {
printf("FAIL integrated failed_gates=%d\n", failures);
return 1;
}
printf("PASS integrated frames=%d verified=%d\n", presented, verified);
return 0;
}
@@ -0,0 +1,5 @@
# SPDX-License-Identifier: GPL-3.0-or-later
add_executable(d3d12-integrated integrated12.c)
target_compile_options(d3d12-integrated PRIVATE -Wall -Wextra -Werror)
target_link_options(d3d12-integrated PRIVATE -Wl,--no-insert-timestamp)
target_link_libraries(d3d12-integrated PRIVATE d3d12 dxgi dxguid d3dcompiler psapi user32)
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Build the Direct3D 12 workload with the pinned llvm-mingw (https://github.com/MacosPorters/betterxen/blob/54264e23a417e861834ee879f810717385b91f58/docs/research/hybrid-toolchain.md).
# tests/conformance/test_d3d12_integrated/build.sh <llvm-mingw-dir> [output-dir]
set -eu
TC=${1:?usage: build.sh LLVM_MINGW_DIR [OUTPUT_DIR]}
src=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
out=${2:-"$src/../../../artifacts/hybrid-workloads/x86_64"}
mkdir -p "$out"
"$TC/bin/x86_64-w64-mingw32-clang" -std=c11 -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
-o "$out/d3d12-integrated.exe" "$src/integrated12.c" \
-ld3d12 -ldxgi -ldxguid -ld3dcompiler -lpsapi -luser32
description=$(file -b "$out/d3d12-integrated.exe")
echo "$description"
case "$description" in
*PE32+*x86-64*) ;;
*) exit 1 ;;
esac
@@ -0,0 +1,776 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original BetterXen workload: Direct3D 12 graphics and compute with presentation and
// self-verification, run through `betterxen hybrid run`. Written from Microsoft's public
// Direct3D 12 documentation.
//
// The scene is deliberately the same as tests/conformance/test_d3d11_integrated, with the same
// verification schedule, so the two APIs must produce the same pixel digest:
// pass 1 two textured quads with a depth buffer into an offscreen target; near quad B is
// drawn first and moves with the arrow keys
// pass 2 compute: rotate channels into a UAV and write a 16-row frame-number band
// pass 3 full-screen triangle into the swapchain back buffer
// The back buffer is copied to a READBACK buffer and compared, with zero tolerance, with an
// image computed on the CPU. Two frames are in flight; each has its own command allocator,
// constant-buffer slice and fence value.
//
// Limits: read-back proves what was handed to Present, not what reached the screen. No debug
// layer is used, so a missing barrier that happens to work is not detected.
//
// usage: integrated12.exe [--frames N] [--duration-s N] [--verify-every N] [--vsync]
// [--external-input] [--input-timeout-s N] [--hold-ms N] [--max-growth-mb N]
// [--expect-absent-env NAME] [--fault color|blank|stale|input|depth|upload|crash|hang]
// Exit: 0 pass, 1 a verification failed, 2 no Direct3D 12 device, 3 an API call failed.
#define COBJMACROS
#define WIDL_C_INLINE_WRAPPERS /* struct-returning D3D12 methods in C (mingw-w64) */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <psapi.h>
#include <d3d12.h>
#include <d3dcompiler.h>
#include <dxgi1_4.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define W 256
#define H 256
#define BAND 16
#define STEP 16
#define SLOTS 2
#define ROW_PITCH (W * 4) /* 1024, a multiple of D3D12_TEXTURE_DATA_PITCH_ALIGNMENT */
static int failures;
static LARGE_INTEGER qpc_freq, qpc_start;
static double now_ms(void) {
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return (double)(t.QuadPart - qpc_start.QuadPart) * 1000.0 / (double)qpc_freq.QuadPart;
}
static void gate(const char *name, int ok, const char *detail) {
printf("gate %s %s %s t_ms=%.1f\n", name, ok ? "pass" : "FAIL", detail, now_ms());
if (!ok) failures++;
}
#define API(x, what) do { HRESULT hr_ = (x); if (FAILED(hr_)) { \
printf("FAIL api %s hr=0x%08lx\n", what, (unsigned long)hr_); exit(3); } } while (0)
#define WIN(x, what) do { if (!(x)) { \
printf("FAIL api %s error=%lu\n", what, (unsigned long)GetLastError()); exit(3); } } while (0)
/* ---- window and input ------------------------------------------------------------------ */
static int off_x, off_y, keys_seen, quit_requested;
static LRESULT CALLBACK wndproc(HWND h, UINT m, WPARAM w, LPARAM l) {
if (m == WM_KEYDOWN) {
if (w == VK_ESCAPE) quit_requested = 1;
else {
int dx = w == VK_RIGHT ? STEP : w == VK_LEFT ? -STEP : 0;
int dy = w == VK_DOWN ? STEP : w == VK_UP ? -STEP : 0;
if (dx || dy) {
keys_seen++;
off_x += dx;
off_y += dy;
if (off_x < -64) off_x = -64;
if (off_x > 32) off_x = 32;
if (off_y < -64) off_y = -64;
if (off_y > 32) off_y = 32;
}
}
return 0;
}
if (m == WM_CLOSE) { quit_requested = 1; return 0; }
return DefWindowProcA(h, m, w, l);
}
static void pump(void) {
MSG msg;
while (PeekMessageA(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessageA(&msg);
}
}
/* ---- expected image (CPU, independent of the shaders) ---------------------------------- */
static const unsigned char TEX_A[4][4] = {
{255, 0, 0, 255}, {0, 255, 0, 255}, {0, 0, 255, 255}, {255, 255, 255, 255}};
static const unsigned char TEX_B[4][4] = {
{255, 255, 0, 255}, {0, 255, 255, 255}, {255, 0, 255, 255}, {128, 128, 128, 255}};
static void expected_pixel(int x, int y, unsigned marker, int bx, int by, int wrong, unsigned char out[4]) {
if (y < BAND) {
out[0] = (unsigned char)(marker & 255);
out[1] = (unsigned char)(marker >> 8);
out[2] = 77;
out[3] = 255;
return;
}
const unsigned char *c = NULL;
if (x >= bx && x < bx + 128 && y >= by && y < by + 128)
c = TEX_B[((y - by) / 64) * 2 + (x - bx) / 64];
else if (x >= 32 && x < 160 && y >= 32 && y < 160)
c = TEX_A[((y - 32) / 64) * 2 + (x - 32) / 64];
out[0] = c ? c[2] : 0;
out[1] = c ? c[0] : 0;
out[2] = c ? c[1] : 0;
out[3] = 255;
if (wrong && c == TEX_A[0]) out[0] ^= 255;
}
/* ---- Direct3D 12 ----------------------------------------------------------------------- */
static const char *HLSL =
"cbuffer C : register(b0) { float2 offset; uint marker; uint pad; };\n"
"Texture2D tex : register(t0); SamplerState smp : register(s0);\n"
"struct VI { float3 p : POSITION; float2 uv : TEXCOORD; };\n"
"struct VO { float4 p : SV_Position; float2 uv : TEXCOORD; };\n"
"VO vs_quad(VI v) { VO o; o.p = float4(v.p.xy + offset, v.p.z, 1); o.uv = v.uv; return o; }\n"
"float4 ps_quad(VO i) : SV_Target { return tex.Sample(smp, i.uv); }\n"
"float4 vs_full(uint id : SV_VertexID) : SV_Position {\n"
" float2 uv = float2((id << 1) & 2, id & 2);\n"
" return float4(uv * float2(2, -2) + float2(-1, 1), 0, 1); }\n"
"float4 ps_full(float4 p : SV_Position) : SV_Target { return tex.Load(int3(p.xy, 0)); }\n"
"RWTexture2D<unorm float4> dst : register(u0);\n"
"[numthreads(8, 8, 1)] void cs_main(uint3 id : SV_DispatchThreadID) {\n"
" if (id.y < 16) { dst[id.xy] = float4((marker & 255) / 255.0, (marker >> 8) / 255.0, 77 / 255.0, 1); return; }\n"
" float4 c = tex.Load(int3(id.xy, 0));\n"
" dst[id.xy] = float4(c.b, c.r, c.g, 1); }\n";
typedef struct { float x, y, z, u, v; } Vertex;
typedef struct { float ox, oy; unsigned marker, pad; } Constants;
static ID3D12Device *dev;
static ID3D12CommandQueue *queue;
static ID3D12Fence *fence;
static HANDLE fence_event;
static UINT64 fence_next = 1;
static ID3DBlob *compile(const char *entry, const char *target) {
ID3DBlob *code = NULL, *err = NULL;
HRESULT hr = D3DCompile(HLSL, strlen(HLSL), NULL, NULL, NULL, entry, target, 0, 0, &code, &err);
if (FAILED(hr)) {
printf("FAIL api D3DCompile %s hr=0x%08lx %s\n", entry, (unsigned long)hr,
err ? (const char *)ID3D10Blob_GetBufferPointer(err) : "");
exit(3);
}
if (err) ID3D10Blob_Release(err);
return code;
}
static ID3D12Resource *resource(D3D12_HEAP_TYPE heap, const D3D12_RESOURCE_DESC *d,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE *clear) {
D3D12_HEAP_PROPERTIES hp = {.Type = heap};
ID3D12Resource *r = NULL;
API(ID3D12Device_CreateCommittedResource(dev, &hp, D3D12_HEAP_FLAG_NONE, d, state, clear,
&IID_ID3D12Resource, (void **)&r), "CreateCommittedResource");
return r;
}
static ID3D12Resource *buffer(D3D12_HEAP_TYPE heap, UINT64 bytes, D3D12_RESOURCE_STATES state) {
D3D12_RESOURCE_DESC d = {.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER, .Width = bytes, .Height = 1,
.DepthOrArraySize = 1, .MipLevels = 1, .SampleDesc = {1, 0},
.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR};
return resource(heap, &d, state, NULL);
}
static ID3D12Resource *texture(UINT w, UINT h, DXGI_FORMAT fmt, D3D12_RESOURCE_FLAGS flags,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE *clear) {
D3D12_RESOURCE_DESC d = {.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D, .Width = w, .Height = h,
.DepthOrArraySize = 1, .MipLevels = 1, .Format = fmt, .SampleDesc = {1, 0},
.Flags = flags};
return resource(D3D12_HEAP_TYPE_DEFAULT, &d, state, clear);
}
static void barrier(ID3D12GraphicsCommandList *list, ID3D12Resource *r, D3D12_RESOURCE_STATES from,
D3D12_RESOURCE_STATES to) {
D3D12_RESOURCE_BARRIER b = {.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION};
b.Transition.pResource = r;
b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
b.Transition.StateBefore = from;
b.Transition.StateAfter = to;
ID3D12GraphicsCommandList_ResourceBarrier(list, 1, &b);
}
static void wait_for(UINT64 value) {
if (ID3D12Fence_GetCompletedValue(fence) < value) {
API(ID3D12Fence_SetEventOnCompletion(fence, value, fence_event), "SetEventOnCompletion");
WIN(WaitForSingleObject(fence_event, 10000) == WAIT_OBJECT_0, "GPU completion within 10 s");
}
}
static UINT64 submit(ID3D12GraphicsCommandList *list) {
API(ID3D12GraphicsCommandList_Close(list), "Close");
ID3D12CommandList *lists[1] = {(ID3D12CommandList *)list};
ID3D12CommandQueue_ExecuteCommandLists(queue, 1, lists);
const UINT64 value = fence_next++;
API(ID3D12CommandQueue_Signal(queue, fence, value), "Signal");
return value;
}
static void copy_texture(ID3D12GraphicsCommandList *list, ID3D12Resource *tex, ID3D12Resource *buf,
UINT w, UINT h, UINT pitch, int to_texture) {
D3D12_TEXTURE_COPY_LOCATION t = {.pResource = tex, .Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX};
D3D12_TEXTURE_COPY_LOCATION b = {.pResource = buf, .Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT};
b.PlacedFootprint.Footprint = (D3D12_SUBRESOURCE_FOOTPRINT){DXGI_FORMAT_R8G8B8A8_UNORM, w, h, 1, pitch};
if (to_texture) ID3D12GraphicsCommandList_CopyTextureRegion(list, &t, 0, 0, 0, &b, NULL);
else ID3D12GraphicsCommandList_CopyTextureRegion(list, &b, 0, 0, 0, &t, NULL);
}
static void fill(ID3D12Resource *upload, const void *data, size_t bytes) {
void *p = NULL;
D3D12_RANGE none = {0, 0};
API(ID3D12Resource_Map(upload, 0, &none, &p), "Map upload");
memcpy(p, data, bytes);
ID3D12Resource_Unmap(upload, 0, NULL);
}
static ID3D12DescriptorHeap *heap_of(D3D12_DESCRIPTOR_HEAP_TYPE type, UINT n, int visible) {
D3D12_DESCRIPTOR_HEAP_DESC d = {.Type = type, .NumDescriptors = n,
.Flags = visible ? D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE
: D3D12_DESCRIPTOR_HEAP_FLAG_NONE};
ID3D12DescriptorHeap *h = NULL;
API(ID3D12Device_CreateDescriptorHeap(dev, &d, &IID_ID3D12DescriptorHeap, (void **)&h), "descriptor heap");
return h;
}
static ID3D12RootSignature *root_signature(int compute) {
D3D12_DESCRIPTOR_RANGE srv = {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0};
D3D12_DESCRIPTOR_RANGE other = {compute ? D3D12_DESCRIPTOR_RANGE_TYPE_UAV : D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER,
1, 0, 0, 0};
D3D12_ROOT_PARAMETER p[3];
memset(p, 0, sizeof p);
p[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
p[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
p[1].DescriptorTable.NumDescriptorRanges = 1;
p[1].DescriptorTable.pDescriptorRanges = &srv;
p[2] = p[1];
p[2].DescriptorTable.pDescriptorRanges = &other;
D3D12_ROOT_SIGNATURE_DESC d = {.NumParameters = 3, .pParameters = p,
.Flags = compute ? D3D12_ROOT_SIGNATURE_FLAG_NONE
: D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT};
ID3DBlob *blob = NULL, *err = NULL;
API(D3D12SerializeRootSignature(&d, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &err), "serialize root signature");
ID3D12RootSignature *rs = NULL;
API(ID3D12Device_CreateRootSignature(dev, 0, ID3D10Blob_GetBufferPointer(blob), ID3D10Blob_GetBufferSize(blob),
&IID_ID3D12RootSignature, (void **)&rs), "root signature");
ID3D10Blob_Release(blob);
return rs;
}
static ID3D12PipelineState *graphics_pipeline(ID3D12RootSignature *rs, ID3DBlob *vs, ID3DBlob *ps,
int quad, int depth_test) {
static const D3D12_INPUT_ELEMENT_DESC ied[2] = {
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
{"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}};
D3D12_GRAPHICS_PIPELINE_STATE_DESC d;
memset(&d, 0, sizeof d);
d.pRootSignature = rs;
d.VS = (D3D12_SHADER_BYTECODE){ID3D10Blob_GetBufferPointer(vs), ID3D10Blob_GetBufferSize(vs)};
d.PS = (D3D12_SHADER_BYTECODE){ID3D10Blob_GetBufferPointer(ps), ID3D10Blob_GetBufferSize(ps)};
d.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
d.SampleMask = UINT_MAX;
d.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
d.RasterizerState.CullMode = D3D12_CULL_MODE_BACK;
d.RasterizerState.DepthClipEnable = TRUE;
if (quad) {
d.InputLayout = (D3D12_INPUT_LAYOUT_DESC){ied, 2};
d.DepthStencilState.DepthEnable = depth_test;
d.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
d.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS;
d.DSVFormat = DXGI_FORMAT_D32_FLOAT;
}
d.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
d.NumRenderTargets = 1;
d.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
d.SampleDesc.Count = 1;
ID3D12PipelineState *p = NULL;
API(ID3D12Device_CreateGraphicsPipelineState(dev, &d, &IID_ID3D12PipelineState, (void **)&p), "graphics PSO");
return p;
}
static void quad_vertices(Vertex *v, int x0, int y0, float z) {
const float l = x0 / 128.0f - 1.0f, r = (x0 + 128) / 128.0f - 1.0f;
const float t = 1.0f - y0 / 128.0f, b = 1.0f - (y0 + 128) / 128.0f;
v[0] = (Vertex){l, t, z, 0, 0};
v[1] = (Vertex){r, t, z, 1, 0};
v[2] = (Vertex){l, b, z, 0, 1};
v[3] = (Vertex){r, b, z, 1, 1};
}
static double working_set_mb(void) {
PROCESS_MEMORY_COUNTERS m;
memset(&m, 0, sizeof m);
if (!GetProcessMemoryInfo(GetCurrentProcess(), &m, sizeof m) || !m.WorkingSetSize) return -1.0;
return (double)m.WorkingSetSize / (1024.0 * 1024.0);
}
/* Create, upload, copy back, compare and destroy a texture on the GPU; 1 if it survived. */
static int churn(ID3D12CommandAllocator *alloc, ID3D12GraphicsCommandList *list, unsigned seed) {
static unsigned data[256 * 256];
for (unsigned i = 0; i < 256 * 256; i++) data[i] = i * 2654435761u + seed;
ID3D12Resource *up = buffer(D3D12_HEAP_TYPE_UPLOAD, sizeof data, D3D12_RESOURCE_STATE_GENERIC_READ);
ID3D12Resource *down = buffer(D3D12_HEAP_TYPE_READBACK, sizeof data, D3D12_RESOURCE_STATE_COPY_DEST);
ID3D12Resource *tex = texture(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE,
D3D12_RESOURCE_STATE_COPY_DEST, NULL);
fill(up, data, sizeof data);
API(ID3D12CommandAllocator_Reset(alloc), "churn allocator reset");
API(ID3D12GraphicsCommandList_Reset(list, alloc, NULL), "churn list reset");
copy_texture(list, tex, up, 256, 256, 1024, 1);
barrier(list, tex, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE);
copy_texture(list, tex, down, 256, 256, 1024, 0);
wait_for(submit(list));
void *p = NULL;
API(ID3D12Resource_Map(down, 0, NULL, &p), "Map readback churn");
const int ok = !memcmp(p, data, sizeof data);
D3D12_RANGE none = {0, 0};
ID3D12Resource_Unmap(down, 0, &none);
ID3D12Resource_Release(tex);
ID3D12Resource_Release(down);
ID3D12Resource_Release(up);
return ok;
}
int main(int argc, char **argv) {
const char *window_title = "BetterXen D3D12 workload";
int frames = 600, verify_every = 30, vsync = 0, external = 0, input_timeout_s = 60;
int duration_s = 0, hold_ms = 0, max_growth = 64, hold_first_ms = 0;
const char *fault = "", *absent_env = NULL;
setvbuf(stdout, NULL, _IONBF, 0);
QueryPerformanceFrequency(&qpc_freq);
QueryPerformanceCounter(&qpc_start);
for (int i = 1; i < argc; i++) {
const char *a = argv[i], *v = i + 1 < argc ? argv[i + 1] : NULL;
if (!strcmp(a, "--vsync")) vsync = 1;
else if (!strcmp(a, "--external-input")) external = 1;
else if (!strcmp(a, "--frames") && v) frames = atoi(v), i++;
else if (!strcmp(a, "--duration-s") && v) duration_s = atoi(v), i++;
else if (!strcmp(a, "--verify-every") && v) verify_every = atoi(v), i++;
else if (!strcmp(a, "--input-timeout-s") && v) input_timeout_s = atoi(v), i++;
else if (!strcmp(a, "--hold-ms") && v) hold_ms = atoi(v), i++;
else if (!strcmp(a, "--hold-first-ms") && v) hold_first_ms = atoi(v), i++;
else if (!strcmp(a, "--window-title") && v) window_title = v, i++;
else if (!strcmp(a, "--max-growth-mb") && v) max_growth = atoi(v), i++;
else if (!strcmp(a, "--expect-absent-env") && v) absent_env = v, i++;
else if (!strcmp(a, "--fault") && v &&
(!strcmp(v, "color") || !strcmp(v, "blank") || !strcmp(v, "stale") || !strcmp(v, "input") ||
!strcmp(v, "depth") || !strcmp(v, "upload") || !strcmp(v, "crash") || !strcmp(v, "hang")))
fault = v, i++;
else { printf("FAIL usage: unknown or incomplete argument %s\n", a); return 3; }
}
if (frames < 64 || verify_every < 1) { printf("FAIL usage: --frames >= 64, --verify-every >= 1\n"); return 3; }
if (absent_env) {
char tmp[2];
SetLastError(0);
const DWORD n = GetEnvironmentVariableA(absent_env, tmp, sizeof tmp);
const int absent = n == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND;
char msg[128];
snprintf(msg, sizeof msg, "%.64s %s", absent_env, absent ? "is not visible" : "is visible");
gate("runtime.env", absent, msg);
}
WNDCLASSA wc = {.lpfnWndProc = wndproc, .hInstance = GetModuleHandleA(NULL),
.lpszClassName = "BetterXenIntegrated12"};
WIN(RegisterClassA(&wc), "RegisterClass");
RECT r = {0, 0, W, H};
AdjustWindowRect(&r, WS_OVERLAPPEDWINDOW, FALSE);
HWND hwnd = CreateWindowA(wc.lpszClassName, window_title, WS_OVERLAPPEDWINDOW | WS_VISIBLE,
64, 64, r.right - r.left, r.bottom - r.top, NULL, NULL, wc.hInstance, NULL);
WIN(hwnd, "CreateWindow");
pump();
HRESULT hr = D3D12CreateDevice(NULL, D3D_FEATURE_LEVEL_11_0, &IID_ID3D12Device, (void **)&dev);
if (FAILED(hr)) { printf("NO DEVICE hr=0x%08lx\n", (unsigned long)hr); return 2; }
IDXGIFactory4 *factory = NULL;
API(CreateDXGIFactory1(&IID_IDXGIFactory4, (void **)&factory), "factory");
D3D12_COMMAND_QUEUE_DESC qd = {.Type = D3D12_COMMAND_LIST_TYPE_DIRECT};
API(ID3D12Device_CreateCommandQueue(dev, &qd, &IID_ID3D12CommandQueue, (void **)&queue), "queue");
{
IDXGIAdapter1 *ad = NULL;
DXGI_ADAPTER_DESC1 desc;
for (UINT i = 0; i < 1 && SUCCEEDED(IDXGIFactory4_EnumAdapters1(factory, i, &ad)); i++) {
if (SUCCEEDED(IDXGIAdapter1_GetDesc1(ad, &desc))) {
char name[128];
size_t k = 0;
for (; k < 127 && desc.Description[k]; k++) name[k] = (char)desc.Description[k];
name[k] = 0;
printf("adapter=%s vendor=0x%x\n", name, desc.VendorId);
}
IDXGIAdapter1_Release(ad);
}
}
API(ID3D12Device_CreateFence(dev, 0, D3D12_FENCE_FLAG_NONE, &IID_ID3D12Fence, (void **)&fence), "fence");
fence_event = CreateEventA(NULL, FALSE, FALSE, NULL);
WIN(fence_event, "CreateEvent");
DXGI_SWAP_CHAIN_DESC1 sd = {.Width = W, .Height = H, .Format = DXGI_FORMAT_R8G8B8A8_UNORM,
.SampleDesc = {1, 0}, .BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT,
.BufferCount = 2, .SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD};
IDXGISwapChain1 *swap1 = NULL;
IDXGISwapChain3 *swap = NULL;
API(IDXGIFactory4_CreateSwapChainForHwnd(factory, (IUnknown *)queue, hwnd, &sd, NULL, NULL, &swap1), "swapchain");
API(IDXGISwapChain1_QueryInterface(swap1, &IID_IDXGISwapChain3, (void **)&swap), "swapchain3");
ID3D12CommandAllocator *alloc[SLOTS], *aux_alloc = NULL;
ID3D12GraphicsCommandList *list = NULL, *aux = NULL;
UINT64 slot_value[SLOTS] = {0};
for (int i = 0; i < SLOTS; i++)
API(ID3D12Device_CreateCommandAllocator(dev, D3D12_COMMAND_LIST_TYPE_DIRECT, &IID_ID3D12CommandAllocator,
(void **)&alloc[i]), "allocator");
API(ID3D12Device_CreateCommandAllocator(dev, D3D12_COMMAND_LIST_TYPE_DIRECT, &IID_ID3D12CommandAllocator,
(void **)&aux_alloc), "aux allocator");
API(ID3D12Device_CreateCommandList(dev, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc[0], NULL,
&IID_ID3D12GraphicsCommandList, (void **)&list), "list");
API(ID3D12Device_CreateCommandList(dev, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, aux_alloc, NULL,
&IID_ID3D12GraphicsCommandList, (void **)&aux), "aux list");
API(ID3D12GraphicsCommandList_Close(aux), "close aux");
/* resources */
const D3D12_CLEAR_VALUE black_clear = {.Format = DXGI_FORMAT_R8G8B8A8_UNORM, .Color = {0, 0, 0, 1}};
const D3D12_CLEAR_VALUE depth_clear = {.Format = DXGI_FORMAT_D32_FLOAT, .DepthStencil = {1.0f, 0}};
ID3D12Resource *back[2];
for (UINT i = 0; i < 2; i++)
API(IDXGISwapChain3_GetBuffer(swap, i, &IID_ID3D12Resource, (void **)&back[i]), "GetBuffer");
ID3D12Resource *off = texture(W, H, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, &black_clear);
ID3D12Resource *post = texture(W, H, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, NULL);
ID3D12Resource *depth = texture(W, H, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
D3D12_RESOURCE_STATE_DEPTH_WRITE, &depth_clear);
ID3D12Resource *ta = texture(2, 2, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE,
D3D12_RESOURCE_STATE_COPY_DEST, NULL);
ID3D12Resource *tb = texture(2, 2, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE,
D3D12_RESOURCE_STATE_COPY_DEST, NULL);
Vertex verts[8];
quad_vertices(verts, 96, 96, 0.25f); /* B, near */
quad_vertices(verts + 4, 32, 32, 0.5f); /* A, far */
const unsigned short indices[6] = {0, 1, 2, 2, 1, 3};
ID3D12Resource *vb = buffer(D3D12_HEAP_TYPE_DEFAULT, sizeof verts, D3D12_RESOURCE_STATE_COPY_DEST);
ID3D12Resource *ib = buffer(D3D12_HEAP_TYPE_DEFAULT, sizeof indices, D3D12_RESOURCE_STATE_COPY_DEST);
/* one upload buffer: vertices, indices, then the two textures at 512-byte offsets */
unsigned char staging[2048];
memset(staging, 0, sizeof staging);
memcpy(staging, verts, sizeof verts);
memcpy(staging + 256, indices, sizeof indices);
for (int row = 0; row < 2; row++) {
memcpy(staging + 512 + row * 256, TEX_A[row * 2], 8);
memcpy(staging + 1024 + row * 256, TEX_B[row * 2], 8);
}
if (!strcmp(fault, "upload")) staging[512] ^= 255; /* wrong texel data reaches the GPU */
ID3D12Resource *up = buffer(D3D12_HEAP_TYPE_UPLOAD, sizeof staging, D3D12_RESOURCE_STATE_GENERIC_READ);
fill(up, staging, sizeof staging);
ID3D12GraphicsCommandList_CopyBufferRegion(list, vb, 0, up, 0, sizeof verts);
ID3D12GraphicsCommandList_CopyBufferRegion(list, ib, 0, up, 256, sizeof indices);
for (int t = 0; t < 2; t++) {
D3D12_TEXTURE_COPY_LOCATION dst = {.pResource = t ? tb : ta,
.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX};
D3D12_TEXTURE_COPY_LOCATION src = {.pResource = up, .Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT};
src.PlacedFootprint.Offset = 512 + 512 * (UINT64)t;
src.PlacedFootprint.Footprint = (D3D12_SUBRESOURCE_FOOTPRINT){DXGI_FORMAT_R8G8B8A8_UNORM, 2, 2, 1, 256};
ID3D12GraphicsCommandList_CopyTextureRegion(list, &dst, 0, 0, 0, &src, NULL);
barrier(list, t ? tb : ta, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
}
barrier(list, vb, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
barrier(list, ib, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER);
wait_for(submit(list));
ID3D12Resource_Release(up);
/* constant buffer: per slot, one 256-byte entry for quad B and one for quad A */
ID3D12Resource *cb = buffer(D3D12_HEAP_TYPE_UPLOAD, SLOTS * 2 * 256, D3D12_RESOURCE_STATE_GENERIC_READ);
unsigned char *cb_ptr = NULL;
{
D3D12_RANGE none = {0, 0};
API(ID3D12Resource_Map(cb, 0, &none, (void **)&cb_ptr), "map constants");
}
ID3D12Resource *readback = buffer(D3D12_HEAP_TYPE_READBACK, ROW_PITCH * H, D3D12_RESOURCE_STATE_COPY_DEST);
/* descriptors */
ID3D12DescriptorHeap *rtv_heap = heap_of(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 3, 0);
ID3D12DescriptorHeap *dsv_heap = heap_of(D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, 0);
ID3D12DescriptorHeap *srv_heap = heap_of(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5, 1);
ID3D12DescriptorHeap *smp_heap = heap_of(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, 1);
const UINT rtv_step = ID3D12Device_GetDescriptorHandleIncrementSize(dev, D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
const UINT srv_step = ID3D12Device_GetDescriptorHandleIncrementSize(dev, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
D3D12_CPU_DESCRIPTOR_HANDLE rtv0 = ID3D12DescriptorHeap_GetCPUDescriptorHandleForHeapStart(rtv_heap);
D3D12_CPU_DESCRIPTOR_HANDLE dsv = ID3D12DescriptorHeap_GetCPUDescriptorHandleForHeapStart(dsv_heap);
D3D12_CPU_DESCRIPTOR_HANDLE srv0 = ID3D12DescriptorHeap_GetCPUDescriptorHandleForHeapStart(srv_heap);
D3D12_GPU_DESCRIPTOR_HANDLE gpu0 = ID3D12DescriptorHeap_GetGPUDescriptorHandleForHeapStart(srv_heap);
D3D12_CPU_DESCRIPTOR_HANDLE rtv[3];
for (UINT i = 0; i < 3; i++) {
rtv[i].ptr = rtv0.ptr + (SIZE_T)i * rtv_step;
ID3D12Device_CreateRenderTargetView(dev, i < 2 ? back[i] : off, NULL, rtv[i]);
}
ID3D12Device_CreateDepthStencilView(dev, depth, NULL, dsv);
ID3D12Resource *srv_res[5] = {ta, tb, off, NULL, post};
D3D12_GPU_DESCRIPTOR_HANDLE table[5];
for (UINT i = 0; i < 5; i++) {
D3D12_CPU_DESCRIPTOR_HANDLE h = {srv0.ptr + (SIZE_T)i * srv_step};
table[i].ptr = gpu0.ptr + (UINT64)i * srv_step;
if (srv_res[i]) ID3D12Device_CreateShaderResourceView(dev, srv_res[i], NULL, h);
else ID3D12Device_CreateUnorderedAccessView(dev, post, NULL, NULL, h);
}
D3D12_SAMPLER_DESC smp = {.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT,
.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER, .MaxLOD = D3D12_FLOAT32_MAX};
ID3D12Device_CreateSampler(dev, &smp, ID3D12DescriptorHeap_GetCPUDescriptorHandleForHeapStart(smp_heap));
D3D12_GPU_DESCRIPTOR_HANDLE smp_table = ID3D12DescriptorHeap_GetGPUDescriptorHandleForHeapStart(smp_heap);
gate("graphics.init", 1, "device queue allocators lists fence swapchain resources descriptor heaps");
ID3DBlob *vsq = compile("vs_quad", "vs_5_0"), *psq = compile("ps_quad", "ps_5_0");
ID3DBlob *vsf = compile("vs_full", "vs_5_0"), *psf = compile("ps_full", "ps_5_0");
ID3DBlob *csb = compile("cs_main", "cs_5_0");
ID3D12RootSignature *rs_gfx = root_signature(0), *rs_cs = root_signature(1);
ID3D12PipelineState *pso_quad = graphics_pipeline(rs_gfx, vsq, psq, 1, strcmp(fault, "depth") != 0);
ID3D12PipelineState *pso_full = graphics_pipeline(rs_gfx, vsf, psf, 0, 0);
ID3D12PipelineState *pso_cs = NULL;
D3D12_COMPUTE_PIPELINE_STATE_DESC cd = {.pRootSignature = rs_cs,
.CS = {ID3D10Blob_GetBufferPointer(csb), ID3D10Blob_GetBufferSize(csb)}};
API(ID3D12Device_CreateComputePipelineState(dev, &cd, &IID_ID3D12PipelineState, (void **)&pso_cs), "compute PSO");
ID3D10Blob_Release(vsq);
ID3D10Blob_Release(psq);
ID3D10Blob_Release(vsf);
ID3D10Blob_Release(psf);
ID3D10Blob_Release(csb);
gate("shader.compile", 1, "root signatures, two graphics and one compute pipeline (shader model 5.0)");
static const WPARAM script[5] = {VK_RIGHT, VK_RIGHT, VK_DOWN, VK_LEFT, VK_DOWN};
int injected = 0, verified = 0, bad_frames = 0, presented = 0, churns = 0, churn_ok = 1;
unsigned long long digest = 1469598103934665603ULL;
double mem_warm = -1.0, mem_peak = 0.0, prev = now_ms(), next_sample = 60000.0;
int last_keys = 0, after_keys = 0;
const int warmup = frames / 5;
const D3D12_VIEWPORT vp = {0, 0, W, H, 0, 1};
const D3D12_RECT scissor = {0, 0, W, H};
const float black[4] = {0, 0, 0, 1};
const D3D12_VERTEX_BUFFER_VIEW vbv = {ID3D12Resource_GetGPUVirtualAddress(vb), sizeof verts, sizeof(Vertex)};
const D3D12_INDEX_BUFFER_VIEW ibv = {ID3D12Resource_GetGPUVirtualAddress(ib), sizeof indices,
DXGI_FORMAT_R16_UINT};
ID3D12DescriptorHeap *heaps[2] = {srv_heap, smp_heap};
const double loop_start = now_ms();
if (external) printf("ready for input: right right down left down\n");
int f = 0, last = 0;
for (; !last && !quit_requested; f++) {
if (!external && strcmp(fault, "input") && injected < 5 && f == (injected + 1) * (frames / 8)) {
WIN(PostMessageA(hwnd, WM_KEYDOWN, script[injected], 0), "PostMessage");
injected++;
}
pump();
const int keys_changed = keys_seen != last_keys;
last_keys = keys_seen;
if (external) {
if (keys_seen >= 5) after_keys++;
last = after_keys >= 30 || now_ms() - loop_start > input_timeout_s * 1000.0;
} else if (duration_s) {
last = f >= frames - 1 && now_ms() - loop_start >= duration_s * 1000.0;
} else {
last = f == frames - 1;
}
const unsigned marker = (unsigned)(f + 1) & 0xffff;
const int bx = 96 + off_x, by = 96 + off_y;
const int slot = f % SLOTS;
const double slot_begin = now_ms();
wait_for(slot_value[slot]);
const double slot_end = now_ms();
Constants moved = {off_x / 128.0f, -off_y / 128.0f, strcmp(fault, "stale") ? marker : 1u, 0};
Constants fixed = {0.0f, 0.0f, moved.marker, 0};
memcpy(cb_ptr + slot * 512, &moved, sizeof moved);
memcpy(cb_ptr + slot * 512 + 256, &fixed, sizeof fixed);
const D3D12_GPU_VIRTUAL_ADDRESS cb_va = ID3D12Resource_GetGPUVirtualAddress(cb) + (UINT64)slot * 512;
const UINT bb = IDXGISwapChain3_GetCurrentBackBufferIndex(swap);
const int check = f == 0 || last || f % verify_every == 0 ||
(injected && f == injected * (frames / 8) + 1) || (external && keys_changed);
API(ID3D12CommandAllocator_Reset(alloc[slot]), "allocator reset");
API(ID3D12GraphicsCommandList_Reset(list, alloc[slot], NULL), "list reset");
ID3D12GraphicsCommandList_SetDescriptorHeaps(list, 2, heaps);
ID3D12GraphicsCommandList_RSSetViewports(list, 1, &vp);
ID3D12GraphicsCommandList_RSSetScissorRects(list, 1, &scissor);
/* pass 1 */
barrier(list, off, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET);
ID3D12GraphicsCommandList_OMSetRenderTargets(list, 1, &rtv[2], FALSE, &dsv);
ID3D12GraphicsCommandList_ClearRenderTargetView(list, rtv[2], black, 0, NULL);
ID3D12GraphicsCommandList_ClearDepthStencilView(list, dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, NULL);
ID3D12GraphicsCommandList_SetGraphicsRootSignature(list, rs_gfx);
ID3D12GraphicsCommandList_SetPipelineState(list, pso_quad);
ID3D12GraphicsCommandList_IASetPrimitiveTopology(list, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
ID3D12GraphicsCommandList_IASetVertexBuffers(list, 0, 1, &vbv);
ID3D12GraphicsCommandList_IASetIndexBuffer(list, &ibv);
ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(list, 2, smp_table);
if (strcmp(fault, "blank")) {
ID3D12GraphicsCommandList_SetGraphicsRootConstantBufferView(list, 0, cb_va);
ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(list, 1, table[1]);
ID3D12GraphicsCommandList_DrawIndexedInstanced(list, 6, 1, 0, 0, 0);
ID3D12GraphicsCommandList_SetGraphicsRootConstantBufferView(list, 0, cb_va + 256);
ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(list, 1, table[0]);
ID3D12GraphicsCommandList_DrawIndexedInstanced(list, 6, 1, 0, 4, 0);
}
barrier(list, off, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
/* pass 2 */
barrier(list, post, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
ID3D12GraphicsCommandList_SetComputeRootSignature(list, rs_cs);
ID3D12GraphicsCommandList_SetPipelineState(list, pso_cs);
ID3D12GraphicsCommandList_SetComputeRootConstantBufferView(list, 0, cb_va);
ID3D12GraphicsCommandList_SetComputeRootDescriptorTable(list, 1, table[2]);
ID3D12GraphicsCommandList_SetComputeRootDescriptorTable(list, 2, table[3]);
ID3D12GraphicsCommandList_Dispatch(list, W / 8, H / 8, 1);
barrier(list, post, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
/* pass 3 */
barrier(list, back[bb], D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);
ID3D12GraphicsCommandList_OMSetRenderTargets(list, 1, &rtv[bb], FALSE, NULL);
ID3D12GraphicsCommandList_SetGraphicsRootSignature(list, rs_gfx);
ID3D12GraphicsCommandList_SetPipelineState(list, pso_full);
ID3D12GraphicsCommandList_SetGraphicsRootConstantBufferView(list, 0, cb_va);
ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(list, 1, table[4]);
ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(list, 2, smp_table);
ID3D12GraphicsCommandList_DrawInstanced(list, 3, 1, 0, 0);
if (check) {
barrier(list, back[bb], D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
copy_texture(list, back[bb], readback, W, H, ROW_PITCH, 0);
barrier(list, back[bb], D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_PRESENT);
} else {
barrier(list, back[bb], D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);
}
slot_value[slot] = submit(list);
const double submit_end = now_ms();
if (check) {
wait_for(slot_value[slot]);
const unsigned char *mapped = NULL;
API(ID3D12Resource_Map(readback, 0, NULL, (void **)&mapped), "map readback");
int mismatches = 0;
for (int y = 0; y < H; y++) {
const unsigned char *row = mapped + (size_t)y * ROW_PITCH;
for (int x = 0; x < W; x++) {
unsigned char e[4];
expected_pixel(x, y, marker, bx, by, !strcmp(fault, "color"), e);
if (memcmp(row + x * 4, e, 4) && !mismatches++)
printf("mismatch frame=%d x=%d y=%d got=%u,%u,%u,%u want=%u,%u,%u,%u\n", f, x, y,
row[x * 4], row[x * 4 + 1], row[x * 4 + 2], row[x * 4 + 3], e[0], e[1], e[2], e[3]);
for (int c = 0; c < 4; c++) digest = (digest ^ row[x * 4 + c]) * 1099511628211ULL;
}
}
D3D12_RANGE none = {0, 0};
ID3D12Resource_Unmap(readback, 0, &none);
verified++;
if (mismatches) bad_frames++;
}
const double present_begin = now_ms();
API(IDXGISwapChain3_Present(swap, (UINT)vsync, 0), "Present");
const double present_end = now_ms();
if (present_end - slot_begin > 100.0) {
printf("slow_frame frame=%d slot_wait_ms=%.3f record_submit_ms=%.3f readback_ms=%.3f present_ms=%.3f\n",
f, slot_end - slot_begin, submit_end - slot_end, present_begin - submit_end, present_end - present_begin);
}
presented++;
if (f == 0) {
char msg[96];
snprintf(msg, sizeof msg, "pixels=%d mismatched_frames=%d present=ok", W * H, bad_frames);
gate("frame.first", bad_frames == 0, msg);
if (!strcmp(fault, "crash")) *(volatile int *)0 = 1;
if (!strcmp(fault, "hang")) Sleep(INFINITE);
const double until=now_ms()+hold_first_ms;
while (now_ms()<until && !quit_requested) { pump(); Sleep(10); }
}
if (f % 100 == 50) {
churn_ok = churn(aux_alloc, aux, (unsigned)f) && churn_ok;
churns++;
}
const double t = now_ms();
printf("frame_ms %.4f\n", t - prev);
prev = t;
if (f == warmup) mem_warm = working_set_mb();
if (f % 50 == 0) {
const double mb = working_set_mb();
if (mb > mem_peak) mem_peak = mb;
}
if (t - loop_start >= next_sample) {
printf("sample t_s=%.0f frame=%d working_set_mb=%.1f verified=%d mismatched=%d\n",
(t - loop_start) / 1000.0, f, working_set_mb(), verified, bad_frames);
next_sample += 60000.0;
}
}
/* signal after the last Present so the final wait covers it */
const UINT64 idle = fence_next++;
API(ID3D12CommandQueue_Signal(queue, fence, idle), "final signal");
wait_for(idle);
char msg[200];
snprintf(msg, sizeof msg, "presented=%d verified=%d mismatched=%d digest=%016llx", presented, verified,
bad_frames, digest);
gate("frame.continuous", presented == f && bad_frames == 0 && (external || duration_s || presented == frames), msg);
snprintf(msg, sizeof msg, "cycles=%d", churns);
gate("resources.churn", churn_ok && (churns > 0 || presented <= 50), msg);
if (external) {
snprintf(msg, sizeof msg, "keys_seen=%d offset=%d,%d want=16,32 (delivered from outside)", keys_seen,
off_x, off_y);
gate("input", keys_seen == 5 && off_x == 16 && off_y == 32 && bad_frames == 0, msg);
} else {
snprintf(msg, sizeof msg, "posted=%d received=%d offset=%d,%d want=16,32 (PostMessage)", injected,
keys_seen, off_x, off_y);
gate("input", injected == 5 && keys_seen == 5 && off_x == 16 && off_y == 32 && bad_frames == 0, msg);
}
const double mem_end = working_set_mb();
if (mem_end > mem_peak) mem_peak = mem_end;
if (mem_warm < 0 && f <= warmup) mem_warm = mem_end; /* run ended before warm-up */
snprintf(msg, sizeof msg, "working_set_mb_after_warmup=%.1f end=%.1f peak_sampled=%.1f bound_growth=%d",
mem_warm, mem_end, mem_peak, max_growth);
gate("memory.bounded", mem_warm > 0 && mem_end > 0 && mem_end - mem_warm <= max_growth, msg);
const HRESULT removed = ID3D12Device_GetDeviceRemovedReason(dev);
snprintf(msg, sizeof msg, "device_removed_reason=0x%08lx", (unsigned long)removed);
gate("device.healthy", removed == S_OK, msg);
if (hold_ms > 0) {
/* the last presented image stays in the window; keep handling messages */
printf("holding hold_ms=%d\n", hold_ms);
const double until = now_ms() + hold_ms;
while (now_ms() < until && !quit_requested) {
pump();
Sleep(10);
}
}
ID3D12Resource_Unmap(cb, 0, NULL);
#define DROP(p, vt) vt##_Release(p)
DROP(pso_cs, ID3D12PipelineState);
DROP(pso_full, ID3D12PipelineState);
DROP(pso_quad, ID3D12PipelineState);
DROP(rs_cs, ID3D12RootSignature);
DROP(rs_gfx, ID3D12RootSignature);
DROP(smp_heap, ID3D12DescriptorHeap);
DROP(srv_heap, ID3D12DescriptorHeap);
DROP(dsv_heap, ID3D12DescriptorHeap);
DROP(rtv_heap, ID3D12DescriptorHeap);
ID3D12Resource *owned[] = {readback, cb, ib, vb, tb, ta, depth, post, off, back[0], back[1]};
for (size_t i = 0; i < sizeof owned / sizeof owned[0]; i++) ID3D12Resource_Release(owned[i]);
DROP(aux, ID3D12GraphicsCommandList);
DROP(list, ID3D12GraphicsCommandList);
DROP(aux_alloc, ID3D12CommandAllocator);
for (int i = 0; i < SLOTS; i++) DROP(alloc[i], ID3D12CommandAllocator);
DROP(swap, IDXGISwapChain3);
DROP(swap1, IDXGISwapChain1);
DROP(factory, IDXGIFactory4);
DROP(fence, ID3D12Fence);
DROP(queue, ID3D12CommandQueue);
const ULONG refs = ID3D12Device_Release(dev);
int clean = CloseHandle(fence_event) != 0;
clean = DestroyWindow(hwnd) && clean;
pump();
snprintf(msg, sizeof msg, "window_destroyed device_refs_after_release=%lu", (unsigned long)refs);
gate("shutdown", clean && refs == 0, msg);
if (failures) {
printf("FAIL integrated12 failed_gates=%d\n", failures);
return 1;
}
printf("PASS integrated12 frames=%d verified=%d\n", presented, verified);
return 0;
}
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Drive the D3D12 workload with macOS keyboard events.
Starts the workload through `betterxen hybrid run` with `--external-input`, finds its window,
brings that process to the front and posts key events to that process only
(CGEventPostToPid), so nothing is typed into any other application. The events travel macOS
-> Wine's Mac driver -> the Windows message queue. They are synthesized, not typed on a
keyboard. Needs the Accessibility permission, `swiftc` and a logged-in GUI session.
usage: send_keys.py RUNNER BOTTLE EXE [--keys right,right,down,left,down] [--expect pass|fail]
"""
import argparse
import json
import subprocess
import sys
import tempfile
import time
import uuid
from pathlib import Path
CODES = {"left": 123, "right": 124, "down": 125, "up": 126}
SENDER = r"""
import AppKit
let title = CommandLine.arguments[1]
guard CGPreflightPostEventAccess() else { print("no event-posting permission"); exit(3) }
var pid: pid_t = 0
for _ in 0..<120 {
let all = CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]] ?? []
if let w = all.first(where: { ($0[kCGWindowName as String] as? String) == title }) {
pid = pid_t(w[kCGWindowOwnerPID as String] as! Int32); break
}
usleep(250_000)
}
guard pid > 0 else { print("window not found"); exit(4) }
sleep(2)
NSRunningApplication(processIdentifier: pid)?.activate(options: [])
sleep(1)
for code in CommandLine.arguments.dropFirst(2).compactMap({ UInt16($0) }) {
for down in [true, false] {
CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: down)?.postToPid(pid)
usleep(60_000)
}
usleep(250_000)
}
print("posted to pid \(pid)")
"""
def main():
p = argparse.ArgumentParser()
p.add_argument("runner")
p.add_argument("bottle")
p.add_argument("exe")
p.add_argument("--keys", default="right,right,down,left,down")
p.add_argument("--expect", choices=["pass", "fail"], default="pass")
a = p.parse_args()
codes = [str(CODES[k]) for k in a.keys.split(",") if k]
title = "BetterXen input " + uuid.uuid4().hex
with tempfile.TemporaryDirectory() as tmp:
source, binary = Path(tmp) / "send.swift", Path(tmp) / "send"
source.write_text(SENDER)
subprocess.run(["swiftc", "-O", str(source), "-o", str(binary)], check=True)
record = open(Path(tmp) / "run.json", "w+")
run = subprocess.Popen(
[a.runner, "hybrid", "run", "--bottle", a.bottle, "--timeout", "90", "--",
a.exe, "--external-input", "--input-timeout-s", "20", "--window-title", title],
stdout=record, stderr=subprocess.DEVNULL)
sent = subprocess.run([str(binary), title] + codes, capture_output=True, text=True, timeout=60)
print(sent.stdout.strip())
run.wait(timeout=120)
record.seek(0)
result = json.load(record)
gates = {g["name"]: g for g in result["gates"]}
if sent.returncode != 0 or "input" not in gates:
print(f"FAIL keyboard: the events were not sent or the workload reported no input gate "
f"(sender exit {sent.returncode}, run {result['classification']})")
return 1
print("workload:", gates["input"]["detail"])
passed = gates["input"]["passed"]
if passed == (a.expect == "pass"):
print(f"PASS keyboard: input gate {'passed' if passed else 'failed'} as expected")
return 0
print(f"FAIL keyboard: input gate {'passed' if passed else 'failed'}, expected {a.expect}")
return 1
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,5 @@
# SPDX-License-Identifier: GPL-3.0-or-later
add_executable(d3d12-lifetime lifetime.c)
target_compile_options(d3d12-lifetime PRIVATE -Wall -Wextra -Werror)
target_link_options(d3d12-lifetime PRIVATE -Wl,--no-insert-timestamp)
target_link_libraries(d3d12-lifetime PRIVATE d3d12 dxgi dxguid user32)
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
set -eu
TC=${1:?usage: build.sh LLVM_MINGW_DIR [OUTPUT_DIR]}
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/../../.." && pwd)
OUT=${2:-"$ROOT/artifacts/hybrid-workloads/x86_64"}
"$ROOT/scripts/hybrid/check-toolchain.sh" "$TC"
mkdir -p "$OUT"
"$TC/bin/x86_64-w64-mingw32-clang" -std=c11 -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
"$ROOT/tests/conformance/test_d3d12_lifetime/lifetime.c" -o "$OUT/d3d12-lifetime.exe" -ld3d12 -ldxgi -ldxguid -luser32
@@ -0,0 +1,128 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original minimal DXGI lifetime probe. No shaders, assets or third-party implementation.
// A private-data IUnknown acts as a lifetime witness: DXGI must AddRef it on attachment
// and Release it when the swapchain's private data is destroyed. This independently tests
// retention without treating a backend's numeric Release return as the only evidence.
// Public contract: https://learn.microsoft.com/windows/win32/api/dxgi/nf-dxgi-idxgiobject-setprivatedatainterface
#define COBJMACROS
#define WIDL_C_INLINE_WRAPPERS /* struct-returning D3D12 methods in C (mingw-w64) */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <d3d12.h>
#include <dxgi1_4.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Witness { IUnknown iface; LONG refs; } Witness;
static HRESULT STDMETHODCALLTYPE query(IUnknown *self, REFIID iid, void **out) {
if (!out) return E_POINTER;
*out = NULL;
if (!IsEqualGUID(iid, &IID_IUnknown)) return E_NOINTERFACE;
*out = self;
IUnknown_AddRef(self);
return S_OK;
}
static ULONG STDMETHODCALLTYPE addref(IUnknown *self) {
return (ULONG)InterlockedIncrement(&((Witness *)self)->refs);
}
static ULONG STDMETHODCALLTYPE release(IUnknown *self) {
LONG refs = InterlockedDecrement(&((Witness *)self)->refs);
if (!refs) free(self);
return (ULONG)refs;
}
static IUnknownVtbl witness_vtbl = {query, addref, release};
static const GUID witness_guid = {0xd84f72b1, 0xe7f2, 0x449f, {0xa4,0x48,0x52,0x11,0x01,0x47,0x66,0x10}};
#define API(expr) do { HRESULT code=(expr); if (FAILED(code)) { printf("FAIL %s hr=0x%08lx\n", #expr, (unsigned long)code); return 3; } } while(0)
static void drain(unsigned ms) {
DWORD start = GetTickCount();
do {
MSG message;
while (PeekMessageA(&message, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&message); DispatchMessageA(&message);
}
Sleep(10);
} while (GetTickCount() - start < ms);
}
int main(int argc, char **argv) {
setvbuf(stdout, NULL, _IONBF, 0);
int cycles=12, early_destroy=0, detach=0, resize=0, query3=0, present=0, retain_control=0;
for (int i=1;i<argc;i++) {
if (!strcmp(argv[i],"--destroy-first")) early_destroy=1;
else if (!strcmp(argv[i],"--detach-witness")) detach=1;
else if (!strcmp(argv[i],"--resize")) resize=1;
else if (!strcmp(argv[i],"--query-interface")) query3=1;
else if (!strcmp(argv[i],"--present")) present=1;
else if (!strcmp(argv[i],"--retain-app-reference")) retain_control=1;
else if (!strcmp(argv[i],"--cycles") && i+1<argc) cycles=atoi(argv[++i]);
else { puts("FAIL usage"); return 3; }
}
if (cycles<1 || cycles>100) return 3;
ID3D12Device *device=NULL;
HRESULT code=D3D12CreateDevice(NULL,D3D_FEATURE_LEVEL_11_0,&IID_ID3D12Device,(void **)&device);
if (FAILED(code)) { printf("NO DEVICE hr=0x%08lx\n",(unsigned long)code); return 2; }
IDXGIFactory4 *factory=NULL;
API(CreateDXGIFactory1(&IID_IDXGIFactory4,(void **)&factory));
/* Name the implementation that actually answered; a requested backend is not evidence. */
IDXGIAdapter1 *adapter=NULL;
DXGI_ADAPTER_DESC1 desc={0};
LUID luid;
luid=ID3D12Device_GetAdapterLuid(device);
API(IDXGIFactory4_EnumAdapterByLuid(factory,luid,&IID_IDXGIAdapter1,(void **)&adapter));
API(IDXGIAdapter1_GetDesc1(adapter,&desc));
printf("adapter=%ls vendor=0x%04x device=0x%04x\n",desc.Description,desc.VendorId,desc.DeviceId);
IDXGIAdapter1_Release(adapter);
ID3D12CommandQueue *queue=NULL;
D3D12_COMMAND_QUEUE_DESC qd={.Type=D3D12_COMMAND_LIST_TYPE_DIRECT};
API(ID3D12Device_CreateCommandQueue(device,&qd,&IID_ID3D12CommandQueue,(void **)&queue));
Witness *w=calloc(1,sizeof *w);
if (!w) return 3;
w->iface.lpVtbl=&witness_vtbl; w->refs=1;
WNDCLASSA wc={.lpfnWndProc=DefWindowProcA,.hInstance=GetModuleHandleA(NULL),.lpszClassName="BetterXenLifetime"};
if (!RegisterClassA(&wc)) return 3;
for (int n=0;n<cycles;n++) {
HWND window=CreateWindowA(wc.lpszClassName,"BetterXen lifetime probe",WS_OVERLAPPEDWINDOW|WS_VISIBLE,
32,32,128,128,NULL,NULL,wc.hInstance,NULL);
if (!window) return 3;
DXGI_SWAP_CHAIN_DESC1 sd={.Width=64,.Height=64,.Format=DXGI_FORMAT_R8G8B8A8_UNORM,
.SampleDesc={1,0},.BufferUsage=DXGI_USAGE_RENDER_TARGET_OUTPUT,.BufferCount=2,
.SwapEffect=DXGI_SWAP_EFFECT_FLIP_DISCARD};
IDXGISwapChain1 *swap=NULL;
API(IDXGIFactory4_CreateSwapChainForHwnd(factory,(IUnknown *)queue,window,&sd,NULL,NULL,&swap));
/* AddRef/Release pair: the count the application is handed, before it does anything else. */
IDXGISwapChain1_AddRef(swap);
ULONG refs_after_create=IDXGISwapChain1_Release(swap);
LONG before=w->refs;
API(IDXGISwapChain1_SetPrivateDataInterface(swap,&witness_guid,(IUnknown *)w));
if (w->refs != before+1) { puts("FAIL private-data attachment did not AddRef the witness"); return 1; }
IDXGISwapChain3 *swap3=NULL;
if (query3) API(IDXGISwapChain1_QueryInterface(swap,&IID_IDXGISwapChain3,(void **)&swap3));
if (resize) API(IDXGISwapChain1_ResizeBuffers(swap,2,96,64,DXGI_FORMAT_UNKNOWN,0));
if (present) { API(IDXGISwapChain1_Present(swap,0,0)); drain(50); }
if (detach) API(IDXGISwapChain1_SetPrivateDataInterface(swap,&witness_guid,NULL));
if (detach && w->refs != before) { puts("FAIL private-data detachment did not Release the witness"); return 1; }
if (retain_control) IUnknown_AddRef((IUnknown *)w); /* deliberate ownership fault */
if (early_destroy && !DestroyWindow(window)) return 3;
if (swap3) IDXGISwapChain3_Release(swap3);
ULONG swap_refs=IDXGISwapChain1_Release(swap);
if (!early_destroy && !DestroyWindow(window)) return 3;
drain(100);
ULONG device_refs=ID3D12Device_AddRef(device)-1;
ID3D12Device_Release(device);
printf("cycle=%d witness_refs=%ld swap_refs_after_create=%lu swap_release_return=%lu device_refs=%lu\n",
n+1,(long)w->refs,(unsigned long)refs_after_create,(unsigned long)swap_refs,(unsigned long)device_refs);
}
ID3D12CommandQueue_Release(queue);
IDXGIFactory4_Release(factory);
ULONG device_refs=ID3D12Device_Release(device);
drain(1000);
const LONG retained=w->refs-1;
printf("gate %s %s retained_witness_refs=%ld cycles=%d final_device_release=%lu no_app_gpu_submissions=1 app_reference_fault=%d\n",
detach?"resources.private-data-detach":"resources.swapchain-release",
retained==0?"pass":"FAIL",(long)retained,cycles,(unsigned long)device_refs,retain_control);
IUnknown_Release((IUnknown *)w);
UnregisterClassA(wc.lpszClassName,wc.hInstance);
return retained==0?0:1;
}
@@ -0,0 +1,5 @@
# SPDX-License-Identifier: GPL-3.0-or-later
add_executable(d3d12-wave-probe d3d12_run.c)
target_compile_options(d3d12-wave-probe PRIVATE -Wall -Wextra -Werror)
target_link_options(d3d12-wave-probe PRIVATE -Wl,--no-insert-timestamp)
target_link_libraries(d3d12-wave-probe PRIVATE d3d12 dxgi dxguid)
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
set -eu
TC=${1:?usage: build.sh LLVM_MINGW_DIR [OUTPUT_DIR]}
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/../../.." && pwd)
OUT=${2:-"$ROOT/artifacts/hybrid-workloads/x86_64"}
"$ROOT/scripts/hybrid/check-toolchain.sh" "$TC"
mkdir -p "$OUT"
"$TC/bin/x86_64-w64-mingw32-clang" -std=c11 -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
"$ROOT/tests/conformance/test_d3d12_wave/d3d12_run.c" -o "$OUT/d3d12-wave-probe.exe" -ld3d12 -ldxgi -ldxguid
@@ -0,0 +1,178 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original BetterXen workload (shader wave-semantics investigation): a minimal Direct3D 12
// compute host that is independent of the vendored recompiler.
//
// d3d12_run.exe caps
// Prints the default adapter and the device capabilities relevant to wave operations.
// d3d12_run.exe run <shader.dxil> <groups_x> <out_dwords>
// Creates a root signature with one root UAV (u0), a compute PSO from the DXIL file,
// fills a UAV buffer of <out_dwords> dwords with 0xDEADBEEF, dispatches <groups_x> groups
// and prints every dword read back as `out <index> 0x<hex>`. A dword that stays
// 0xDEADBEEF was never written.
//
// Status: `caps` and `run` have both been compiled and run under CrossOver 26.3 on the M4.
// Exit codes: 0 ran, 2 no device, 3 pipeline creation failed, 4 other D3D12 failure.
#define COBJMACROS
#include <d3d12.h>
#include <dxgi1_4.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CK(x, what) do { HRESULT h_ = (x); if (FAILED(h_)) { \
printf("FAIL %s hr=0x%08lx\n", what, (unsigned long)h_); return 4; } } while (0)
static ID3D12Device *make_device(void) {
ID3D12Device *dev = NULL;
static const D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_12_1, D3D_FEATURE_LEVEL_12_0, D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0};
for (unsigned i = 0; i < sizeof levels / sizeof *levels; i++) {
if (SUCCEEDED(D3D12CreateDevice(NULL, levels[i], &IID_ID3D12Device, (void **)&dev))) {
printf("device_created_at_feature_level=0x%x\n", (unsigned)levels[i]);
return dev;
}
}
return NULL;
}
static int caps(void) {
ID3D12Device *dev = make_device();
if (!dev) { printf("NO DEVICE\n"); return 2; }
LUID luid; dev->lpVtbl->GetAdapterLuid(dev, &luid); // (the C macro cannot return a struct)
IDXGIFactory4 *f = NULL;
if (SUCCEEDED(CreateDXGIFactory1(&IID_IDXGIFactory4, (void **)&f))) {
IDXGIAdapter1 *ad = NULL;
if (SUCCEEDED(IDXGIFactory4_EnumAdapterByLuid(f, luid, &IID_IDXGIAdapter1, (void **)&ad))) {
DXGI_ADAPTER_DESC1 d; IDXGIAdapter1_GetDesc1(ad, &d);
char n[128]; size_t i = 0; for (; d.Description[i] && i < 127; i++) n[i] = (char)d.Description[i]; n[i] = 0;
printf("adapter=%s vendor=0x%x device=0x%x vram_mb=%u shared_mb=%u\n", n, d.VendorId, d.DeviceId,
(unsigned)(d.DedicatedVideoMemory >> 20), (unsigned)(d.SharedSystemMemory >> 20));
IDXGIAdapter1_Release(ad);
}
IDXGIFactory4_Release(f);
}
D3D12_FEATURE_DATA_SHADER_MODEL sm = {D3D_SHADER_MODEL_6_7};
HRESULT h = ID3D12Device_CheckFeatureSupport(dev, D3D12_FEATURE_SHADER_MODEL, &sm, sizeof sm);
if (FAILED(h)) { sm.HighestShaderModel = D3D_SHADER_MODEL_6_6; h = ID3D12Device_CheckFeatureSupport(dev, D3D12_FEATURE_SHADER_MODEL, &sm, sizeof sm); }
printf("highest_shader_model=0x%x (query hr=0x%08lx)\n", (unsigned)sm.HighestShaderModel, (unsigned long)h);
D3D12_FEATURE_DATA_D3D12_OPTIONS o = {0};
h = ID3D12Device_CheckFeatureSupport(dev, D3D12_FEATURE_D3D12_OPTIONS, &o, sizeof o);
printf("options: hr=0x%08lx double_ops=%d min_precision=0x%x resource_binding_tier=%d\n", (unsigned long)h, o.DoublePrecisionFloatShaderOps, (unsigned)o.MinPrecisionSupport, (int)o.ResourceBindingTier);
D3D12_FEATURE_DATA_D3D12_OPTIONS1 o1 = {0};
h = ID3D12Device_CheckFeatureSupport(dev, D3D12_FEATURE_D3D12_OPTIONS1, &o1, sizeof o1);
printf("options1: hr=0x%08lx wave_ops=%d wave_lane_count_min=%u wave_lane_count_max=%u total_lane_count=%u expanded_compute_resource_states=%d int64_shader_ops=%d\n",
(unsigned long)h, o1.WaveOps, o1.WaveLaneCountMin, o1.WaveLaneCountMax, o1.TotalLaneCount, o1.ExpandedComputeResourceStates, o1.Int64ShaderOps);
ID3D12Device_Release(dev);
return 0;
}
static int run(const char *path, unsigned groups, unsigned dwords) {
FILE *fp = fopen(path, "rb");
if (!fp) { printf("FAIL open %s\n", path); return 4; }
if (fseek(fp, 0, SEEK_END)) { fclose(fp); return 4; }
long n = ftell(fp);
if (n <= 0 || n > 16 * 1024 * 1024 || fseek(fp, 0, SEEK_SET)) { fclose(fp); return 4; }
void *code = malloc((size_t)n);
if (!code) { fclose(fp); return 4; }
if (fread(code, 1, (size_t)n, fp) != (size_t)n) { printf("FAIL read\n"); return 4; }
fclose(fp);
ID3D12Device *dev = make_device();
if (!dev) { printf("NO DEVICE\n"); return 2; }
D3D12_FEATURE_DATA_D3D12_OPTIONS1 actual_caps = {0};
CK(ID3D12Device_CheckFeatureSupport(dev, D3D12_FEATURE_D3D12_OPTIONS1, &actual_caps, sizeof actual_caps), "dispatch wave capabilities");
printf("dispatch_caps wave_ops=%d min=%u max=%u\n", actual_caps.WaveOps,
actual_caps.WaveLaneCountMin, actual_caps.WaveLaneCountMax);
D3D12_ROOT_PARAMETER rp = {0};
rp.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
rp.Descriptor.ShaderRegister = 0;
rp.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
D3D12_ROOT_SIGNATURE_DESC rsd = {0};
rsd.NumParameters = 1; rsd.pParameters = &rp;
ID3DBlob *blob = NULL, *err = NULL;
CK(D3D12SerializeRootSignature(&rsd, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &err), "serialize root signature");
ID3D12RootSignature *rs = NULL;
CK(ID3D12Device_CreateRootSignature(dev, 0, ID3D10Blob_GetBufferPointer(blob), ID3D10Blob_GetBufferSize(blob), &IID_ID3D12RootSignature, (void **)&rs), "create root signature");
D3D12_COMPUTE_PIPELINE_STATE_DESC pd = {0};
pd.pRootSignature = rs;
pd.CS.pShaderBytecode = code; pd.CS.BytecodeLength = (SIZE_T)n;
ID3D12PipelineState *pso = NULL;
HRESULT h = ID3D12Device_CreateComputePipelineState(dev, &pd, &IID_ID3D12PipelineState, (void **)&pso);
if (FAILED(h)) { printf("PSO_FAILED hr=0x%08lx\n", (unsigned long)h); return 3; }
UINT64 bytes = (UINT64)dwords * 4;
D3D12_HEAP_PROPERTIES hp_def = {0}, hp_up = {0}, hp_rb = {0};
hp_def.Type = D3D12_HEAP_TYPE_DEFAULT; hp_up.Type = D3D12_HEAP_TYPE_UPLOAD; hp_rb.Type = D3D12_HEAP_TYPE_READBACK;
D3D12_RESOURCE_DESC rd = {0};
rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; rd.Width = bytes; rd.Height = 1; rd.DepthOrArraySize = 1; rd.MipLevels = 1;
rd.Format = DXGI_FORMAT_UNKNOWN; rd.SampleDesc.Count = 1; rd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
ID3D12Resource *def, *up, *rb;
D3D12_RESOURCE_DESC rdu = rd; rdu.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
CK(ID3D12Device_CreateCommittedResource(dev, &hp_def, D3D12_HEAP_FLAG_NONE, &rdu, D3D12_RESOURCE_STATE_COPY_DEST, NULL, &IID_ID3D12Resource, (void **)&def), "create default");
CK(ID3D12Device_CreateCommittedResource(dev, &hp_up, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, &IID_ID3D12Resource, (void **)&up), "create upload");
CK(ID3D12Device_CreateCommittedResource(dev, &hp_rb, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST, NULL, &IID_ID3D12Resource, (void **)&rb), "create readback");
unsigned *p; CK(ID3D12Resource_Map(up, 0, NULL, (void **)&p), "map upload");
for (unsigned i = 0; i < dwords; i++) p[i] = 0xDEADBEEFu;
ID3D12Resource_Unmap(up, 0, NULL);
D3D12_COMMAND_QUEUE_DESC qd = {0};
qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
ID3D12CommandQueue *q; CK(ID3D12Device_CreateCommandQueue(dev, &qd, &IID_ID3D12CommandQueue, (void **)&q), "queue");
ID3D12CommandAllocator *al; CK(ID3D12Device_CreateCommandAllocator(dev, D3D12_COMMAND_LIST_TYPE_DIRECT, &IID_ID3D12CommandAllocator, (void **)&al), "allocator");
ID3D12GraphicsCommandList *cl; CK(ID3D12Device_CreateCommandList(dev, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, al, pso, &IID_ID3D12GraphicsCommandList, (void **)&cl), "list");
ID3D12GraphicsCommandList_CopyBufferRegion(cl, def, 0, up, 0, bytes);
D3D12_RESOURCE_BARRIER b = {0};
b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
b.Transition.pResource = def; b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; b.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
ID3D12GraphicsCommandList_ResourceBarrier(cl, 1, &b);
ID3D12GraphicsCommandList_SetComputeRootSignature(cl, rs);
ID3D12GraphicsCommandList_SetComputeRootUnorderedAccessView(cl, 0, ID3D12Resource_GetGPUVirtualAddress(def));
ID3D12GraphicsCommandList_Dispatch(cl, groups, 1, 1);
b.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; b.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
ID3D12GraphicsCommandList_ResourceBarrier(cl, 1, &b);
ID3D12GraphicsCommandList_CopyBufferRegion(cl, rb, 0, def, 0, bytes);
CK(ID3D12GraphicsCommandList_Close(cl), "close");
ID3D12CommandList *lists[1] = {(ID3D12CommandList *)cl};
ID3D12CommandQueue_ExecuteCommandLists(q, 1, lists);
ID3D12Fence *fence; CK(ID3D12Device_CreateFence(dev, 0, D3D12_FENCE_FLAG_NONE, &IID_ID3D12Fence, (void **)&fence), "fence");
HANDLE ev = CreateEventA(NULL, FALSE, FALSE, NULL);
if (!ev) { printf("FAIL CreateEvent\n"); return 4; }
CK(ID3D12CommandQueue_Signal(q, fence, 1), "signal");
CK(ID3D12Fence_SetEventOnCompletion(fence, 1, ev), "set fence event");
if (WaitForSingleObject(ev, 30000) != WAIT_OBJECT_0) { printf("FAIL timeout waiting for the GPU\n"); return 4; }
CK(ID3D12Resource_Map(rb, 0, NULL, (void **)&p), "map readback");
for (unsigned i = 0; i < dwords; i++) printf("out %u 0x%08x\n", i, p[i]);
D3D12_RANGE none = {0, 0};
ID3D12Resource_Unmap(rb, 0, &none);
CloseHandle(ev);
ID3D12Fence_Release(fence);
ID3D12GraphicsCommandList_Release(cl);
ID3D12CommandAllocator_Release(al);
ID3D12CommandQueue_Release(q);
ID3D12Resource_Release(rb);
ID3D12Resource_Release(up);
ID3D12Resource_Release(def);
ID3D12PipelineState_Release(pso);
ID3D12RootSignature_Release(rs);
ID3D10Blob_Release(blob);
if (err) ID3D10Blob_Release(err);
ID3D12Device_Release(dev);
free(code);
return 0;
}
int main(int argc, char **argv) {
if (argc == 2 && !strcmp(argv[1], "caps")) return caps();
if (argc == 5 && !strcmp(argv[1], "run")) {
char *end;
unsigned long groups = strtoul(argv[3], &end, 10);
if (*end || groups < 1 || groups > 65535) return 1;
unsigned long words = strtoul(argv[4], &end, 10);
if (*end || words < 1 || words > 1048576) return 1;
return run(argv[2], (unsigned)groups, (unsigned)words);
}
printf("usage: d3d12_run caps | run <shader.dxil> <groups_x> <out_dwords>\n");
return 1;
}
@@ -0,0 +1,12 @@
# Wave-semantics HLSL probes
Original BetterXen sources, GPL-3.0-or-later. They are compiled with Microsoft's open-source DXC
(`dxc -T cs_6_6 -E main`; release v1.9.2609, `dxc_2026_09_29.zip`, SHA-256 `ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1`, equal to
the release digest; an external tool, not vendored) and dispatched with `d3d12_run.exe run <shader.dxil> 1 <dwords>`
under CrossOver. Build the standalone C host with `tests/conformance/test_d3d12_wave/build.sh LLVM_MINGW_DIR`; it links `-ld3d12 -ldxgi -ldxguid`. Expected values were worked out by hand before running. Results and what they show:
See `docs/research/maintainer-upstream-review.md`; observations from the excluded compiler branch do not certify this candidate. The numeric wrapper `scripts/hybrid/accept-sm6.py` verifies readback rather than relying on exit codes. The lane probe checks supported width and distinct lane IDs without assuming a portable thread-to-lane ordering.
```sh
wine --bottle <bottle> ./dxc.exe -T cs_6_6 -E main -Fo sum_f64_4.dxil sum_f64_4.hlsl # dxcompiler.dll and dxil.dll beside it
wine --bottle <bottle> ./d3d12_run.exe run sum_f64_4.dxil 1 8
```
@@ -0,0 +1,11 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Control for add_f64_4: the same run-time load, add and store in single precision. If this writes
// and the double version does not, the load/store path is not the cause.
// Expected (by hand): word 0 = 2.0f (0x40000000), word 1 = 0 for each of the 4 threads.
RWByteAddressBuffer o : register(u0);
[numthreads(4, 1, 1)]
void main(uint t : SV_GroupIndex) {
uint z = o.Load(t * 8) ^ 0xDEADBEEF;
float s = asfloat(z ^ 0x3FA00000) + asfloat(z ^ 0x3F400000); // 1.25 + 0.75
o.Store2(t * 8, uint2(asuint(s), z));
}
@@ -0,0 +1,18 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// No wave operation: a double addition 1.25 + 0.75 = 2.0 (0x4000000000000000) whose operands are
// only known at run time, so the compiler cannot fold it. The host fills the buffer with
// 0xDEADBEEF; `z` is therefore 0 when the shader runs, but not at compile time. The compiled DXIL
// must contain `fadd ... double` (check with `dxc -dumpbin`). Separates "doubles unsupported" from
// "wave operations on doubles unsupported".
// Expected (by hand): low word 0x00000000, high word 0x40000000 for each of the 4 threads.
RWByteAddressBuffer o : register(u0);
[numthreads(4, 1, 1)]
void main(uint t : SV_GroupIndex) {
uint z = o.Load(t * 8) ^ 0xDEADBEEF;
double a = asdouble(z, z ^ 0x3FF40000); // 1.25
double b = asdouble(z, z ^ 0x3FE80000); // 0.75
double s = a + b;
uint lo, hi;
asuint(s, lo, hi);
o.Store2(t * 8, uint2(lo, hi));
}
@@ -0,0 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Expected (by hand): each launched thread t stores (laneCount << 8) | t, where laneCount is the
// device's wave width (32 per the capability record), so 0x2000, 0x2001, 0x2002, 0x2003.
RWByteAddressBuffer o : register(u0);
[numthreads(4, 1, 1)]
void main(uint t : SV_GroupIndex) { o.Store(t * 4, (WaveGetLaneCount() << 8) | WaveGetLaneIndex()); }
@@ -0,0 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Expected (by hand): 4 threads each add 1.25f, every launched lane reads 5.0 = 0x40a00000.
RWByteAddressBuffer o : register(u0);
[numthreads(4, 1, 1)]
void main(uint t : SV_GroupIndex) { o.Store(t * 4, asuint(WaveActiveSum(1.25f))); }
@@ -0,0 +1,14 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// A wave sum over a double that is only known at run time (see add_f64_4.hlsl).
// Expected (by hand): 4 threads each add 1.25, sum 5.0 = 0x4014000000000000, so each stores low
// word 0x00000000 and high word 0x40140000.
// The device reports DoublePrecisionFloatShaderOps = 0; this probe shows what actually happens.
RWByteAddressBuffer o : register(u0);
[numthreads(4, 1, 1)]
void main(uint t : SV_GroupIndex) {
uint z = o.Load(t * 8) ^ 0xDEADBEEF;
double s = WaveActiveSum(asdouble(z, z ^ 0x3FF40000));
uint lo, hi;
asuint(s, lo, hi);
o.Store2(t * 8, uint2(lo, hi));
}
@@ -0,0 +1,5 @@
# SPDX-License-Identifier: GPL-3.0-or-later
add_executable(selfcheck-c selfcheck.c)
target_compile_options(selfcheck-c PRIVATE -Wall -Wextra -Werror)
target_link_options(selfcheck-c PRIVATE -Wl,--no-insert-timestamp)
target_link_libraries(selfcheck-c PRIVATE kernel32)
@@ -0,0 +1,51 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original BetterXen workload (issue #364): a Windows console program that checks itself.
// It computes CRC-32 over "123456789" (the standard check value is 0xCBF43926), runs a
// threaded counter, and prints the architecture it was compiled for. Exit code 0 means every
// check passed; non-zero names the failing check. It touches no game data and no graphics.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
static uint32_t crc32(const unsigned char *p, size_t n) {
uint32_t c = 0xFFFFFFFFu;
for (size_t i = 0; i < n; i++) {
c ^= p[i];
for (int k = 0; k < 8; k++) c = (c >> 1) ^ (0xEDB88320u & (0u - (c & 1u)));
}
return ~c;
}
static volatile LONG counter;
static DWORD WINAPI bump(LPVOID arg) {
(void)arg;
for (int i = 0; i < 100000; i++) InterlockedIncrement(&counter);
return 0;
}
// `--sleep-silent <seconds>` sleeps before printing anything, to exercise stall detection in
// the supervisor; the checks still run afterwards.
int main(int argc, char **argv) {
if (argc > 2 && !strcmp(argv[1], "--sleep-silent")) Sleep((DWORD)atoi(argv[2]) * 1000u);
#if defined(__x86_64__)
const char *arch = "x86_64";
#elif defined(__aarch64__)
const char *arch = "aarch64";
#else
const char *arch = "other";
#endif
printf("selfcheck arch=%s pointer_bits=%zu\n", arch, sizeof(void *) * 8);
uint32_t c = crc32((const unsigned char *)"123456789", 9);
if (c != 0xCBF43926u) { printf("FAIL crc32 got %08x\n", (unsigned)c); return 1; }
HANDLE t[4];
for (int i = 0; i < 4; i++) t[i] = CreateThread(NULL, 0, bump, NULL, 0, NULL);
for (int i = 0; i < 4; i++) {
if (!t[i]) { printf("FAIL CreateThread\n"); return 2; }
}
WaitForMultipleObjects(4, t, TRUE, 30000);
if (counter != 400000) { printf("FAIL counter=%ld\n", (long)counter); return 3; }
printf("PASS\n");
return 0;
}