Compare commits

..
Author SHA1 Message Date
atharvranjan 2713c9e049 Shader GPU test runner: expect the ten BetterXen tests 2026-11-25 16:35:07 -06:00
atharvranjan bd13b17f30 Merge branch 'engineering/victory-shader-crate' into engineering/shader-gpu-test-runner 2026-11-25 16:34:48 -06:00
atharvranjan 5b99b6bd63 Review fixes: report immediate samplers, hardware-only GPU test host, run-time double probes, and a per-file provenance review (import not approved) 2026-11-25 16:34:46 -06:00
atharvranjan b23e6fd6e5 Shader GPU test runner: stop on a failed build and run only executables named by this build; add a regression test 2026-11-25 16:31:12 -06:00
atharvranjan d2ca4c3995 Shader GPU test runner: expect the current seven BetterXen tests 2026-11-25 16:22:43 -06:00
atharvranjan 59b6c4db5e Merge branch 'engineering/victory-shader-crate' into engineering/shader-gpu-test-runner
# Conflicts:
#	CHANGELOG.md
2026-11-25 16:19:40 -06:00
atharvranjan ca2fe15d3e Fix the two wave-operation failures: integer f64 wave sum, device-aware 64-lane test, independent DXC probes and regression tests 2026-11-25 16:19:25 -06:00
atharvranjan 8fbef1e31f Add the shader GPU test runner script, locating the test executable through cargo's build message 2026-11-25 16:03:39 -06:00
atharvranjan 6fd254825d Vendor victory-shader (GFX10 to DXIL recompiler) from skakwy/victory-mac, with translate_native and BetterXen fixture tests 2026-11-25 16:01:53 -06:00
atharvranjan db3bdb5a5c Merge pull request #380 from MacosPorters/remove-agent-pr-checks
Remove the agent-pr-checks workflow
2026-11-25 14:48:58 -06:00
atharvranjan 9b20f78a06 Remove agent-pr-checks tests and docs 2026-11-25 14:41:35 -06:00
atharvranjan 77cec214c0 Merge pull request #378 from MacosPorters/planning/hybrid-first-transition
Transition to a CrossOver-based hybrid direction with progressive planning; archive native work
2026-11-25 14:32:48 -06:00
atharvranjan 953254a435 Remove the agent-pr-checks workflow 2026-11-25 14:30:07 -06:00
52 changed files with 892 additions and 2815 deletions

No files matched your search

-102
View File
@@ -1,102 +0,0 @@
name: Agent PR checks
# Checks pull requests against the task queue: linked claimed task, file
# ownership, overlap with other open pull requests, and independent
# verification. Runs on the base branch only: pull request code is never checked
# out or executed; changed files come from the API. Not yet run on GitHub.
#
# Advisory: problems are reported as a warning and in the run summary, but the
# check does not fail until a live smoke test and the migration of existing
# issues are done (docs/coordination/agent-tasks.md). Only a comment starting
# with /verified starts the verify job; ordinary comments start nothing.
on:
pull_request_target:
types: [opened, synchronize, reopened, edited]
issue_comment:
types: [created]
permissions: {}
jobs:
check:
if: github.event_name == 'pull_request_target'
runs-on: ubuntu-24.04-arm
permissions:
contents: read
issues: read
pull-requests: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check pull request
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
status=0
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
{
echo '## Agent PR check'
echo '```json'
cat "$RUNNER_TEMP/result.json"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
# 1 means problems were found: advisory for now. Anything else is a failure of the check itself.
if [ "$status" -eq 1 ]; then
echo "::warning title=Agent PR check (advisory)::problems found; see the run summary"
elif [ "$status" -ne 0 ]; then
exit "$status"
fi
verify:
if: github.event_name == 'issue_comment' && github.event.issue.pull_request && startsWith(github.event.comment.body, '/verified')
runs-on: ubuntu-24.04-arm
# issues: write posts the reply.
permissions:
contents: read
issues: write
pull-requests: read
concurrency:
group: agent-verify-${{ github.event.issue.number }}
cancel-in-progress: false
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Record verification and check again
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
python3 -m agent_queue decide --event "$RUNNER_TEMP/event.json" --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
# Check again only after an accepted verification of the current head: refused, stale,
# malformed or unauthorized /verified comments get a reply and nothing else.
if ! python3 -m agent_queue should-rerun --actions "$RUNNER_TEMP/actions.json"; then exit 0; fi
# pull_request_target runs are recorded against the base branch, not the pull request
# head, so the earlier check run cannot be found by head SHA. Evaluate the same check here.
status=0
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
{
echo '## Agent PR check after verification'
echo '```json'
cat "$RUNNER_TEMP/result.json"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
if [ "$status" -eq 1 ]; then
echo "::warning title=Agent PR check (advisory)::problems found; see the run summary"
elif [ "$status" -ne 0 ]; then
exit "$status"
fi
+5 -10
View File
@@ -10,16 +10,10 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- Integrated skakwy's `victory-shader` (GFX10/RDNA 2 machine code to DXIL SM 6.6 recompiler, about 43,500 lines of Rust) as `crates/victory-shader`, with provenance in its `UPSTREAM.md`, the Mesa notice preserved and 19 lines of lint-only edits to upstream files. Added `translate_native` and tests that translate BetterXen's own gfx1030 fixtures to DXIL and run them on the Apple GPU through D3D12 under CrossOver 26.3 (D3DMetal), plus `scripts/hybrid/run-shader-gpu-tests.sh`, which runs them through `betterxen-hybrid run`. Local results on the M4, not independently reproduced: 177 upstream CPU-side tests pass on macOS; all 6 fixtures with expected words (add, float-exact, bitwise-branch, or, shifts, ashr) matched the manifest on the GPU, with a negative control; the GPU tests fail without D3D12 instead of skipping; the full upstream suite under CrossOver has 224 passed, 2 failed (wave-wide reductions), 3 ignored. DXIL validation by `dxil.dll` was not run. The native RDNA-to-Metal compiler is unchanged. See `docs/research/victory-shader-integration.md`.
- Added `--stall-timeout` and a memory-settle wait to `betterxen-hybrid run`/`bench` (#385): a run that prints nothing for the given time is stopped and classified `stalled`, and after any stop the supervisor waits (up to `--settle-bound`, default 60 s) until free memory is back above the start threshold and records whether it recovered. Based on supervision lessons from skakwy's victory-mac (reimplemented, not copied). Also fixes a defect found by the first real stall run: stopping a bottle used `CX_BOTTLE`, which does not select the bottle, so a stopped Windows process kept running; it now sets `WINEPREFIX`. Verified with 4 new unit tests (stub launcher) and a real CrossOver 26.3 run on the M4: a silent workload was stopped as `stalled` after 4.7 s of a 120 s timeout, nothing was left running, and the next run passed. The low-memory recovery path is only tested with an injected memory reader. Not independently reviewed.
- Added `betterxen-hybrid run` and `bench`: launch a Windows program through an installed CrossOver (`bin/wine --bottle`, an interface CodeWeavers does not document for macOS), with timeout, the memory guard, failure classification (passed, failed exit, timed out, stopped on low memory, cannot execute, no graphics device), sampled CrossOver process memory and CPU, thermal notes, recognised host-noise diagnostics and frame statistics, and write a JSON record; `bench` repeats a workload across graphics backends. Locally verified with 24 unit tests (stub launcher) and with real runs on CrossOver 26.3 on the Apple M4.
- Executed the original Windows workloads under CrossOver 26.3 for the first time (`docs/research/crossover-baseline-2026-11-25.md`). x86-64 C, Rust, Direct3D 11 clear and triangle/frame-loop programs passed; all four ARM64 builds were rejected by CrossOver (`cannot execute`). Five-repeat, 2000-frame comparison of default, D3DMetal, DXMT, DXVK and wined3d on a trivial offscreen workload: D3DMetal's median submit-and-wait was about 1.8 times the others; this is not rendering performance. Observed on one machine, not independently reproduced, using an undocumented backend variable.
- Added `workloads/d3d11-frameloop` (indexed triangle, shaders, event-query frame loop) and negative controls for both Direct3D programs; made workload builds byte-reproducible on one machine with `--no-insert-timestamp`.
- Added `betterxen-hybrid guard`, a memory-pressure supervisor: it refuses to start a command when system-wide free memory is below a threshold and stops it (SIGTERM, then SIGKILL) when memory drops below a limit, reporting why. It is adapted from the memory guard in contributor skakwy's `victory-mac` `mac/run-victory.sh` (GPL-3.0, used with his permission) and reimplemented in Rust. Locally verified with 6 unit tests and three end-to-end runs (refuse, pass-through, stop) on macOS 27.0; the `memory_pressure -Q` output format is not a documented interface; not independently reviewed.
- Added original Windows workloads and a build script (#364, #365): a C and a Rust self-checking console program and a Direct3D 11 clear-and-readback program (`workloads/`), built for x86-64 and ARM64 with a checksum-verified llvm-mingw 20261117 by `scripts/hybrid/build-windows-workloads.sh` (`docs/research/hybrid-toolchain.md`). All six outputs were confirmed as the right PE architecture with `file`. **The x86-64 outputs were later run under CrossOver (see below).**
- Extended `docs/research/upstream-integration-audit.md` with a component-level review of skakwy's `victory-mac`: the reported ~1 FPS is, in his own notes, 1 to 1.9 s per frame of a leaked console-game dump measured by his runtime, so it is not reproducible or adoptable here. His Windows cross-link wrapper failed with Homebrew `llvm@17` and was not integrated; his Metal swizzle and D3DMetal-internals fixes are rejected; game-specific loader patches are rejected.
- Added the `betterxen-hybrid` crate (`crates/hybrid`, no third-party dependencies, native arm64) with `host`, `crossover`, `toolchain`, `frames` and `receipt` commands that print JSON: a host receipt (macOS, chip, memory, core split, whether an x86_64 binary runs under Rosetta, GPU and Metal family), CrossOver discovery limited to `Info.plist` metadata, `lipo -archs` and the documented `BottleDir` and `ManagedBottleDirs` preferences, a Windows cross-compiler probe, and frame-time statistics (nearest-rank percentiles, 1 % and 0.1 % lows, stutter count). Locally verified: 13 unit tests, clippy with warnings denied, and a run on the Apple M4 reference machine, where CrossOver is **not installed** (the report says so) and only Homebrew mingw-w64 x86_64 and i686 compilers were found. CrossOver discovery has been tested on a synthetic bundle only and has never inspected a real CrossOver; nothing launches a program or measures a game. Not independently reviewed (#353, #350, #364, #145).
- Added `docs/research/upstream-integration-audit.md` and registry and reuse-matrix rows for skakwy/victory-mac, MacBox, ScarlettMac, ossover, Whisky and rum (source read through the GitHub API, nothing executed, no code copied). Findings: MacBox and ScarlettMac are GPL-2.0 and game-specific, so they are rejected; the Game Porting Toolkit licence text (a third-party copy of version 4.0) limits use to developing, testing or evaluating games and distribution to non-commercial; contributor-reported frame results (about 1 FPS, then two rendered frames) are recorded as unverified.
- Review follow-up on the proposed `victory-shader` import (#394): `translate_native` now reports immediate samplers as static samplers (a sampled texel read 0 on the GPU before), BetterXen's GPU tests use a host that `VICTORY_WARP` cannot redirect, the double-precision probes take run-time operands and were rerun (same result), and a per-file provenance review records that the crate was developed against one commercial title's shaders. **The import is not approved; a maintainer decision is required** (`docs/research/victory-shader-provenance.md`). Earlier statements that the crate had nothing game-specific are withdrawn.
- Fixed the two wave-operation failures the vendored victory-shader tests showed under D3DMetal (`docs/research/shader-wave-semantics.md`). Device capabilities were measured with a new original D3D12 host (`workloads/d3d12-wave-probe`): shader model 6.6, wave operations, waves exactly 32 lanes, no double-precision shader operations. One failure was a wrong test precondition (a 64-lane lowering run on the 32-lane device); the test now checks the device width and asserts the recompiler's refusal. The other was unsupported double-precision operations: shaders compiled from original HLSL by Microsoft's DXC that use a `double` ran without writing anything, while float wave operations worked. The recompiler's one native-double site (`active_f64_sum`) now builds the console's balanced sum tree with its existing integer fp64 add and no longer declares doubles. Local results on one Apple M4 under CrossOver 26.3, not independently reproduced: the whole suite passes (229 passed, 3 ignored; the vendored original had 2 failures); 24 new GPU cases compare full 64-bit sums with a CPU model of the tree; both regression tests fail against the original lowering. Cost not measured; tree-order fidelity relies on the recompiler's own recognizer.
- Added `scripts/hybrid/run-shader-gpu-tests.sh`, which cross-builds the vendored `victory-shader` test executable for Windows and runs it under CrossOver through `betterxen-hybrid run` (supervision, memory guard, stall detection, JSON record), either BetterXen's ten tests or the whole upstream suite. It takes both the runner and the test executable from the messages of the cargo invocations that built them, and stops if a build fails (review fix: an earlier version piped cargo into the parser, so a failed build exited 0 and ran a stale executable, and it assumed the runner was under `target/`). `scripts/hybrid/test-run-shader-gpu-tests.sh` is a stubbed regression test for both. It needs the runner from #384 and #388. Verified on the Apple M4 with CrossOver 26.3: fixtures pass; the whole suite shows the known failures; there is no fallback to a guessed path. Not independently reviewed.
- Integrated skakwy's `victory-shader` (GFX10/RDNA 2 machine code to DXIL SM 6.6 recompiler, about 43,500 lines of Rust) as `crates/victory-shader`, with provenance in its `UPSTREAM.md`, the Mesa notice preserved and 19 lines of lint-only edits to upstream files. Added `translate_native` and tests that translate BetterXen's own gfx1030 fixtures to DXIL and, on Windows targets, run them on the GPU through D3D12. Local results on one Apple M4 with CrossOver 26.3 (D3DMetal), not independently reproduced: 177 upstream CPU-side tests pass on macOS; all 6 fixtures with expected words matched the manifest on the GPU, with a negative control; the GPU tests fail without D3D12 instead of skipping; the full upstream suite under CrossOver has 224 passed, 2 failed, 3 ignored. DXIL validation by `dxil.dll` was not run. The native RDNA-to-Metal compiler is unchanged. See `docs/research/victory-shader-integration.md`.
- Added the upstream research registry and component reuse matrix (`docs/research/`), a public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch. VIctory-family projects are excluded from reuse on provenance grounds. The GitHub project board is not yet configured because the token lacks the `project` scope (#346).
- Added hybrid research records: `docs/research/hybrid-backlog-research-2026-11-25.md` (findings and registry candidates, from search summaries) and `docs/research/primary-source-verification-2026-11-25.md` (re-check against CodeWeavers, Apple, DXMT and Wine primary pages). It confirms CrossOver's backend list, finds no public documentation of `CX_GRAPHICS_BACKEND`, and records that two Apple notices on Rosetta's end disagree; D3DMetal's license text and CrossOver's Rosetta and ARM64 plans remain unverified. Eleven issues created from the research were reviewed the same day: #364 and #365 stay in Phase 1, the others are parked and recorded under "Parked ideas" in the roadmap. Rust 1.100.0 (already installed) is the required toolchain; the default `stable` was 1.94.1. Planning only; nothing was installed or run.
- Added File > Open Executable… with Command-O to the app (#252). It opens the focused window's read-only file importer, the same one as that window's button, and is disabled when no window can present it; each window keeps its own importer, so with several windows only the focused one shows the picker. The chosen file goes through the same inspection path as the button, drag and drop and Finder Open With; nothing is executed. A file-importer failure is now shown in red with the system's description instead of being ignored, a cancelled picker shows nothing, and the message clears on the next selection. `BetterXen --smoke-import-result`, run by `scripts/build-app.sh`, checks cancellation, a shown failure and its clearing; it fails on the previous importer handling. Checked locally on Apple Silicon in the running app (Command-O and the menu item open the picker, cancel shows no error, a second Command-O opens it again, with two windows only the focused one presents it, and with every window closed the menu item is disabled); not yet independently reviewed.
@@ -29,6 +23,7 @@ remains unsupported.
- Documented the proposed guest AVX/AVX2 state and decoding contract and specified an original integer fixture with known results and fault controls (#299).
### Removed
- Removed the "Agent PR checks" workflow (`.github/workflows/agent-pr-checks.yml`), its section in `docs/coordination/agent-tasks.md` and the four workflow tests in `tests/agent_queue/test_workflows_cli.py` that only exercised it. Pull requests are no longer checked for `Closes #N`, task file patterns or `/verified` comments; the claims workflow and its tests are unchanged. The agent queue Python tests pass locally (85 tests).
- Removed the "PR template" check (`.github/workflows/pr-template.yml`, `scripts/pr_template_check.py` and its tests) and its CI test step. Also removed `.github/PULL_REQUEST_TEMPLATE.md`. Pull request descriptions are no longer validated or pre-filled; CONTRIBUTING.md still asks for the same information and the claim-first rule still applies.
### Changed
Generated
-4
View File
@@ -15,10 +15,6 @@ dependencies = [
"xenora-shader",
]
[[package]]
name = "betterxen-hybrid"
version = "0.1.0"
[[package]]
name = "bitflags"
version = "2.13.2"
+2 -2
View File
@@ -16,6 +16,6 @@ Cargo resolves the Rust packages from crates.io at the source checksums in [Carg
The [isolated fuzz workspace](fuzz/Cargo.lock) resolves developer-only dependencies, including [libfuzzer-sys](https://github.com/rust-fuzz/libfuzzer/tree/719e4efb9b8857ebaa782ae59376c8cbb78fed0f). See the [fuzz dependency inventory](docs/licenses.md#fuzz-development-dependencies) for locked revisions and selected licenses.
llvm-mingw release 20261117 is used as an external build tool for original Windows test programs under Apache-2.0 with LLVM exceptions plus its component licences; nothing from it is shipped or copied (see [hybrid-toolchain](docs/research/hybrid-toolchain.md)). `crates/hybrid/src/memory.rs` is a Rust reimplementation of the memory-guard logic in skakwy's [victory-mac](https://github.com/skakwy/victory-mac) `mac/run-victory.sh` (commit 22b3f8e45a59, GPL-3.0), used with the author's permission. The stall detection and memory-settle logic in `crates/hybrid/src/run.rs` follows supervision lessons from the same repository (`mac/PROGRESS.md`, `crates/victory-core/src/notes.rs`) and is reimplemented, not copied.
`crates/victory-shader` is vendored from skakwy's [victory-mac](https://github.com/skakwy/victory-mac) (GPL-3.0; authors and provenance in [its UPSTREAM.md](crates/victory-shader/UPSTREAM.md)); it contains opcode names generated from Mesa (MIT, Copyright (c) 2018 Valve Corporation) with the notice kept in `src/gfx10/opcodes.rs`. Its Rust dependencies are `thiserror` (MIT OR Apache-2.0), `zlib-rs` (Zlib), and on Windows targets `windows`/`windows-sys` (MIT OR Apache-2.0); versions are in `Cargo.lock`.
Microsoft's DirectX Shader Compiler (release v1.9.2609, `dxc_2026_09_29.zip`; University of Illinois/NCSA licence with MIT components per its `LICENSE-LLVM.txt`, `LICENCE-MIT.txt` and `LICENSE-MS.txt`) is used as an external tool to compile the HLSL probes in `workloads/d3d12-wave-probe/hlsl/`; it is not vendored or distributed.
-14
View File
@@ -1,14 +0,0 @@
[package]
name = "betterxen-hybrid"
description = "Host receipt, CrossOver discovery, frame-time statistics and Windows cross-toolchain probes for the hybrid direction"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[[bin]]
name = "betterxen-hybrid"
path = "src/main.rs"
-13
View File
@@ -1,13 +0,0 @@
//! 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
@@ -1,162 +0,0 @@
//! 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
@@ -1,192 +0,0 @@
//! Frame-time statistics from a list of frame intervals in milliseconds (issue #145).
//!
//! Percentiles use the nearest-rank method on the sorted intervals: the p-th percentile is
//! the value at rank ceil(p/100 * n) (1-based). "1 % low FPS" is 1000 divided by the 99th
//! percentile interval. These definitions are fixed here so reports are comparable; other
//! tools define lows differently (for example as the mean of the worst 1 %).
use crate::json::Json;
#[derive(Debug, Clone, PartialEq)]
pub struct FrameStats {
pub frames: usize,
pub total_ms: f64,
pub mean_ms: f64,
pub avg_fps: f64,
pub min_ms: f64,
pub max_ms: f64,
pub p50_ms: f64,
pub p95_ms: f64,
pub p99_ms: f64,
pub p999_ms: f64,
pub low_1pct_fps: f64,
pub low_01pct_fps: f64,
/// Frames longer than twice the median interval.
pub stutters: usize,
}
#[derive(Debug, PartialEq)]
pub enum FrameError {
Empty,
Invalid { index: usize, value: f64 },
Parse { line: usize, text: String },
}
impl std::fmt::Display for FrameError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FrameError::Empty => write!(f, "no frame intervals"),
FrameError::Invalid { index, value } => {
write!(
f,
"frame {index}: interval {value} is not a positive finite number of milliseconds"
)
}
FrameError::Parse { line, text } => {
write!(f, "line {line}: cannot parse {text:?} as milliseconds")
}
}
}
}
impl std::error::Error for FrameError {}
fn nearest_rank(sorted: &[f64], pct: f64) -> f64 {
let n = sorted.len();
let rank = ((pct / 100.0) * n as f64).ceil().max(1.0) as usize;
sorted[rank.min(n) - 1]
}
pub fn analyze(intervals_ms: &[f64]) -> Result<FrameStats, FrameError> {
if intervals_ms.is_empty() {
return Err(FrameError::Empty);
}
for (index, &value) in intervals_ms.iter().enumerate() {
if !value.is_finite() || value <= 0.0 {
return Err(FrameError::Invalid { index, value });
}
}
let mut sorted = intervals_ms.to_vec();
sorted.sort_by(|a, b| a.total_cmp(b));
let total: f64 = intervals_ms.iter().sum();
let n = sorted.len();
let p50 = nearest_rank(&sorted, 50.0);
let p99 = nearest_rank(&sorted, 99.0);
let p999 = nearest_rank(&sorted, 99.9);
Ok(FrameStats {
frames: n,
total_ms: total,
mean_ms: total / n as f64,
avg_fps: n as f64 / (total / 1000.0),
min_ms: sorted[0],
max_ms: sorted[n - 1],
p50_ms: p50,
p95_ms: nearest_rank(&sorted, 95.0),
p99_ms: p99,
p999_ms: p999,
low_1pct_fps: 1000.0 / p99,
low_01pct_fps: 1000.0 / p999,
stutters: intervals_ms.iter().filter(|&&v| v > 2.0 * p50).count(),
})
}
/// Parse one interval per line; blank lines and lines starting with `#` are skipped.
pub fn parse_intervals(text: &str) -> Result<Vec<f64>, FrameError> {
let mut out = Vec::new();
for (i, line) in text.lines().enumerate() {
let t = line.trim();
if t.is_empty() || t.starts_with('#') {
continue;
}
let v: f64 = t.parse().map_err(|_| FrameError::Parse {
line: i + 1,
text: t.to_string(),
})?;
out.push(v);
}
Ok(out)
}
impl FrameStats {
pub fn to_json(&self) -> Json {
Json::obj(vec![
("frames", Json::Num(self.frames as f64)),
("total_ms", Json::Num(self.total_ms)),
("mean_ms", Json::Num(self.mean_ms)),
("avg_fps", Json::Num(self.avg_fps)),
("min_ms", Json::Num(self.min_ms)),
("max_ms", Json::Num(self.max_ms)),
("p50_ms", Json::Num(self.p50_ms)),
("p95_ms", Json::Num(self.p95_ms)),
("p99_ms", Json::Num(self.p99_ms)),
("p999_ms", Json::Num(self.p999_ms)),
("low_1pct_fps", Json::Num(self.low_1pct_fps)),
("low_0_1pct_fps", Json::Num(self.low_01pct_fps)),
("stutters_over_2x_median", Json::Num(self.stutters as f64)),
("percentile_method", Json::str("nearest-rank")),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
// Expected values below are worked out by hand, not produced by analyze().
#[test]
fn known_answer_ten_frames() {
// Sorted: 10,10,10,10,10,10,10,10,20,100. Total 200 ms, n = 10.
let v = [10.0, 10.0, 10.0, 10.0, 20.0, 10.0, 10.0, 10.0, 100.0, 10.0];
let s = analyze(&v).unwrap();
assert_eq!(s.frames, 10);
assert_eq!(s.total_ms, 200.0);
assert_eq!(s.mean_ms, 20.0);
assert_eq!(s.avg_fps, 50.0);
assert_eq!(s.p50_ms, 10.0); // rank 5
assert_eq!(s.p95_ms, 100.0); // rank ceil(9.5) = 10
assert_eq!(s.p99_ms, 100.0);
assert_eq!(s.low_1pct_fps, 10.0);
assert_eq!(s.stutters, 1); // threshold is 2 * 10 = 20; 20 is not > 20, only 100 is.
}
#[test]
fn stutter_threshold_is_strict() {
let s = analyze(&[10.0, 10.0, 10.0, 20.0, 21.0]).unwrap();
assert_eq!(s.stutters, 1);
}
#[test]
fn one_frame_per_second() {
let s = analyze(&[1000.0, 1000.0]).unwrap();
assert_eq!(s.avg_fps, 1.0);
}
#[test]
fn rejects_bad_input() {
assert_eq!(analyze(&[]), Err(FrameError::Empty));
assert!(matches!(
analyze(&[1.0, 0.0]),
Err(FrameError::Invalid { index: 1, .. })
));
assert!(matches!(
analyze(&[f64::NAN]),
Err(FrameError::Invalid { .. })
));
assert!(matches!(analyze(&[-3.0]), Err(FrameError::Invalid { .. })));
}
#[test]
fn parses_text() {
assert_eq!(
parse_intervals("# c\n16.5\n\n 8 \n").unwrap(),
vec![16.5, 8.0]
);
assert_eq!(
parse_intervals("1\nabc\n"),
Err(FrameError::Parse {
line: 2,
text: "abc".into()
})
);
}
}
-140
View File
@@ -1,140 +0,0 @@
//! Host receipt: what this Mac is, from documented system interfaces (issue #353).
//!
//! Every field is `Option` where the probe can fail; absence is reported as null, not guessed.
use crate::cmdutil::run;
use crate::json::Json;
#[derive(Debug, Clone, PartialEq)]
pub struct HostReceipt {
pub macos_version: Option<String>,
pub macos_build: Option<String>,
pub chip: Option<String>,
pub apple_silicon: Option<bool>,
pub memory_bytes: Option<u64>,
pub logical_cpus: Option<u32>,
pub performance_cores: Option<u32>,
pub efficiency_cores: Option<u32>,
/// True only if an x86_64 slice of a system binary actually executed.
pub rosetta_executes_x86_64: Option<bool>,
pub gpu_name: Option<String>,
pub gpu_cores: Option<String>,
pub metal_support: Option<String>,
pub host_arch_of_this_binary: &'static str,
}
fn sysctl(name: &str) -> Option<String> {
run("/usr/sbin/sysctl", &["-n", name])
}
pub fn collect() -> HostReceipt {
let gpu = run(
"/usr/sbin/system_profiler",
&["SPDisplaysDataType", "-json"],
)
.and_then(|j| parse_gpu(&j));
HostReceipt {
macos_version: run("/usr/bin/sw_vers", &["-productVersion"]),
macos_build: sysctl("kern.osversion"),
chip: sysctl("machdep.cpu.brand_string"),
apple_silicon: sysctl("hw.optional.arm64").map(|v| v == "1"),
memory_bytes: sysctl("hw.memsize").and_then(|v| v.parse().ok()),
logical_cpus: sysctl("hw.logicalcpu").and_then(|v| v.parse().ok()),
performance_cores: sysctl("hw.perflevel0.physicalcpu").and_then(|v| v.parse().ok()),
efficiency_cores: sysctl("hw.perflevel1.physicalcpu").and_then(|v| v.parse().ok()),
// Executes the x86_64 slice of /usr/bin/true. Failure means Rosetta cannot run it
// now; it does not distinguish "not installed" from "disabled".
rosetta_executes_x86_64: Some(
run("/usr/bin/arch", &["-x86_64", "/usr/bin/true"]).is_some(),
),
gpu_name: gpu.as_ref().map(|g| g.0.clone()),
gpu_cores: gpu.as_ref().and_then(|g| g.1.clone()),
metal_support: gpu.as_ref().and_then(|g| g.2.clone()),
host_arch_of_this_binary: std::env::consts::ARCH,
}
}
/// Pull `sppci_model`, `sppci_cores` and `spdisplays_mtlgpufamilysupport` of the first display
/// entry from `system_profiler SPDisplaysDataType -json` output. Returns None if the model
/// key is absent. Uses a small string scan because this crate has no JSON parser dependency.
pub fn parse_gpu(json: &str) -> Option<(String, Option<String>, Option<String>)> {
let model = string_value(json, "sppci_model")?;
Some((
model,
string_value(json, "sppci_cores"),
string_value(json, "spdisplays_mtlgpufamilysupport"),
))
}
fn string_value(json: &str, key: &str) -> Option<String> {
let needle = format!("\"{key}\"");
let at = json.find(&needle)? + needle.len();
let rest = json[at..].trim_start().strip_prefix(':')?.trim_start();
let rest = rest.strip_prefix('"')?;
let end = rest.find('"')?;
Some(rest[..end].to_string())
}
impl HostReceipt {
pub fn to_json(&self) -> Json {
let n = |v: Option<u32>| v.map_or(Json::Null, |x| Json::Num(x as f64));
Json::obj(vec![
("macos_version", Json::opt_str(self.macos_version.clone())),
("macos_build", Json::opt_str(self.macos_build.clone())),
("chip", Json::opt_str(self.chip.clone())),
(
"apple_silicon",
self.apple_silicon.map_or(Json::Null, Json::Bool),
),
(
"memory_bytes",
self.memory_bytes
.map_or(Json::Null, |x| Json::Num(x as f64)),
),
("logical_cpus", n(self.logical_cpus)),
("performance_cores", n(self.performance_cores)),
("efficiency_cores", n(self.efficiency_cores)),
(
"rosetta_executes_x86_64",
self.rosetta_executes_x86_64.map_or(Json::Null, Json::Bool),
),
("gpu_name", Json::opt_str(self.gpu_name.clone())),
("gpu_cores", Json::opt_str(self.gpu_cores.clone())),
("metal_support", Json::opt_str(self.metal_support.clone())),
(
"receipt_binary_arch",
Json::str(self.host_arch_of_this_binary),
),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_gpu_fixture() {
let j = r#"{"SPDisplaysDataType":[{"sppci_cores":"10","sppci_model":"Apple M4",
"spdisplays_mtlgpufamilysupport":"spdisplays_metal4"}]}"#;
let g = parse_gpu(j).unwrap();
assert_eq!(g.0, "Apple M4");
assert_eq!(g.1.as_deref(), Some("10"));
assert_eq!(g.2.as_deref(), Some("spdisplays_metal4"));
}
#[test]
fn missing_gpu_is_none() {
assert!(parse_gpu("{}").is_none());
}
#[test]
fn collect_runs_on_this_host() {
let r = collect();
if cfg!(target_os = "macos") {
assert!(r.macos_version.is_some());
assert!(r.memory_bytes.unwrap() > 0);
}
assert!(r.to_json().render().contains("receipt_binary_arch"));
}
}
-114
View File
@@ -1,114 +0,0 @@
//! Minimal JSON value and writer. Output only; no parsing is needed by this crate.
#[derive(Debug, Clone, PartialEq)]
pub enum Json {
Null,
Bool(bool),
Num(f64),
Str(String),
Arr(Vec<Json>),
Obj(Vec<(String, Json)>),
}
impl Json {
pub fn str(s: impl Into<String>) -> Json {
Json::Str(s.into())
}
pub fn opt_str(s: Option<String>) -> Json {
s.map_or(Json::Null, Json::Str)
}
pub fn obj(fields: Vec<(&str, Json)>) -> Json {
Json::Obj(
fields
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect(),
)
}
pub fn render(&self) -> String {
let mut out = String::new();
self.write(&mut out, 0);
out.push('\n');
out
}
fn write(&self, out: &mut String, depth: usize) {
let pad = |out: &mut String, d: usize| out.push_str(&" ".repeat(d));
match self {
Json::Null => out.push_str("null"),
Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Json::Num(n) if n.is_finite() => {
if n.fract() == 0.0 && n.abs() < 1e15 {
out.push_str(&format!("{}", *n as i64));
} else {
out.push_str(&format!("{n}"));
}
}
// JSON has no NaN or infinity; refuse to invent a number.
Json::Num(_) => out.push_str("null"),
Json::Str(s) => escape(s, out),
Json::Arr(items) if items.is_empty() => out.push_str("[]"),
Json::Arr(items) => {
out.push_str("[\n");
for (i, item) in items.iter().enumerate() {
pad(out, depth + 1);
item.write(out, depth + 1);
out.push_str(if i + 1 < items.len() { ",\n" } else { "\n" });
}
pad(out, depth);
out.push(']');
}
Json::Obj(fields) if fields.is_empty() => out.push_str("{}"),
Json::Obj(fields) => {
out.push_str("{\n");
for (i, (k, v)) in fields.iter().enumerate() {
pad(out, depth + 1);
escape(k, out);
out.push_str(": ");
v.write(out, depth + 1);
out.push_str(if i + 1 < fields.len() { ",\n" } else { "\n" });
}
pad(out, depth);
out.push('}');
}
}
}
}
fn escape(s: &str, out: &mut String) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escapes_and_nests() {
let j = Json::obj(vec![
("a", Json::str("q\"\\\n\u{1}")),
(
"b",
Json::Arr(vec![Json::Num(1.0), Json::Num(0.5), Json::Null]),
),
("c", Json::Num(f64::NAN)),
]);
let r = j.render();
assert!(r.contains(r#""a": "q\"\\\n\u0001""#), "{r}");
assert!(r.contains("0.5"));
assert!(r.contains(r#""c": null"#));
}
}
-32
View File
@@ -1,32 +0,0 @@
//! BetterXen hybrid tooling: read-only inspection and measurement helpers around an
//! externally installed CrossOver. Nothing here launches a game or claims compatibility.
pub mod cmdutil;
pub mod crossover;
pub mod frames;
pub mod host;
pub mod json;
pub mod memory;
pub mod run;
pub mod toolchain;
/// Value of a top-level string key in flat JSON produced by `plutil -convert json`.
pub fn host_string(json: &str, key: &str) -> Option<String> {
let needle = format!("\"{key}\"");
let at = json.find(&needle)? + needle.len();
let rest = json[at..]
.trim_start()
.strip_prefix(':')?
.trim_start()
.strip_prefix('"')?;
let mut out = String::new();
let mut chars = rest.chars();
while let Some(c) = chars.next() {
match c {
'"' => return Some(out),
'\\' => out.push(chars.next()?),
c => out.push(c),
}
}
None
}
-325
View File
@@ -1,325 +0,0 @@
use betterxen_hybrid::{crossover, frames, host, json::Json, memory, run, toolchain};
use std::path::PathBuf;
use std::process::ExitCode;
const USAGE: &str = "usage: betterxen-hybrid <command>
host host receipt (JSON)
crossover [--app P] CrossOver installs and documented preferences (JSON)
toolchain Windows cross-compilers found on PATH (JSON)
frames <file> frame-time statistics; file has one interval in ms per line (JSON)
guard [--min-start-free N] [--min-free N] -- CMD ARGS...
run CMD; refuse to start / stop it when free memory is low
run --bottle B [--backend X] [--timeout S] [--stall-timeout S] [--settle-bound S] [--expect TEXT] [--out DIR]
[--min-start-free N] [--min-free N] -- EXE [ARGS...]
run a Windows program through CrossOver; write a JSON record
bench --bottle B --backends a,b,c [--repeat N] [same options] -- EXE [ARGS...]
run the program per backend N times; summarise frame times
receipt host + crossover + toolchain in one JSON document";
fn crossover_json(app: Option<PathBuf>) -> Json {
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
let cands = match app {
Some(p) => vec![p],
None => crossover::candidate_paths(&home),
};
let installs = crossover::discover(&cands);
Json::obj(vec![
("installed", Json::Bool(!installs.is_empty())),
(
"installs",
Json::Arr(installs.iter().map(|i| i.to_json()).collect()),
),
(
"bottle_dir_preference",
Json::opt_str(crossover::preference("BottleDir")),
),
(
"managed_bottle_dirs_preference",
Json::opt_str(crossover::preference("ManagedBottleDirs")),
),
(
"searched",
Json::Arr(
cands
.iter()
.map(|p| Json::str(p.display().to_string()))
.collect(),
),
),
(
"note",
Json::str(
"Only Info.plist metadata, lipo -archs and documented defaults keys are read. Bottle graphics backend and bundle internals are not interpreted (undocumented, #350).",
),
),
])
}
fn toolchain_json() -> Json {
let path = std::env::var("PATH").unwrap_or_default();
Json::Arr(
toolchain::probe(&path)
.iter()
.map(|c| c.to_json())
.collect(),
)
}
fn guard(args: &[String]) -> ExitCode {
let mut limits = memory::Limits {
min_start_free: 70,
min_free: 20,
poll: std::time::Duration::from_secs(1),
grace: std::time::Duration::from_secs(10),
};
let mut i = 0;
while i < args.len() && args[i] != "--" {
let v = args.get(i + 1).and_then(|v| v.parse::<u8>().ok());
match (args[i].as_str(), v) {
("--min-start-free", Some(v)) => limits.min_start_free = v,
("--min-free", Some(v)) => limits.min_free = v,
_ => {
eprintln!("{USAGE}");
return ExitCode::from(2);
}
}
i += 2;
}
let Some(cmd) = args.get(i + 1) else {
eprintln!("{USAGE}");
return ExitCode::from(2);
};
match memory::supervise(cmd, &args[i + 2..], limits, &mut memory::free_percentage) {
memory::Outcome::Exited(Some(0)) => ExitCode::SUCCESS,
memory::Outcome::Exited(c) => ExitCode::from(c.map_or(1, |c| c.clamp(1, 255)) as u8),
other => {
eprintln!("guard: {other:?}");
ExitCode::from(3)
}
}
}
struct RunArgs {
cfg: run::RunConfig,
backends: Vec<String>,
repeat: u32,
out: Option<PathBuf>,
}
fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
let mut bottle = None;
let mut backend = None;
let mut backends = Vec::new();
let mut repeat = 1u32;
let mut timeout = 300u64;
let mut stall = None;
let mut settle = 60u64;
let mut expect = None;
let mut out = None;
let (mut min_start, mut min_free) = (50u8, 15u8);
let mut i = 0;
while i < args.len() && args[i] != "--" {
let v = args
.get(i + 1)
.ok_or_else(|| format!("{} needs a value", args[i]))?
.clone();
match args[i].as_str() {
"--bottle" => bottle = Some(v),
"--backend" => backend = Some(v),
"--backends" => backends = v.split(',').map(String::from).collect(),
"--repeat" => repeat = v.parse().map_err(|_| "bad --repeat")?,
"--timeout" => timeout = v.parse().map_err(|_| "bad --timeout")?,
"--stall-timeout" => stall = Some(v.parse().map_err(|_| "bad --stall-timeout")?),
"--settle-bound" => settle = v.parse().map_err(|_| "bad --settle-bound")?,
"--expect" => expect = Some(v),
"--out" => out = Some(PathBuf::from(v)),
"--min-start-free" => min_start = v.parse().map_err(|_| "bad --min-start-free")?,
"--min-free" => min_free = v.parse().map_err(|_| "bad --min-free")?,
o => return Err(format!("unknown option {o}")),
}
i += 2;
}
let program = args.get(i + 1).ok_or("missing program after --")?.clone();
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
let installs = crossover::discover(&crossover::candidate_paths(&home));
let install = installs.first().ok_or("no CrossOver installation found")?;
let wine = run::wine_path(&install.path);
if !wine.is_file() {
return Err(format!(
"{} not found in this CrossOver build",
wine.display()
));
}
let work = out
.clone()
.unwrap_or_else(|| PathBuf::from("artifacts/hybrid-runs"));
Ok(RunArgs {
cfg: run::RunConfig {
wine,
bottle: bottle.ok_or("--bottle is required")?,
backend,
program,
args: args[i + 2..].to_vec(),
timeout: std::time::Duration::from_secs(timeout),
limits: memory::Limits {
min_start_free: min_start,
min_free,
poll: std::time::Duration::from_millis(250),
grace: std::time::Duration::from_secs(10),
},
expect,
work_dir: work,
stall_timeout: stall.map(std::time::Duration::from_secs),
settle_bound: std::time::Duration::from_secs(settle),
read_free: memory::free_percentage,
},
backends,
repeat,
out,
})
}
fn crossover_build() -> Option<String> {
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
crossover::discover(&crossover::candidate_paths(&home))
.first()
.and_then(|i| {
Some(format!(
"{} ({})",
i.short_version.clone()?,
i.build_version.clone()?
))
})
}
fn save(dir: &std::path::Path, name: &str, j: &Json) {
let _ = std::fs::create_dir_all(dir);
let _ = std::fs::write(dir.join(name), j.render());
}
fn run_cmd(args: &[String]) -> ExitCode {
let a = match parse_run_args(args) {
Ok(a) => a,
Err(e) => {
eprintln!("{e}\n{USAGE}");
return ExitCode::from(2);
}
};
let r = run::execute(&a.cfg, crossover_build());
print!("{}", r.json.render());
if let Some(dir) = &a.out {
save(
dir,
&format!(
"run-{}.json",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
),
&r.json,
);
}
if r.class == run::Class::Passed {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
fn bench_cmd(args: &[String]) -> ExitCode {
let a = match parse_run_args(args) {
Ok(a) if !a.backends.is_empty() => a,
Ok(_) => {
eprintln!("bench needs --backends\n{USAGE}");
return ExitCode::from(2);
}
Err(e) => {
eprintln!("{e}\n{USAGE}");
return ExitCode::from(2);
}
};
let build = crossover_build();
let mut per_backend = Vec::new();
let mut all_ok = true;
for b in &a.backends {
let mut runs = Vec::new();
for _ in 0..a.repeat {
let mut cfg = a.cfg.clone();
cfg.backend = if b == "default" {
None
} else {
Some(b.clone())
};
let r = run::execute(&cfg, build.clone());
all_ok &= r.class == run::Class::Passed;
runs.push(r.json);
}
per_backend.push(Json::obj(vec![
("backend", Json::str(b.clone())),
("runs", Json::Arr(runs)),
]));
}
let doc = Json::obj(vec![
("schema", Json::str("betterxen-hybrid-bench/0")),
("repeat", Json::Num(a.repeat as f64)),
("host", host::collect().to_json()),
("results", Json::Arr(per_backend)),
]);
print!("{}", doc.render());
if let Some(dir) = &a.out {
save(dir, "bench.json", &doc);
}
if all_ok {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
fn main() -> ExitCode {
match std::env::args().nth(1).as_deref() {
Some("run") => return run_cmd(&std::env::args().skip(2).collect::<Vec<_>>()),
Some("bench") => return bench_cmd(&std::env::args().skip(2).collect::<Vec<_>>()),
_ => {}
}
if std::env::args().nth(1).as_deref() == Some("guard") {
return guard(&std::env::args().skip(2).collect::<Vec<_>>());
}
let args: Vec<String> = std::env::args().skip(1).collect();
let result: Result<Json, String> = match args.first().map(String::as_str) {
Some("host") => Ok(host::collect().to_json()),
Some("crossover") => {
let app = match args.get(1).map(String::as_str) {
Some("--app") => args.get(2).map(PathBuf::from),
_ => None,
};
Ok(crossover_json(app))
}
Some("toolchain") => Ok(toolchain_json()),
Some("frames") => match args.get(1) {
None => Err("frames needs a file".into()),
Some(f) => std::fs::read_to_string(f)
.map_err(|e| format!("{f}: {e}"))
.and_then(|t| frames::parse_intervals(&t).map_err(|e| e.to_string()))
.and_then(|v| frames::analyze(&v).map_err(|e| e.to_string()))
.map(|s| s.to_json()),
},
Some("receipt") => Ok(Json::obj(vec![
("schema", Json::str("betterxen-hybrid-receipt/0")),
("host", host::collect().to_json()),
("crossover", crossover_json(None)),
("windows_cross_compilers", toolchain_json()),
])),
_ => Err(USAGE.into()),
};
match result {
Ok(j) => {
print!("{}", j.render());
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("{e}");
ExitCode::from(2)
}
}
}
-210
View File
@@ -1,210 +0,0 @@
//! Memory-pressure supervision of a child process.
//!
//! Adapted in concept from the memory guard in `mac/run-victory.sh` of
//! <https://github.com/skakwy/victory-mac> (author skakwy, GPL-3.0; commit 22b3f8e, used with
//! the author's permission): do not start a workload when little memory is free, and stop it
//! when system-wide free memory falls below a limit, because GPU memory is wired under
//! unified memory and a runaway workload can take the whole Mac down. This version is
//! reimplemented in Rust, stops the child with SIGTERM before SIGKILL, and reports why it
//! stopped. It supervises any command; it contains nothing game-specific.
//!
//! The reading is the "System-wide memory free percentage" line of `memory_pressure -Q`.
//! That line was observed on macOS 27.0 (build 26A428); its format is not a documented
//! stable interface, so an unreadable value is an error, never "assume enough memory".
use crate::cmdutil::run;
use std::process::{Child, Command};
use std::time::{Duration, Instant};
pub fn parse_free_percentage(output: &str) -> Option<u8> {
let line = output
.lines()
.find(|l| l.contains("System-wide memory free percentage"))?;
let digits: String = line
.split(':')
.nth(1)?
.trim()
.chars()
.take_while(|c| c.is_ascii_digit())
.collect();
let v: u8 = digits.parse().ok()?;
(v <= 100).then_some(v)
}
pub fn free_percentage() -> Option<u8> {
run("/usr/bin/memory_pressure", &["-Q"]).and_then(|o| parse_free_percentage(&o))
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Limits {
/// Refuse to start below this percent free.
pub min_start_free: u8,
/// Stop the child when free memory drops below this percent.
pub min_free: u8,
pub poll: Duration,
/// Time between SIGTERM and SIGKILL.
pub grace: Duration,
}
#[derive(Debug, PartialEq)]
pub enum Outcome {
/// The child ran to completion; `None` means it ended by a signal.
Exited(Option<i32>),
RefusedToStart {
free: u8,
need: u8,
},
StoppedLowMemory {
free: u8,
limit: u8,
},
/// Memory could not be read, so no guarantee can be given.
MemoryUnreadable,
SpawnFailed(String),
}
pub(crate) fn terminate(child: &mut Child, grace: Duration) {
let _ = Command::new("/bin/kill")
.args(["-TERM", &child.id().to_string()])
.status();
let t0 = Instant::now();
while t0.elapsed() < grace {
if matches!(child.try_wait(), Ok(Some(_))) {
return;
}
std::thread::sleep(Duration::from_millis(50));
}
let _ = child.kill();
let _ = child.wait();
}
/// Run `program` under `limits`, reading memory through `read_free`.
pub fn supervise(
program: &str,
args: &[String],
limits: Limits,
read_free: &mut dyn FnMut() -> Option<u8>,
) -> Outcome {
match read_free() {
None => return Outcome::MemoryUnreadable,
Some(free) if free < limits.min_start_free => {
return Outcome::RefusedToStart {
free,
need: limits.min_start_free,
};
}
Some(_) => {}
}
let mut child = match Command::new(program).args(args).spawn() {
Ok(c) => c,
Err(e) => return Outcome::SpawnFailed(format!("{program}: {e}")),
};
loop {
match child.try_wait() {
Ok(Some(status)) => return Outcome::Exited(status.code()),
Ok(None) => {}
Err(e) => return Outcome::SpawnFailed(e.to_string()),
}
match read_free() {
None => {
terminate(&mut child, limits.grace);
return Outcome::MemoryUnreadable;
}
Some(free) if free < limits.min_free => {
terminate(&mut child, limits.grace);
return Outcome::StoppedLowMemory {
free,
limit: limits.min_free,
};
}
Some(_) => {}
}
std::thread::sleep(limits.poll);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn limits() -> Limits {
Limits {
min_start_free: 50,
min_free: 20,
poll: Duration::from_millis(20),
grace: Duration::from_millis(500),
}
}
#[test]
fn parses_memory_pressure_output() {
let real = "The system has 25769803776 (1572864 pages with a page size of 16384).\nSystem-wide memory free percentage: 71%\n";
assert_eq!(parse_free_percentage(real), Some(71));
assert_eq!(
parse_free_percentage("System-wide memory free percentage: 100%"),
Some(100)
);
assert_eq!(
parse_free_percentage("System-wide memory free percentage: 101%"),
None
);
assert_eq!(
parse_free_percentage("System-wide memory free percentage: x"),
None
);
assert_eq!(parse_free_percentage("nothing"), None);
}
#[test]
fn refuses_to_start_when_low() {
let out = supervise("/usr/bin/true", &[], limits(), &mut || Some(30));
assert_eq!(out, Outcome::RefusedToStart { free: 30, need: 50 });
}
#[test]
fn unreadable_memory_is_an_error() {
assert_eq!(
supervise("/usr/bin/true", &[], limits(), &mut || None),
Outcome::MemoryUnreadable
);
}
#[test]
fn child_exit_code_is_reported() {
let out = supervise(
"/bin/sh",
&["-c".into(), "exit 7".into()],
limits(),
&mut || Some(90),
);
assert_eq!(out, Outcome::Exited(Some(7)));
}
#[test]
fn stops_child_when_memory_drops() {
let mut calls = 0;
let t0 = Instant::now();
let out = supervise("/bin/sleep", &["30".into()], limits(), &mut || {
calls += 1;
Some(if calls < 4 { 90 } else { 10 })
});
assert_eq!(
out,
Outcome::StoppedLowMemory {
free: 10,
limit: 20
}
);
assert!(
t0.elapsed() < Duration::from_secs(10),
"child was not stopped promptly"
);
}
#[test]
fn real_reading_is_available_on_macos() {
if cfg!(target_os = "macos") {
assert!(free_percentage().is_some());
}
}
}
-685
View File
@@ -1,685 +0,0 @@
//! Launch a Windows program through an installed CrossOver, supervise it, and write a
//! structured record of what happened.
//!
//! Interface used: `<CrossOver.app>/Contents/SharedSupport/CrossOver/bin/wine --bottle B EXE`
//! and `.../bin/wineserver -k`. These are **not documented by CodeWeavers** for macOS; they
//! exist in the installed build and answer `--help` (cxbottle, cxstart) as observed on build
//! 26.3.0.39832. Every record therefore carries the CrossOver build and a flag saying the
//! launcher interface is vendor-help-only. The graphics backend is selected through the
//! `CX_GRAPHICS_BACKEND` environment variable, which appears in third-party launch scripts and
//! is likewise undocumented; an unrecognised value was observed to be ignored silently, so a
//!
//! Stall detection and the wait for memory to settle after a stop follow the supervision
//! lessons in skakwy's <https://github.com/skakwy/victory-mac> (`mac/PROGRESS.md`,
//! `mac/run-victory.sh`, `crates/victory-core/src/notes.rs` at commit 22b3f8e45a59; his own
//! work, GPL-3.0, used with his permission): detect a hung run by absence of progress, stop a
//! bottle with `wineserver -k` and its prefix, and do not start the next run until memory has
//! been returned. Reimplemented here; none of his code is copied.
//!
//! A record names the backend *requested* and relies on the workload's own diagnostics
//! (adapter name, backend log lines) to show what actually ran.
use crate::frames;
use crate::json::Json;
use crate::memory;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone)]
pub struct RunConfig {
pub wine: PathBuf,
pub bottle: String,
pub backend: Option<String>,
pub program: String,
pub args: Vec<String>,
pub timeout: Duration,
pub limits: memory::Limits,
/// Text that must appear in stdout for a zero exit to count as a pass.
pub expect: Option<String>,
pub work_dir: PathBuf,
/// Stop the run when neither stdout nor stderr has grown for this long.
pub stall_timeout: Option<Duration>,
/// After a stop, wait at most this long for free memory to return to `min_start_free`.
pub settle_bound: Duration,
/// Free-memory reader; `memory::free_percentage` outside tests.
pub read_free: fn() -> Option<u8>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Class {
Passed,
FailedExit(i32),
MissingExpectedMarker,
TimedOut,
/// No output on stdout or stderr for the stall timeout.
Stalled,
StoppedLowMemory,
RefusedToStart,
/// The Windows loader did not accept the file (for example an ARM64 PE this build cannot run).
CannotExecute,
/// The workload reported that no graphics device could be created.
NoDevice,
MemoryUnreadable,
LaunchFailed,
}
impl Class {
pub fn name(&self) -> String {
match self {
Class::Passed => "passed".into(),
Class::FailedExit(c) => format!("failed_exit_{c}"),
Class::MissingExpectedMarker => "missing_expected_marker".into(),
Class::TimedOut => "timed_out".into(),
Class::Stalled => "stalled".into(),
Class::StoppedLowMemory => "stopped_low_memory".into(),
Class::RefusedToStart => "refused_to_start_low_memory".into(),
Class::CannotExecute => "cannot_execute".into(),
Class::NoDevice => "no_graphics_device".into(),
Class::MemoryUnreadable => "memory_unreadable".into(),
Class::LaunchFailed => "launch_failed".into(),
}
}
}
/// Classify a finished (or stopped) run from observable facts only.
pub fn classify(exit: Option<i32>, stdout: &str, stderr: &str, expect: Option<&str>) -> Class {
if stderr.contains("cannot execute") {
return Class::CannotExecute;
}
if stdout.contains("NO DEVICE") && exit == Some(2) {
return Class::NoDevice;
}
match exit {
Some(0) => match expect {
Some(m) if !stdout.contains(m) => Class::MissingExpectedMarker,
_ => Class::Passed,
},
Some(c) => Class::FailedExit(c),
None => Class::FailedExit(-1),
}
}
/// Known host-environment noise in CrossOver output, reported as diagnostics instead of
/// silently dropped. Returns (kind, line) for each recognised line.
pub fn diagnostics(text: &str) -> Vec<(&'static str, String)> {
let mut out = Vec::new();
for line in text.lines() {
if line.contains("LibClamAV Error") || line.contains("Can't open file or directory") {
out.push(("clamav-database-missing", line.to_string()));
} else if line.starts_with("warn:") && line.contains("DXVK") {
out.push(("dxvk-warning", line.to_string()));
}
}
out
}
/// Which graphics layer announced itself, judged from the workload's stdout and stderr.
pub fn detected_backend(output: &str) -> &'static str {
if output.contains("DXVK:") {
"dxvk"
} else if output.contains("DXMT") || output.contains("D3D_FEATURE_LEVEL_11_1\ninfo: Using") {
"dxmt"
} else if output.contains("adapter=AMD Compatibility Mode") {
"d3dmetal (inferred: Apple-reported adapter identity)"
} else if output.contains("adapter=Apple M") {
"wined3d (inferred: native adapter name, no layer banner)"
} else {
"unknown"
}
}
#[derive(Debug, Default, Clone)]
pub struct Samples {
pub peak_rss_kb: u64,
pub mean_cpu_percent_of_core: f64,
pub min_free_percent: Option<u8>,
pub samples: u32,
}
/// Sum RSS (KB) and CPU % of processes whose command line mentions the CrossOver bundle or the
/// bottle directory. Heuristic: processes not started from those paths are not counted.
fn sample_processes(needles: &[String]) -> (u64, f64) {
let Some(out) = crate::cmdutil::run("/bin/ps", &["-axo", "rss=,pcpu=,command="]) else {
return (0, 0.0);
};
let (mut rss, mut cpu) = (0u64, 0f64);
for l in out.lines() {
if !needles.iter().any(|n| l.contains(n.as_str())) {
continue;
}
let mut it = l.split_whitespace();
rss += it.next().and_then(|v| v.parse::<u64>().ok()).unwrap_or(0);
cpu += it.next().and_then(|v| v.parse::<f64>().ok()).unwrap_or(0.0);
}
(rss, cpu)
}
fn thermal() -> Json {
match crate::cmdutil::run("/usr/bin/pmset", &["-g", "therm"]) {
Some(t) => Json::Arr(
t.lines()
.map(|l| Json::str(l.trim()))
.filter(|j| *j != Json::str(""))
.collect(),
),
None => Json::Null,
}
}
pub struct RunRecord {
pub class: Class,
pub duration: Duration,
pub exit: Option<i32>,
pub stdout: String,
pub stderr: String,
pub samples: Samples,
pub json: Json,
}
pub fn execute(cfg: &RunConfig, crossover_build: Option<String>) -> RunRecord {
let t_wall = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let _ = std::fs::create_dir_all(&cfg.work_dir);
let out_path = cfg
.work_dir
.join(format!("stdout-{t_wall}-{}.txt", std::process::id()));
let err_path = cfg
.work_dir
.join(format!("stderr-{t_wall}-{}.txt", std::process::id()));
let mut settle: Option<(Duration, bool)> = None;
let thermal_before = thermal();
let free_start = (cfg.read_free)();
let mut result = RunRecord {
class: Class::LaunchFailed,
duration: Duration::ZERO,
exit: None,
stdout: String::new(),
stderr: String::new(),
samples: Samples::default(),
json: Json::Null,
};
match free_start {
None => result.class = Class::MemoryUnreadable,
Some(f) if f < cfg.limits.min_start_free => result.class = Class::RefusedToStart,
Some(_) => {
let files = std::fs::File::create(&out_path)
.and_then(|o| std::fs::File::create(&err_path).map(|e| (o, e)));
if let Ok((o, e)) = files {
let mut cmd = Command::new(&cfg.wine);
cmd.arg("--bottle")
.arg(&cfg.bottle)
.arg(&cfg.program)
.args(&cfg.args);
cmd.stdout(Stdio::from(o)).stderr(Stdio::from(e));
if let Some(b) = &cfg.backend {
cmd.env("CX_GRAPHICS_BACKEND", b);
}
let started = Instant::now();
if let Ok(mut child) = cmd.spawn() {
let bundle = cfg
.wine
.to_string_lossy()
.split("/Contents/")
.next()
.unwrap_or("")
.to_string();
let needles = vec![bundle, format!("Bottles/{}", cfg.bottle)];
let (mut cpu_sum, mut n) = (0f64, 0u32);
let mut stop: Option<Class> = None;
let mut last_len = 0u64;
let mut last_growth = Instant::now();
loop {
match child.try_wait() {
Ok(Some(st)) => {
result.exit = st.code();
break;
}
Ok(None) => {}
Err(_) => break,
}
let (rss, cpu) = sample_processes(&needles);
result.samples.peak_rss_kb = result.samples.peak_rss_kb.max(rss);
cpu_sum += cpu;
n += 1;
match (cfg.read_free)() {
Some(f) => {
let m = result.samples.min_free_percent.map_or(f, |x| x.min(f));
result.samples.min_free_percent = Some(m);
if f < cfg.limits.min_free {
stop = Some(Class::StoppedLowMemory);
}
}
None => stop = Some(Class::MemoryUnreadable),
}
let len = [&out_path, &err_path]
.iter()
.map(|p| std::fs::metadata(p).map_or(0, |m| m.len()))
.sum::<u64>();
if len != last_len {
last_len = len;
last_growth = Instant::now();
}
if stop.is_none() && started.elapsed() > cfg.timeout {
stop = Some(Class::TimedOut);
}
if stop.is_none()
&& cfg.stall_timeout.is_some_and(|d| last_growth.elapsed() > d)
{
stop = Some(Class::Stalled);
}
if stop.is_some() {
memory::terminate(&mut child, cfg.limits.grace);
stop_bottle(&cfg.wine, &cfg.bottle);
break;
}
std::thread::sleep(cfg.limits.poll);
}
result.duration = started.elapsed();
if stop.is_some() {
let t = Instant::now();
let need = cfg.limits.min_start_free;
let mut recovered = false;
loop {
if (cfg.read_free)().is_some_and(|f| f >= need) {
recovered = true;
break;
}
if t.elapsed() >= cfg.settle_bound {
break;
}
std::thread::sleep(cfg.limits.poll);
}
settle = Some((t.elapsed(), recovered));
}
result.samples.samples = n;
result.samples.mean_cpu_percent_of_core =
if n > 0 { cpu_sum / n as f64 } else { 0.0 };
result.stdout = std::fs::read_to_string(&out_path).unwrap_or_default();
result.stderr = std::fs::read_to_string(&err_path).unwrap_or_default();
result.class = stop.unwrap_or_else(|| {
classify(
result.exit,
&result.stdout,
&result.stderr,
cfg.expect.as_deref(),
)
});
}
}
}
}
let intervals: Vec<f64> = result
.stdout
.lines()
.filter_map(|l| l.strip_prefix("frame_ms "))
.filter_map(|v| v.trim().parse().ok())
.collect();
let frame_stats = frames::analyze(&intervals).ok().map(|s| s.to_json());
let combined = format!("{}\n{}", result.stdout, result.stderr);
let diags: Vec<Json> = diagnostics(&combined)
.into_iter()
.map(|(k, l)| Json::obj(vec![("kind", Json::str(k)), ("line", Json::str(l))]))
.collect();
let tail = |s: &str| -> Json {
let lines: Vec<&str> = s.lines().filter(|l| !l.starts_with("frame_ms ")).collect();
let keep = if lines.len() > 40 {
&lines[lines.len() - 40..]
} else {
&lines[..]
};
Json::Arr(keep.iter().map(|l| Json::str(*l)).collect())
};
result.json = Json::obj(vec![
("schema", Json::str("betterxen-hybrid-run/0")),
("unix_time", Json::Num(t_wall as f64)),
("crossover_build", Json::opt_str(crossover_build)),
(
"launcher_interface",
Json::str(
"CrossOver bin/wine --bottle (vendor --help only; not documented by CodeWeavers for macOS)",
),
),
("bottle", Json::str(cfg.bottle.clone())),
("backend_requested", Json::opt_str(cfg.backend.clone())),
("backend_variable_documented", Json::Bool(false)),
("backend_detected", Json::str(detected_backend(&combined))),
("program", Json::str(cfg.program.clone())),
(
"args",
Json::Arr(cfg.args.iter().map(|a| Json::str(a.clone())).collect()),
),
("classification", Json::str(result.class.name())),
(
"exit_code",
result.exit.map_or(Json::Null, |c| Json::Num(c as f64)),
),
(
"duration_ms",
Json::Num(result.duration.as_secs_f64() * 1000.0),
),
("timeout_s", Json::Num(cfg.timeout.as_secs_f64())),
(
"stall_timeout_s",
cfg.stall_timeout
.map_or(Json::Null, |d| Json::Num(d.as_secs_f64())),
),
(
"memory_settle_after_stop",
settle.map_or(Json::Null, |(d, ok)| {
Json::obj(vec![
("waited_ms", Json::Num(d.as_secs_f64() * 1000.0)),
("recovered_to_start_threshold", Json::Bool(ok)),
("bound_s", Json::Num(cfg.settle_bound.as_secs_f64())),
])
}),
),
(
"free_memory_percent_at_start",
free_start.map_or(Json::Null, |f| Json::Num(f as f64)),
),
(
"min_free_memory_percent_during_run",
result
.samples
.min_free_percent
.map_or(Json::Null, |f| Json::Num(f as f64)),
),
(
"peak_crossover_rss_kb_sampled",
Json::Num(result.samples.peak_rss_kb as f64),
),
(
"mean_crossover_cpu_percent_of_one_core_sampled",
Json::Num(result.samples.mean_cpu_percent_of_core),
),
("process_samples", Json::Num(result.samples.samples as f64)),
(
"gpu_utilization",
Json::str("not collected: no unprivileged documented source on this host"),
),
("thermal_before", thermal_before),
("thermal_after", thermal()),
("diagnostics", Json::Arr(diags)),
("frame_stats", frame_stats.unwrap_or(Json::Null)),
("stdout_tail", tail(&result.stdout)),
("stderr_tail", tail(&result.stderr)),
]);
let _ = std::fs::remove_file(&out_path);
let _ = std::fs::remove_file(&err_path);
result
}
/// Prefix directory of a bottle. CrossOver documents `BottleDir` in its preferences; otherwise
/// the default location under Application Support is used.
pub fn bottle_prefix(bottle: &str) -> PathBuf {
let base = crate::crossover::preference("BottleDir")
.map(PathBuf::from)
.unwrap_or_else(|| {
PathBuf::from(std::env::var("HOME").unwrap_or_default())
.join("Library/Application Support/CrossOver/Bottles")
});
base.join(bottle)
}
/// Stop every process of one bottle with `wineserver -k`, selecting the bottle through
/// `WINEPREFIX`. Setting `CX_BOTTLE` instead was tried first and observed NOT to select the
/// bottle: the Windows process kept running after the supervisor reported it stopped.
pub fn stop_bottle(wine: &Path, bottle: &str) {
if let Some(dir) = wine.parent() {
let _ = Command::new(dir.join("wineserver"))
.arg("-k")
.env("WINEPREFIX", bottle_prefix(bottle))
.status();
}
}
pub fn wine_path(app: &Path) -> PathBuf {
app.join("Contents/SharedSupport/CrossOver/bin/wine")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classifies_from_observed_facts() {
assert_eq!(classify(Some(0), "PASS", "", Some("PASS")), Class::Passed);
assert_eq!(
classify(Some(0), "ok", "", Some("PASS")),
Class::MissingExpectedMarker
);
assert_eq!(classify(Some(0), "", "", None), Class::Passed);
assert_eq!(classify(Some(1), "FAIL", "", None), Class::FailedExit(1));
assert_eq!(
classify(Some(2), "NO DEVICE hr=0x1", "", None),
Class::NoDevice
);
assert_eq!(classify(Some(2), "other", "", None), Class::FailedExit(2));
assert_eq!(
classify(
Some(1),
"",
"winewrapper.exe:error: cannot execute L\"a.exe\"",
None
),
Class::CannotExecute
);
}
#[test]
fn recognises_noise_and_backends() {
let d = diagnostics(
"LibClamAV Error: x\nERROR: Can't open file or directory\nwarn: DXVK: No state cache\nfine",
);
assert_eq!(d.len(), 3);
assert_eq!(d[0].0, "clamav-database-missing");
assert!(detected_backend("info: DXVK: cxaddon\nadapter=Apple M4").starts_with("dxvk"));
assert!(detected_backend("adapter=AMD Compatibility Mode").starts_with("d3dmetal"));
assert_eq!(detected_backend("nothing"), "unknown");
}
fn stub(dir: &Path, body: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
std::fs::create_dir_all(dir).unwrap();
let p = dir.join("wine");
std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
p
}
fn cfg(wine: PathBuf, timeout_ms: u64, tag: &str) -> RunConfig {
RunConfig {
wine,
bottle: "t".into(),
backend: None,
program: "x.exe".into(),
args: vec![],
timeout: Duration::from_millis(timeout_ms),
limits: memory::Limits {
min_start_free: 0,
min_free: 0,
poll: Duration::from_millis(30),
grace: Duration::from_millis(500),
},
expect: Some("PASS".into()),
work_dir: std::env::temp_dir().join(format!("bxrun-{tag}-{}", std::process::id())),
stall_timeout: None,
settle_bound: Duration::from_millis(200),
read_free: memory::free_percentage,
}
}
// These use a stub standing in for the launcher: they prove the supervision and record
// logic, not anything about CrossOver.
#[test]
fn stub_run_records_pass_frames_and_env() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stub1-{}", std::process::id()));
let w = stub(
&dir,
"echo \"backend=$CX_GRAPHICS_BACKEND\"; echo 'frame_ms 10'; echo 'frame_ms 20'; echo PASS",
);
let mut c = cfg(w, 10_000, "a");
c.backend = Some("dxmt".into());
let r = execute(&c, Some("test".into()));
assert_eq!(r.class, Class::Passed);
let j = r.json.render();
assert!(j.contains("\"frames\": 2"), "{j}");
assert!(j.contains("backend=dxmt"), "{j}");
assert!(j.contains("\"backend_requested\": \"dxmt\""));
assert!(
!j.contains("frame_ms 10"),
"frame lines belong in frame_stats, not the tail"
);
}
#[test]
fn stub_run_times_out_and_is_stopped() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stub2-{}", std::process::id()));
let w = stub(&dir, "exec /bin/sleep 30");
let t0 = Instant::now();
let r = execute(&cfg(w, 300, "b"), None);
assert_eq!(r.class, Class::TimedOut);
assert!(t0.elapsed() < Duration::from_secs(10));
}
#[test]
fn stub_failure_is_classified_with_exit_code() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stub3-{}", std::process::id()));
let w = stub(&dir, "echo FAIL; exit 3");
assert_eq!(
execute(&cfg(w, 10_000, "c"), None).class,
Class::FailedExit(3)
);
}
#[test]
fn silent_workload_is_stopped_as_stalled_before_the_timeout() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stall1-{}", std::process::id()));
let w = stub(&dir, "exec /bin/sleep 30");
let mut c = cfg(w, 20_000, "d");
c.stall_timeout = Some(Duration::from_millis(300));
let t0 = Instant::now();
let r = execute(&c, None);
assert_eq!(r.class, Class::Stalled);
assert!(
t0.elapsed() < Duration::from_secs(5),
"stall must fire long before the 20 s timeout"
);
assert!(r.json.render().contains("\"classification\": \"stalled\""));
}
#[test]
fn workload_that_keeps_printing_is_not_stalled() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stall2-{}", std::process::id()));
// Prints every 0.1 s for about 1.2 s: longer than the 0.5 s stall timeout in total.
let w = stub(
&dir,
"i=0; while [ $i -lt 12 ]; do echo tick; i=$((i+1)); sleep 0.1; done; echo PASS",
);
let mut c = cfg(w, 20_000, "e");
c.stall_timeout = Some(Duration::from_millis(500));
assert_eq!(execute(&c, None).class, Class::Passed);
}
static FREE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(90);
fn fake_free() -> Option<u8> {
Some(FREE.load(std::sync::atomic::Ordering::SeqCst))
}
// One test owns the shared `FREE` value, so it does not race with the others.
#[test]
fn after_a_stop_the_run_waits_for_memory_to_return() {
use std::sync::atomic::Ordering::SeqCst;
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-settle-{}", std::process::id()));
let w = stub(&dir, "exec /bin/sleep 30");
let mut c = cfg(w, 300, "f");
c.read_free = fake_free;
c.limits.min_start_free = 50;
c.limits.min_free = 0; // only the timeout stops the run
c.settle_bound = Duration::from_secs(5);
// Memory drops 100 ms in and returns 900 ms in; the timeout stop happens at about 300 ms.
FREE.store(90, SeqCst);
let h = std::thread::spawn(|| {
std::thread::sleep(Duration::from_millis(100));
FREE.store(10, SeqCst);
std::thread::sleep(Duration::from_millis(800));
FREE.store(90, SeqCst);
});
let r = execute(&c, None);
h.join().unwrap();
assert_eq!(r.class, Class::TimedOut);
let j = r.json.render();
assert!(j.contains("\"recovered_to_start_threshold\": true"), "{j}");
assert!(r.duration >= Duration::from_millis(300));
// Memory never returns: the wait gives up at the bound and says so.
FREE.store(90, SeqCst);
let h = std::thread::spawn(|| {
std::thread::sleep(Duration::from_millis(100));
FREE.store(10, SeqCst);
});
c.settle_bound = Duration::from_millis(400);
let t0 = Instant::now();
let r = execute(&c, None);
h.join().unwrap();
assert!(t0.elapsed() < Duration::from_secs(5));
assert!(
r.json
.render()
.contains("\"recovered_to_start_threshold\": false")
);
FREE.store(90, SeqCst);
}
#[test]
fn stopping_a_bottle_selects_it_through_wineprefix() {
use std::os::unix::fs::PermissionsExt;
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stop-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let log = dir.join("wineserver.log");
let ws = dir.join("wineserver");
std::fs::write(
&ws,
format!(
"#!/bin/sh\necho \"args=$* WINEPREFIX=$WINEPREFIX\" > '{}'\n",
log.display()
),
)
.unwrap();
std::fs::set_permissions(&ws, std::fs::Permissions::from_mode(0o755)).unwrap();
stop_bottle(&dir.join("wine"), "my-bottle");
let got = std::fs::read_to_string(&log).unwrap();
assert!(got.contains("args=-k"), "{got}");
assert!(
got.contains("Bottles/my-bottle") || got.contains("/my-bottle"),
"{got}"
);
}
}
-82
View File
@@ -1,82 +0,0 @@
//! 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();
}
}
+11 -1
View File
@@ -1,5 +1,7 @@
# Upstream provenance: victory-shader
**Not approved for merge.** This crate was developed against one commercial title's shaders; the per-file review and the open maintainer decision are in `docs/research/victory-shader-provenance.md`.
| | |
| --- | --- |
| Source | <https://github.com/skakwy/victory-mac>, directory `crates/victory-shader/` (Cargo.toml and `src/`) |
@@ -21,6 +23,14 @@ Changes to upstream files (19 lines, nothing functional) and files BetterXen add
- `src/lib.rs`: `#[rustfmt::skip]` on each `mod` so the vendored files stay byte-comparable with upstream.
- `src/emit/mod.rs`, `src/emit/f64.rs`, `src/emit/lower.rs`: `#[allow(...)]` attributes only, so the crate passes `clippy -D warnings` here. They silence imports and variables used only by Windows-only tests, an unused trait method, a test constant that looks like pi, and two dead duplicate match arms in `lower.rs` that exist upstream (an earlier arm already handles `v_cvt_f32_f64` and `v_permlanex16_b32`).
### Functional edits to upstream files (research/shader-wave-semantics, PR #392)
- `src/emit/lower.rs` (`active_f64_sum`, about 90 lines): the whole-wave f64 sum no longer emits a native `double` wave operation (`makeDouble`, `waveActiveOp.f64`, `splitDouble`); it builds the console's balanced tree over the lanes with the crate's own integer `add_f64`, reading partner runs through `waveReadLaneAt` and a ballot for lanes that are not present, and no longer sets the doubles feature flag. Why: D3DMetal reports no double-precision shader operations and a shader that uses a `double` ran without writing anything (docs/research/shader-wave-semantics.md).
- `src/emit/bitcode.rs`: two `#[allow(dead_code)]` for the double type, now never constructed.
- `src/emit/host.rs`: `Host::wave_lane_count_max()` and `Host::hardware()` (test host only; `hardware()` ignores `VICTORY_WARP`).
- `src/emit/mod.rs`: the static-sampler construction is factored into `static_samplers()` so `translate_native` reports immediate samplers.
- `src/emit/wave64_tests.rs`: `a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit` checks the device's wave width and, on a device narrower than 64 lanes, asserts the recompiler's refusal instead of running a 64-lane lowering.
## Not carried
The upstream repository's other crates (`victory-gpu`, `victory-loader`, `victory-hle`, ...), which are tied to one console title and its runtime, and `mac/`, `tools/`. The shader inputs the upstream project was built for are not included; BetterXen validates this crate only with its own synthetic fixtures (see `docs/research/` for the validation record).
The upstream repository's other crates (`victory-gpu`, `victory-loader`, `victory-hle`, ...), which are tied to one console title and its runtime, and `mac/`, `tools/`. No shader binaries or dumps of the title the upstream project targets are included, but comments and behaviour in this crate refer to that title's shaders; BetterXen validates this crate only with its own synthetic fixtures (see `docs/research/` for the validation record).
+1 -1
View File
@@ -38,8 +38,8 @@ pub fn translate_native(native: &NativeProgram) -> Result<HostShader, ShaderErro
stage: native.stage,
dxil: lowered.dxil,
user_data: lowered.user_data,
static_samplers: super::static_samplers(&lowered.samplers, lowered.cmp_samplers),
samplers: lowered.samplers,
static_samplers: Vec::new(),
root_cbvs: lowered.root_cbvs,
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
@@ -191,7 +191,7 @@ mod on_the_gpu {
let _one = crate::emit::valu_tests::ONE_AT_A_TIME
.lock()
.unwrap_or_else(|e| e.into_inner());
let host = Host::new(false).expect("no SM 6.6 D3D12 hardware device: not verified");
let host = Host::hardware().expect("no SM 6.6 D3D12 hardware device: not verified");
let mut ran = 0;
for f in fixtures() {
let got = run_on_gpu(&host, &f);
@@ -210,7 +210,7 @@ mod on_the_gpu {
let _one = crate::emit::valu_tests::ONE_AT_A_TIME
.lock()
.unwrap_or_else(|e| e.into_inner());
let host = Host::new(false).expect("no SM 6.6 D3D12 hardware device: not verified");
let host = Host::hardware().expect("no SM 6.6 D3D12 hardware device: not verified");
for f in fixtures() {
let got = run_on_gpu(&host, &f);
let mut wrong = f.expected.clone();
@@ -220,3 +220,272 @@ mod on_the_gpu {
}
}
}
// ---- f64 whole-wave sum (research/shader-wave-semantics) --------------------------------------
//
// The console's whole-wave f64 sum, as `valu_tests::whole_wave_f64_sum_and_cvt_f32_f64` builds it,
// but storing both words of the f64 result instead of converting to f32, so all 64 bits are
// compared. Upstream lowered it to a native `double` wave operation, which D3DMetal does not run
// (docs/research/shader-wave-semantics.md); it is now done with the integer fp64 add.
// Expected results come from a CPU model of the balanced tree over the lanes in their order
// (lanes 2k and 2k+1, then pairs, ...) with the CPU's own f64 additions, `+0.0` for lanes that
// are not launched; nothing is taken from the recompiler.
const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 {
0x7E00_0000 | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF)
}
const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] {
[
0x35 << 26 | (op as u32 & 0x3FF) << 16 | vdst as u32,
(src0 as u32 & 0x1FF) | (src1 as u32 & 0x1FF) << 9 | (src2 as u32 & 0x1FF) << 18,
]
}
const fn buffer_store_dword(vdata: u8, srsrc: u8, byte_off: u16) -> [u32; 2] {
[
0x38 << 26 | 0x1C << 18 | (byte_off as u32 & 0xFFF),
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8,
]
}
/// A one-group compute program over `threads` threads: each lane's f64 is root constants
/// `(s0, s1)`; the program sums the wave and stores the sum's low then high word to the UAV.
fn f64_wave_sum_program(threads: u32) -> NativeProgram {
let v_mov_dpp8 = |vdst: u8, vsrc: u8, sel: u32| [vop1(0x001, vdst, 0xE9), vsrc as u32 | (sel << 8)];
let v_mov_row_mirror = |vdst: u8, vsrc: u8| {
[
vop1(0x001, vdst, 0xFA),
vsrc as u32 | (0x140 << 8) | (1 << 19) | (0xF << 24) | (0xF << 28),
]
};
let mut w: Vec<u32> = Vec::new();
w.push(0xBE80_0000 | 5 << 16 | 0x03 << 8 | 0x80); // s_mov_b32 s5, 0 (table address high)
w.extend_from_slice(&[0x3D << 26 | 0x02 << 18 | 8 << 6 | (4 >> 1), 125 << 25]); // s_load_dwordx4 s[8:11], s[4:5], 0
w.push(vop1(0x001, 6, 0)); // v_mov_b32 v6, s0
w.push(vop1(0x001, 7, 1)); // v_mov_b32 v7, s1
w.push(0xBE80_0000 | 12 << 16 | 0x3D << 8 | 0xC1); // s_or_saveexec_b32 s12, -1
w.extend_from_slice(&vop3(0x101, 2, 0x80, 256 + 6, 12));
w.extend_from_slice(&vop3(0x101, 3, 0x80, 256 + 7, 12));
for sel in [14570689u32, 9658386, 2340] {
w.extend_from_slice(&v_mov_dpp8(4, 2, sel));
w.extend_from_slice(&v_mov_dpp8(5, 3, sel));
w.extend_from_slice(&vop3(0x164, 2, 256 + 4, 256 + 2, 0)); // v_add_f64
}
w.extend_from_slice(&v_mov_row_mirror(4, 2));
w.extend_from_slice(&v_mov_row_mirror(5, 3));
w.extend_from_slice(&vop3(0x164, 2, 256 + 4, 256 + 2, 0));
w.extend_from_slice(&vop3(0x378, 4, 256 + 2, 0x80, 0x80)); // v_permlanex16_b32
w.extend_from_slice(&vop3(0x378, 5, 256 + 3, 0x80, 0x80));
w.extend_from_slice(&vop3(0x164, 2, 256 + 4, 256 + 2, 0));
w.extend_from_slice(&vop3(0x360, 14, 256 + 2, 0x80, 0)); // v_readlane_b32 s14, v2, 0
w.extend_from_slice(&vop3(0x360, 15, 256 + 3, 0x80, 0)); // v_readlane_b32 s15, v3, 0
w.push(0xBE80_0000 | 16 << 16 | 0x03 << 8 | 14); // s_mov_b32 s16, s14
w.push(0xBE80_0000 | 17 << 16 | 0x03 << 8 | 15); // s_mov_b32 s17, s15
w.push(0xBE80_0000 | 126 << 16 | 0x03 << 8 | 12); // s_mov_b32 exec_lo, s12
w.push(vop1(0x001, 0, 16)); // v_mov_b32 v0, s16 (low word)
w.extend_from_slice(&buffer_store_dword(0, 8, 0));
w.push(vop1(0x001, 0, 17)); // v_mov_b32 v0, s17 (high word)
w.extend_from_slice(&buffer_store_dword(0, 8, 4));
w.push(0xBF81_0000); // s_endpgm
let code: Vec<u8> = w.iter().flat_map(|x| x.to_le_bytes()).collect();
let param = |root, sgprs, user_data, slot| RootParam {
root,
table_offset_dwords: 0,
sgprs,
base_register: 0,
user_data,
slot,
};
NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 12,
layout: vec![param(RootType::Constants, 4, 0, 0), param(RootType::Table, 1, 4, 1)],
used: vec![UsedResource {
kind: ResourceType::Uav,
root: RootType::Table,
table_offset_dwords: 0,
lower_bound: 0,
stride: 0,
dwords: 4,
user_data: 4,
slot: 1,
}],
io: StageIo::Cs(ComputeIo { rsrc2: 5 << 1, threads: [threads, 1, 1] }),
code,
}
}
/// The CPU model: the balanced tree over 32 lanes, the first `launched` holding `x`, the rest `+0.0`.
fn tree_sum(x: f64, launched: usize) -> f64 {
let mut v: Vec<f64> = (0..32).map(|l| if l < launched { x } else { 0.0 }).collect();
while v.len() > 1 {
v = v.chunks(2).map(|p| p[0] + p[1]).collect();
}
v[0]
}
#[test]
fn the_f64_wave_sum_is_lowered_without_native_doubles() {
let shader = translate_native(&f64_wave_sum_program(4)).expect("translate");
let c = crate::dxbc::Container::parse(&shader.dxil).expect("container");
let sfi0 = c.part(crate::dxbc::FourCC::SFI0).expect("SFI0 part").data;
let features = u64::from_le_bytes(sfi0[..8].try_into().unwrap());
assert_ne!(features & 0x4000, 0, "the sum uses wave operations (sanity check of this parse)");
assert_eq!(features & 0x1, 0, "no native double may be declared: D3DMetal does not run them");
}
#[test]
fn the_cpu_model_is_the_balanced_tree() {
// 4 lanes of 1.25: (1.25 + 1.25) twice, then 2.5 + 2.5, then the rest +0
assert_eq!(tree_sum(1.25, 4), 5.0);
assert_eq!(tree_sum(1.25, 32), 40.0);
// the order matters for values that round: this is not the sequential sum
let x = 0.1;
let sequential: f64 = (0..32).fold(0.0, |a, _| a + x);
assert_ne!(tree_sum(x, 32).to_bits(), sequential.to_bits());
}
#[cfg(windows)]
mod f64_on_the_gpu {
use super::*;
use crate::emit::host::{Dispatch, Host, Root, View};
/// Whole-wave f64 sums on the default D3D12 device, all 64 bits compared with the CPU model,
/// for full and partial waves and for values that round. Fails when there is no device.
#[test]
fn f64_wave_sums_match_the_cpu_tree_bit_for_bit() {
let _one = crate::emit::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let host = Host::hardware().expect("no SM 6.6 D3D12 hardware device: not verified");
let mut ran = 0;
for threads in [1u32, 4, 20, 32] {
let shader = translate_native(&f64_wave_sum_program(threads)).expect("translate");
let (root, pso) = host.compute_pipeline(&shader).expect("compute pipeline");
for x in [1.25f64, 0.1, -3.75e10, 1.0e-300, 123456.789, f64::from_bits(0x3FF0_0000_0000_0001)] {
let b = x.to_bits();
let inputs = [b as u32, (b >> 32) as u32, 0, 0];
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
ud[u.index as usize] = match (u.root, u.slot) {
(RootType::Constants, 0) => inputs[u.dword as usize],
(RootType::Table, 1) => 0,
other => panic!("unexpected user data {other:?}"),
};
}
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[View::RawUav(2)],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
let got = u64::from(out[0][0]) | u64::from(out[0][1]) << 32;
let want = tree_sum(x, threads as usize).to_bits();
assert_eq!(got, want, "{threads} threads of {x:e}: got {got:#018x}, want {want:#018x}");
ran += 1;
}
}
eprintln!("betterxen: {ran} f64 wave sums ran on the GPU and matched the CPU tree bit for bit");
}
}
// ---- immediate samplers through translate_native ---------------------------------------------
//
// A compute program that builds its sampler from constants in the code (an immediate sampler)
// needs a static sampler in the host's root signature. `translate_native` must report it, as the
// container path does; the buffer-only fixtures above cannot notice.
/// Samples texel (0.5, 0.5) of the 2D texture in table slot 0 with an immediate sampler and stores
/// the red channel to the raw UAV in table slot 1.
fn immediate_sampler_program() -> NativeProgram {
let s_mov_lit = |dst: u8, lit: u32| [0xBE80_03FF | (dst as u32) << 16, lit];
let smem = |op: u32, dst: u32, base: u32, off: u32| [0x3D << 26 | op << 18 | dst << 6 | base >> 1, 125 << 25 | off];
let mut w: Vec<u32> = Vec::new();
w.push(0xBE80_0300 | 2 << 16); // s_mov_b32 s2, s0 (table address)
w.push(0xBE80_0380 | 3 << 16); // s_mov_b32 s3, 0
w.extend(smem(0x03, 8, 2, 0)); // s_load_dwordx8 s[8:15]: the texture SRV
w.extend(smem(0x02, 20, 2, 32)); // s_load_dwordx4 s[20:23]: the UAV
w.push(0x7E00_02F0 | 2 << 17); // v_mov_b32 v2, 0.5
w.push(0x7E00_02F0 | 3 << 17); // v_mov_b32 v3, 0.5
for (i, word) in [0x0000_0092u32, 0x00C0_0000, 0x1850_0000, 0].into_iter().enumerate() {
w.extend(s_mov_lit(16 + i as u8, word)); // s[16:19]: the sampler, as constants
}
// image_sample_lz v4, v[2:3], s[8:15], s[16:19] dmask:0x1 dim:2D
w.extend([0x3C << 26 | 0x21 << 18 | 1 << 8 | 1 << 3, (16u32 >> 2) << 21 | (8u32 >> 2) << 16 | 4 << 8 | 2]);
w.extend([0x38 << 26 | 0x1C << 18, 0x80 << 24 | (20u32 >> 2) << 16 | 4 << 8]); // buffer_store_dword v4
w.push(0xBF81_0000); // s_endpgm
let used = |kind, table_offset_dwords, dwords| UsedResource {
kind,
root: RootType::Table,
table_offset_dwords,
lower_bound: 0,
stride: 0,
dwords,
user_data: 0,
slot: 0,
};
NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 8,
layout: vec![RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 0,
slot: 0,
}],
used: vec![used(ResourceType::Srv, 0, 8), used(ResourceType::Uav, 8, 4)],
io: StageIo::Cs(ComputeIo { rsrc2: 1 << 1, threads: [1, 1, 1] }),
code: w.iter().flat_map(|x| x.to_le_bytes()).collect(),
}
}
#[test]
fn translate_native_reports_immediate_samplers_as_static_samplers() {
let shader = translate_native(&immediate_sampler_program()).expect("translate");
assert_eq!(shader.samplers.len(), 1, "the program has one immediate sampler");
assert_eq!(shader.static_samplers.len(), 1, "the host builds s0 from this list");
}
#[cfg(windows)]
#[test]
fn immediate_sampler_samples_the_texture_on_the_gpu() {
use crate::emit::host::{Dispatch, Host, Root, View};
let _one = crate::emit::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let host = Host::hardware().expect("no SM 6.6 D3D12 hardware device: not verified");
let shader = translate_native(&immediate_sampler_program()).expect("translate");
let (root, pso) = host.compute_pipeline(&shader).expect("compute pipeline");
let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
let texels = [[0.25f32, 0.5, 0.75, 1.0]];
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[View::Texture(1, 1, &texels), View::RawUav(1)],
samplers: &[],
groups: [1, 1, 1],
},
)
.expect("dispatch");
assert_eq!(out[0][0], 0.25f32.to_bits(), "red of the only texel");
eprintln!("betterxen: the immediate-sampler program sampled the texture on the GPU");
}
#[test]
fn static_samplers_keep_the_comparison_filter_flag() {
let words = [0x0000_0092u32, 0x00C0_0000, 0x1850_0000, 0];
let list = super::static_samplers(&[words, words], 0b10);
assert_eq!(list.len(), 2);
assert_eq!(list[0].filter & 0x80, 0, "sampler 0 is not a comparison sampler");
assert_ne!(list[1].filter & 0x80, 0, "sampler 1 is");
}
@@ -30,6 +30,7 @@ enum TypeDef {
Void,
Int(u32),
Float,
#[allow(dead_code)] // BetterXen: no native double is emitted any more (see lower.rs active_f64_sum)
Double,
/// Pointee and address space.
Ptr(Ty, u32),
@@ -248,6 +249,7 @@ impl Module {
pub fn float(&mut self) -> Ty {
self.ty(TypeDef::Float)
}
#[allow(dead_code)] // BetterXen: see TypeDef::Double
pub fn double(&mut self) -> Ty {
self.ty(TypeDef::Double)
}
+29
View File
@@ -82,9 +82,38 @@ fn err(e: windows::core::Error) -> String {
}
impl Host {
/// The widest wave the device reports (`D3D12_OPTIONS1.WaveLaneCountMax`), or `None` when the
/// device does not report wave operations. BetterXen addition: tests that lower for a given
/// host wave width must not run on a narrower device (see wave64_tests.rs).
pub fn wave_lane_count_max(&self) -> Option<u32> {
let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
// SAFETY: `o` is a correctly sized, writable feature-data struct for this feature.
unsafe {
self.device
.CheckFeatureSupport(
D3D12_FEATURE_D3D12_OPTIONS1,
(&mut o as *mut D3D12_FEATURE_DATA_D3D12_OPTIONS1).cast(),
std::mem::size_of::<D3D12_FEATURE_DATA_D3D12_OPTIONS1>() as u32,
)
.ok()?;
}
(o.WaveOps.as_bool() && o.WaveLaneCountMax > 0).then_some(o.WaveLaneCountMax)
}
/// The default adapter, or WARP with `warp` (or `VICTORY_WARP=1`).
pub fn new(warp: bool) -> Result<Self, String> {
let warp = warp || std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1");
Self::create(warp)
}
/// The default hardware adapter, whatever `VICTORY_WARP` says; an error when the default
/// device is the software adapter. BetterXen addition: a test that reports GPU verification
/// must not be redirectable to WARP by the environment.
pub fn hardware() -> Result<Self, String> {
Self::create(false)
}
fn create(warp: bool) -> Result<Self, String> {
// SAFETY: plain D3D12/DXGI calls with valid out pointers.
unsafe {
// `VICTORY_D3D12_DEBUG`: the debug layer, whose messages a
+58 -31
View File
@@ -2052,6 +2052,19 @@ impl<'a> Lower<'a> {
/// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere),
/// returning the low (`!high`) or high (`high`) 32-bit word.
///
/// BetterXen change (research/shader-wave-semantics): upstream emitted a native `double`
/// wave operation here (`makeDouble`, `waveActiveOp.f64`, `splitDouble`). The host this is
/// run on (D3DMetal over Metal) has no fp64: it reports no double-precision shader operations
/// and, observed with shaders from Microsoft's DXC, a shader that uses a `double` runs without
/// writing anything. Every other fp64 instruction here is done with 64-bit integer
/// operations ([`super::f64::add_f64`], checked against the CPU's doubles); this does the
/// same. The console's sum is the balanced tree over the lanes in their order (lanes 2k and
/// 2k+1, then pairs, ...; [`super::wave::buddies`]), which is how it is built here: each
/// lane adds its partner run's partial sum, read from the first lane of that run that is
/// present, and `+0.0` where none is (a lane outside EXEC adds `+0` on the console, and a
/// lane the host never launched is the same). The addition is commutative, so every lane
/// holds the same sum.
fn active_f64_sum(
&mut self,
lo: Value,
@@ -2075,25 +2088,48 @@ impl<'a> Lower<'a> {
let z = self.s.m.i32(0);
let lo = self.s.m.select(c, on, lo, z);
let hi = self.s.m.select(c, on, hi, z);
self.s.flags |= flags::WAVE_OPS | flags::DOUBLES;
let f64t = self.s.m.double();
self.s.flags |= flags::WAVE_OPS;
let i32t = self.s.t.i32;
let split_ty = self
.s
.m
.named_struct("dx.types.splitdouble", vec![i32t, i32t]);
let arg = self
.s
.op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]);
let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0));
let sum = self
.s
.op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]);
let split = self
.s
.op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]);
let mut r_lo = self.s.m.extract(c, split, 0);
let mut r_hi = self.s.m.extract(c, split, 1);
let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
let here = self.s.m.bool(true);
let ballot = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[here]);
let (blo, bhi) = (self.s.m.extract(c, ballot, 0), self.s.m.extract(c, ballot, 1));
let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
let [zero, k31, k32] = [0, 31, 32].map(|k| self.s.m.i32(k));
// Steps within one host wave: the console wave's lanes, or 32 of them when two host
// waves of 32 exchange their halves for the last addition.
let steps = if self.exchange.is_some() || !self.x.native.wave64 { 5 } else { 6 };
let mut sum = self.join64(lo, hi);
for step in 0..steps {
let size = 1u32 << step;
let (bit, run) = (self.s.m.i32(size), self.s.m.i32(!(size - 1)));
let other = self.s.m.bin(c, Bin::Xor, lane, bit);
let base = self.s.m.bin(c, Bin::And, other, run);
// The lanes of the partner run that are here, from bit 0.
let upper = self.s.m.cmp(c, pred::IUGE, base, k32);
let word = self.s.m.select(c, upper, bhi, blo);
let at = self.s.m.bin(c, Bin::And, base, k31);
let shifted = self.s.m.bin(c, Bin::LShr, word, at);
let bits = if size >= 32 {
shifted
} else {
let mk = self.s.m.i32((1u32 << size) - 1);
self.s.m.bin(c, Bin::And, shifted, mk)
};
// FirstbitLo (dx.op 32): the run's first lane that is here
let first = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[bits]);
let any = self.s.m.cmp(c, pred::NE, bits, zero);
let first = self.s.m.select(c, any, first, zero);
let from = self.s.m.bin(c, Bin::Add, base, first);
let (slo, shi) = self.split64(sum);
let tlo = self.read_lane(slo, from);
let thi = self.read_lane(shi, from);
let tlo = self.s.m.select(c, any, tlo, zero);
let thi = self.s.m.select(c, any, thi, zero);
let theirs = self.join64(tlo, thi);
sum = super::f64::add_f64(&mut Gen { l: self }, sum, theirs);
}
let (mut r_lo, mut r_hi) = self.split64(sum);
if self.exchange.is_some() {
if !self.all_lanes(self.cur_ir) {
need(self.cur_ir);
@@ -2101,19 +2137,10 @@ impl<'a> Lower<'a> {
}
let (lo0, lo1) = self.exchange_halves(self.cur, r_lo);
let (hi0, hi1) = self.exchange_halves(self.cur, r_hi);
let c = self.cur;
let d0 = self
.s
.op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo0, hi0]);
let d1 = self
.s
.op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]);
let total = self.s.m.bin(c, Bin::Add, d0, d1);
let split = self
.s
.op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]);
r_lo = self.s.m.extract(c, split, 0);
r_hi = self.s.m.extract(c, split, 1);
let d0 = self.join64(lo0, hi0);
let d1 = self.join64(lo1, hi1);
let total = super::f64::add_f64(&mut Gen { l: self }, d0, d1);
(r_lo, r_hi) = self.split64(total);
}
Ok(if high { r_hi } else { r_lo })
}
+18 -12
View File
@@ -646,18 +646,7 @@ fn emit_program(
stage: native.stage,
dxil: l.dxil,
user_data: l.user_data,
static_samplers: l
.samplers
.iter()
.enumerate()
.map(|(n, &w)| {
let mut s = StaticSampler::from_words(w);
if l.cmp_samplers >> n & 1 != 0 {
s.filter |= 0x80;
}
s
})
.collect(),
static_samplers: static_samplers(&l.samplers, l.cmp_samplers),
samplers: l.samplers,
root_cbvs: l.root_cbvs,
root_srvs: l.root_srvs,
@@ -667,6 +656,23 @@ fn emit_program(
Ok((shader, wave_size))
}
/// The static sampler descriptions for the immediate samplers a shader uses (`s<n>` at position
/// n); bit n of `cmp` marks a sampler used for comparisons. BetterXen change: factored out so
/// `translate_native` builds the same list as the container path.
fn static_samplers(samplers: &[[u32; 4]], cmp: u64) -> Vec<StaticSampler> {
samplers
.iter()
.enumerate()
.map(|(n, &w)| {
let mut s = StaticSampler::from_words(w);
if cmp >> n & 1 != 0 {
s.filter |= 0x80;
}
s
})
.collect()
}
/// The rows of an `ISG1`/`OSG1` part.
fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> {
use crate::dxbc::u32_at;
@@ -235,6 +235,23 @@ fn a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() {
words[1] = 0xBF88_0000 | (words.len() as u32 - 2);
let native = native(&words);
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
// BetterXen correction (research/shader-wave-semantics): this program is lowered for a host
// of 64-lane waves. A device whose waves are narrower cannot run that lowering: its lanes 32
// and up do not exist, and the observed result was 0 instead of the tree. Such a device
// must be offered the lowering for its own width instead, which the recompiler refuses for
// this program ("a wave sum of 16-bit floats where not every lane runs"): the test then
// asserts that refusal, which is the correct behaviour, rather than reporting a failure
// or silently skipping.
if let Some(w) = Host::hardware().ok().and_then(|h| h.wave_lane_count_max()).filter(|&w| w < 64) {
let refused = lowered_on(&native, &p, &HashSet::new(), w);
assert!(
matches!(&refused, Err(ShaderError::Unsupported { what, .. }) if what.contains("16-bit floats where not every lane runs")),
"a {w}-lane device must be refused this program, got {:?}",
refused.as_ref().map(|_| "a shader")
);
eprintln!("device waves are {w} lanes; refused for that width as expected; not run on the device");
return;
}
let shader = lowered_on(&native, &p, &HashSet::new(), 64).expect("lower");
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut copy = shader.dxil.clone();
+2 -3
View File
@@ -68,10 +68,9 @@ checkpoints retain their original evidence scope.
- [Public sources](research/sources.md), [RDNA 2 notes](research/rdna2.md), and [Xbox GPU evidence](research/xbox-gpu.md) — Specifications, evidence scope, and unknown console behavior.
- [Shader inputs](research/shader-containers.md) and [risk register](risk-register.md) — Input provenance and unresolved engineering risks.
- [Upstream integration audit](research/upstream-integration-audit.md) — Source-level review of external macOS compatibility projects, licence and provenance decisions, and what was implemented in `crates/hybrid`.
- [victory-shader provenance review](research/victory-shader-provenance.md) — Per-file licence and origin record for the proposed import; not approved, maintainer decision pending.
- [victory-shader integration](research/victory-shader-integration.md) — The vendored GFX10-to-DXIL recompiler, how BetterXen's fixtures run through it on the GPU under CrossOver, and what is not verified.
- [CrossOver baseline](research/crossover-baseline-2026-11-25.md) — First executions of original workloads under CrossOver 26.3 on the M4, backend comparison and its limits.
- [Windows cross-toolchain](research/hybrid-toolchain.md) — Pinned llvm-mingw release, how original Windows workloads are built, and what was and was not executed.
- [Shader wave-semantics investigation](research/shader-wave-semantics.md) — Why two upstream wave tests failed under D3DMetal: device capabilities, independent probes, the fix and its limits.
- [Texture format inventory](research/texture-formats.md) — Formats and layouts by stage (decode, layout, native upload, sampling, guest), their public specifications, unknowns and ranked follow-ups.
- [PortWatch native macOS research](research/portwatch-native-macos.md) — Screening of public Xbox-on-Windows port projects for native macOS planning; discovery only.
- [Synthetic integration and upstream evidence](research/synthetic-integration.md) — Audited source snapshots and remaining commercial startup prerequisites.
+2 -3
View File
@@ -36,10 +36,9 @@ pending-run replay and exact head-SHA verification against a real repository.
## Production follow-ups
1. Keep `agent-pr-checks` advisory until this evidence is reviewed.
2. Coordinate adding `pull-requests: read` to the production audit job permissions
1. Coordinate adding `pull-requests: read` to the production audit job permissions
(same defect as the smoke audit failure).
3. Add a second QA-eligible verifier before treating `/verified` as smoke-complete.
2. Add a second QA-eligible verifier before treating `/verified` as smoke-complete.
## Local unit suite
-16
View File
@@ -90,22 +90,6 @@ cycles `agent:invalid` (and restores them when fixed), flags overlapping claims
writes a JSON summary to the run summary. `scripts/agent-queue.sh status --json` prints the same
machine-readable summary (counts and lists per area, priority and state).
## Pull request checks
`agent-pr-checks` fails a pull request when: it has no `Closes #N` for a claimed task; the task is held
by someone else; it changes files outside the task's patterns; it changes a file that another open
pull request also changes; the claim has lapsed without a push; or no eligible `/verified <current
head sha>` exists. The SHA must be the full 40 characters and the only argument: a commit with the
same short prefix is cheap to make. After an accepted `/verified` (an eligible verifier, the current
head) the verify job evaluates the same check again and writes it to its run summary; the earlier
check run is not re-run, since `pull_request_target` runs are recorded against the base branch and
cannot be found by the pull request head. Refused, stale, malformed or unauthorized `/verified`
comments get a reply and nothing else, and other pull request comments start no job.
The check is advisory for now: a failure is shown as a warning and in the run summary, and the job
still succeeds. It becomes blocking (fail on problems, then a required check) only after a live smoke
test on GitHub and the migration of existing issues into the queue.
## Forks and upstream sync
Work from a fork, but synchronise against the real upstream (`ranveersoni98/Xenora` in the
+1 -1
View File
@@ -12,9 +12,9 @@ The workspace is GPL-3.0-or-later. The following is the lead's preliminary compa
| bitflags | 2.13.2, `80ce9b545acb0bd42150695fc351889cac1d8eb4` | MIT from MIT OR Apache-2.0 | Runtime transitive dependency |
| AMD RDNA 2 ISA XML | 2026-02-20, schema 1.1.1 | MIT | Source for generated decoder constants |
| LLVM AMDGPU tools | 23.1.6 | Apache-2.0 WITH LLVM-exception | External fixture tool, not linked |
| llvm-mingw | 20261117 (sha256 `98d340bb…446aa`) | Apache-2.0 WITH LLVM-exception, plus component licences in its LICENSE.TXT (mingw-w64 runtime and headers have their own terms; not audited line by line) | External build tool for original Windows test programs, not linked, not distributed |
| victory-shader (vendored) | victory-mac `22b3f8e45a59`, directory snapshot | GPL-3.0 (same as BetterXen's GPL-3.0-or-later); Mesa-derived opcode table MIT | GFX10-to-DXIL shader recompiler; see its UPSTREAM.md |
| thiserror, zlib-rs, windows, windows-sys | 2.0.21, 0.6.8, 0.62.2, 0.61.2 | MIT OR Apache-2.0; Zlib; MIT OR Apache-2.0 | Dependencies of victory-shader; licences from each crate's metadata, not independently audited |
| DirectX Shader Compiler | v1.9.2609, `dxc_2026_09_29.zip` (sha256 `ad31b1fc…a7e7f1`) | University of Illinois/NCSA plus MIT components (per its licence files) | External tool for compiling HLSL probes under CrossOver; not vendored, not distributed |
| Xcode and Metal tools | Xcode 27.2 | Apple proprietary terms | External host tools, not distributed |
## Runtime redistribution review
+1 -9
View File
@@ -14,18 +14,10 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
| Direct3D 12 to Vulkan | VKD3D-Proton | **Evaluate**; blocked on a Vulkan 1.3 provider | Depends on MoltenVK feature coverage, unknown. |
| Vulkan on Metal | MoltenVK | **Evaluate** | Apache-2.0 (compatible with GPLv3). Subset of Vulkan; coverage vs consumers unknown. |
| Shader compiler / runtime | VIctory, VIctory-macOS | **Rejected for reuse** | Built for a specific commercial game's Xbox Series build whose provenance is not established as authorized. Ideas only. |
| GFX10 to DXIL recompiler | victory-mac `crates/victory-shader` (VIctory family) | **Not approved: maintainer decision pending** (the rejection above stands until then) | PR #394 proposes vendoring it. The [per-file review](victory-shader-provenance.md) finds GPL-3.0 licensing but development against one commercial title's shaders; read plainly, the engineering rules exclude it. |
| Project discovery | PortWatch VI | Reference only | Editorial tracker; not engineering evidence; nothing imported. |
| x86-64 decode and ARM64 translation, runtime, gfx1030 compiler, Metal backend | BetterXen native implementation | **Preserved, paused** | Reuse only where hybrid needs it and it shows a demonstrated advantage; not forced into the architecture. |
| Test and diagnostics methodology | BetterXen existing audits, benchmark harness, claims registry | **Reuse** | Existing evidence classes, claims audit and benchmark gating apply to hybrid work (Phase 1 onward). |
| Configuration, diagnostics, benchmarking around CrossOver | BetterXen | **Build** (Phase 2, provisional) | Only after Phase 1 shows what CrossOver does not already provide (#351). |
| Host receipt, frame statistics, cross-toolchain probe | `crates/hybrid` | **Build** (original Rust, public system interfaces) | ossover and Whisky are Swift references; no code adapted. See [audit](upstream-integration-audit.md). |
| Metal HUD log parsing | ossover `MetalHUDLog` | **Reference only** | Log format is documented only by third-party observation; implement after a real trace is captured (#145). |
| Bottle and bundle internals (`cxbottle.conf`, SharedSupport layout) | ossover and others | **Do not depend** | Undocumented, derived from reverse engineering; #350 decides. |
| Game-specific XCL layers | MacBox, ScarlettMac | **Rejected** | GPL-2.0-only and game-specific. |
| Memory-pressure guard for workloads | skakwy/victory-mac `mac/run-victory.sh` | **Adapted** into `crates/hybrid/src/memory.rs` | Contributor-authored, GPL-3.0, permission granted; reimplemented in Rust. |
| Windows cross-linker wrapper | skakwy/victory-mac `tools/macos/gnullvm-cc.sh` | **Not used** | Failed with Homebrew `llvm@17`; llvm-mingw covers the need. |
| Windows cross toolchain | llvm-mingw 20261117 | **External dependency**, not vendored | Apache-2.0 with LLVM exceptions; checksum recorded in [hybrid-toolchain.md](hybrid-toolchain.md). |
| Zero-copy Metal swizzle, D3DMetal state fixes | skakwy/victory-mac `mac/unixlib`, `PROGRESS.md` | **Rejected** | Act on D3DMetal internals; Apple licence forbids reverse engineering. |
Open items: license text for every selected component must be read from the exact release used; DXMT, DXVK and Wine contributor and file-level notices are not reviewed.
@@ -1,59 +0,0 @@
# CrossOver baseline on the M4 reference machine (2026-11-25)
Evidence class: observed runs on one machine by one person (class B in the sense of [claims.toml](../claims.toml)); **not independently reproduced**, so #355 and #353 stay open. Every result is for original BetterXen workloads, never for a game. Nothing here shows Xbox compatibility.
## Environment
| Item | Value (source) |
| --- | --- |
| Machine | Apple M4, 10 cores (4 performance, 6 efficiency), 24 GiB, macOS 27.0 build 26A428 (`betterxen-hybrid host`) |
| CrossOver | `/Applications/CrossOver.app`, 26.3, build 26.3.0.39832, bundle id `com.codeweavers.CrossOver`, main executable universal (x86_64, arm64) (`betterxen-hybrid crossover`). Licence or trial state not inspected; runs worked |
| Wine host binaries | `wineloader` and `wineserver` are **x86_64 only** (`lipo -archs`), so CrossOver's Wine runs under Rosetta 2 on this Mac. `arch -x86_64 /usr/bin/true` executes |
| Bottle | `betterxen-test`, template `win11_64`, created in 18.7 s with `cxbottle --bottle betterxen-test --create --template win11_64` |
| Launch interface | `bin/wine --bottle B program` and `bin/wineserver -k`. `cxbottle --help` and `cxstart --help` exist in the bundle. **None of these command-line interfaces is documented by CodeWeavers for macOS**: the [Mac user guide](https://support.codeweavers.com/en_US/crossover-mac-user-guide) and [advanced configuration page](https://support.codeweavers.com/advanced-crossover-mac-configuration) cover the GUI and hook variables only. They are used here as observed vendor behaviour of this build |
| Backend selection | `CX_GRAPHICS_BACKEND=<name>` in the environment. Undocumented (see #350). An unknown value (`bogus`) was **accepted silently** and gave the same result as the default |
| Toolchain | llvm-mingw 20261117, Rust 1.100.0; see [hybrid-toolchain.md](hybrid-toolchain.md) |
| Host noise | CrossOver's antivirus helper prints `LibClamAV Error` and `Can't open file or directory` because Homebrew's ClamAV has no database in `/opt/homebrew/var/lib/clamav`. Harmless to results; the run record reports it as a diagnostic |
## Workloads executed
Run with `betterxen-hybrid run --bottle betterxen-test --expect PASS -- <exe>`, default backend.
| Workload | x86-64 result | ARM64 result |
| --- | --- | --- |
| C self-check (CRC-32, four threads) | passed, exit 0, 1.4 s | `cannot_execute` |
| Rust self-check (threads, TLS) | passed, exit 0, 0.6 s | `cannot_execute` |
| D3D11 clear and readback | passed, exit 0, 1.1 s | `cannot_execute` |
| D3D11 indexed triangle, shaders, frame loop | passed, exit 0, 0.8 s | `cannot_execute` |
CrossOver 26.3 here **rejects Windows ARM64 executables** with `winewrapper.exe:error: cannot execute`. The ARM64 builds exist and have the correct PE type, but cannot be run in this environment. Process memory sampled while running was about 325 MB (CrossOver's persistent processes, identical across workloads, so it says nothing about the workloads themselves); minimum system free memory stayed at 64 to 68 %.
Negative controls (#365): `d3d11-clear --negative-control` and `d3d11-frameloop --negative-control` expect a deliberately wrong colour and exit 1; the normal runs exit 0.
### Defects found in BetterXen's own workloads, not in CrossOver
1. **Clear test required exact bytes.** The first run read green as 127 where the program expected 128 (0.5 × 255 = 127.5, an exact tie). Re-derived from the primary source ([Direct3D data conversion rules](https://learn.microsoft.com/en-us/windows/win32/direct3d10/d3d10-graphics-programming-guide-resources-data-conversion)): the ideal conversion adds 0.5 and drops the fraction (128), but implementations are permitted a tolerance of 0.6 unit-last-place on the integer side (`D3D12_FLOAT32_TO_INTEGER_TOLERANCE_IN_ULP (0.6f)` in the mingw-w64 header; the D3D11 constant is described by the same page). 127 is 0.5 from 127.5 and is within tolerance. The workload now checks that tolerance and prints how many pixels differ from the ideal. This was a correction to match the specification, not a loosening to get a pass: the negative control still fails.
2. **Triangle was culled.** The first frame-loop run left the centre black. The index order was counter-clockwise, which Direct3D 11 culls by default. Fixed to clockwise; the centre then read (51, 102, 204, 255) exactly.
## Graphics backend comparison
`betterxen-hybrid bench --backends default,d3dmetal,dxmt,dxvk,wined3d --repeat 5`, 2000 frames per run, workload `d3d11-frameloop`: a 640x360 offscreen RGBA8 target, one indexed triangle with a vertex and a pixel shader, an event query waited on every frame. **No window and no presentation.** All 25 runs passed. Medians across five runs:
| Backend (detected from workload output) | Adapter reported | Median frame | p95 | p99 | Frame rate | Startup + run, median |
| --- | --- | --- | --- | --- | --- | --- |
| default | AMD Compatibility Mode | 0.281 ms | 0.448 ms | 0.929 ms | 3153 | 1.42 s |
| d3dmetal | AMD Compatibility Mode | 0.282 ms | 0.558 ms | 1.805 ms | 2898 | 1.44 s |
| dxmt | Apple M4 | 0.158 ms | 0.239 ms | 0.382 ms | 5896 | 1.13 s |
| dxvk (via MoltenVK, "cxaddon-1.10.3") | Apple M4 | 0.150 ms | 0.263 ms | 0.478 ms | 5835 | 1.13 s |
| wined3d | Apple M4 | 0.150 ms | 0.256 ms | 0.419 ms | 5788 | 1.13 s |
Observations, with their limits:
- **The default behaved like D3DMetal** (same adapter identity, same timings) for a bottle made from `win11_64` and an unknown executable. CodeWeavers' Advanced Settings page, as recorded in [primary-source-verification](primary-source-verification-2026-11-25.md), says Auto falls back to wined3d without a per-game database entry. The observation disagrees with that reading; why was not investigated.
- D3DMetal's median per-frame submit-and-wait time was about 1.8 times that of the other three, with a larger tail. This is the cost of a trivial draw plus synchronisation, **not rendering throughput**, and shows nothing about real scenes. It identifies a candidate for investigation, not a bottleneck.
- Sustained run, 200,000 frames: D3DMetal 64.1 s, median 0.283 ms, p99 0.987 ms, p99.9 2.07 ms, maximum 20.3 ms; DXMT 29.6 s, median 0.135 ms, p99 0.339 ms, p99.9 0.48 ms, maximum 7.4 ms. No failure, no hang, and free memory did not trend downward (minimum 64 % and 66 %).
- Not measured: GPU utilization (no unprivileged documented source on this host), memory use of the workload itself, thermal behaviour under load (pmset reported no thermal, performance or CPU-power warning before and after; the workload loads the GPU too lightly for that to mean anything), presentation and frame pacing, texture sampling, depth testing, and Direct3D 12.
## What this does and does not establish
Established on this machine and build: CrossOver 26.3 runs original x86-64 console, threaded, Direct3D 11 clear and triangle programs under four graphics backends with correct pixels; it does not run ARM64 Windows programs; BetterXen can detect, supervise, classify and record such runs. Not established: anything about Direct3D 12, real-scene performance, other macOS or CrossOver versions, other machines, or any game. A second contributor still has to reproduce this.
-36
View File
@@ -1,36 +0,0 @@
# Windows cross-toolchain for original workloads (issue #364)
Evidence class B for the build results (commands run on the reference machine, 2026-11-25), class D for licences. The x86-64 programs were later run under CrossOver 26.3; results are in [crossover-baseline-2026-11-25.md](crossover-baseline-2026-11-25.md).
## Pinned toolchain
| Item | Value |
| --- | --- |
| Toolchain | [llvm-mingw](https://github.com/mstorsjo/llvm-mingw) release `20261117`, asset `llvm-mingw-20261117-ucrt-macos-universal.tar.xz` |
| SHA-256 | `98d340bbb8d46b09ad6886ffba88bd9d5415e131c316de48e6bd7647377446aa`, equal to the digest GitHub shows for the asset; computed locally with `shasum -a 256` after download |
| Host binaries | Mach-O universal (x86_64, arm64); `codesign -dv` shows the clang driver is signed. Runs natively on Apple Silicon |
| Targets used | `x86_64-w64-mingw32` and `aarch64-w64-mingw32` (clang), Rust `x86_64-pc-windows-gnullvm` and `aarch64-pc-windows-gnullvm` |
| Licence | `LICENSE.TXT` in the release opens with "The LLVM Project is under the Apache License v2.0 with LLVM Exceptions" and then lists further component licences (the mingw-w64 runtime has its own terms). The full file was **not** audited line by line. It is an external build tool: nothing from it is shipped or copied into this repository |
| Install | Download, check the digest, unpack outside the repository (for example `~/toolchains/`), pass the directory to the build script. It is not vendored |
Rust 1.100.0 with `rustup target add x86_64-pc-windows-gnullvm aarch64-pc-windows-gnullvm`.
## Build and result
`scripts/hybrid/build-windows-workloads.sh <llvm-mingw-dir>` builds three original programs for both architectures with `-Wall -Wextra -Werror` and then checks each output with `file`; it exits non-zero if a PE has the wrong machine type.
| Program | Source | x86-64 | ARM64 | Executed under CrossOver 26.3 |
| --- | --- | --- | --- | --- |
| C self-check: CRC-32 check value, four threads, interlocked counter | `workloads/win-selfcheck-c` | built; passed | built; rejected (`cannot execute`) | x86-64 yes, ARM64 no |
| Rust self-check: thread-local storage across four threads | `workloads/win-selfcheck-rust` | built; passed | built; rejected | x86-64 yes, ARM64 no |
| Direct3D 11 clear and readback of a 64x64 RGBA8 target (first step of #365) | `workloads/d3d11-clear` | built; passed within the specified tolerance | built; rejected | x86-64 yes, ARM64 no |
A fourth program, `workloads/d3d11-frameloop` (indexed triangle, shaders, sustained frame loop; needs `-ldxguid -ld3dcompiler`), builds the same way. The D3D11 programs exit 2 ("no device") rather than passing when no hardware device exists, so a missing GPU path cannot be mistaken for success.
## Alternative evaluated: skakwy's `gnullvm-cc.sh`
The contributor's `tools/macos/gnullvm-cc.sh` (victory-mac commit `22b3f8e45a59`) links `x86_64-pc-windows-gnullvm` with Homebrew clang and rustup's lld. On the reference machine, with Homebrew `llvm@17` as `LLVM_PREFIX`, it failed at link time: `clang-17` aborted with `dyld: Symbol not found: _LLVMInitializeLanaiAsmParser`, because the script sets `DYLD_LIBRARY_PATH` to the Rust toolchain's `libLLVM`. It probably expects a newer Homebrew LLVM; which version was not asked. llvm-mingw covers the same need without that dependency, so the script was **not integrated**. His note that the plain `x86_64-pc-windows-gnu` target aborts on thread start is unverified here, since no program was run.
## Reproducibility
Rebuilding twice on one machine and path gives byte-identical SHA-256 for all eight outputs, after adding `-Wl,--no-insert-timestamp` (the C programs differed before because of the PE timestamp). The Rust outputs were identical without it. A build in a different directory was not tested and may embed paths; the second-contributor reproduction that #364 requires has not happened. The `file` check shows the llvm-mingw host binaries are universal (x86_64 and arm64), so the issue's "arm64 only" criterion is not met by this release asset.
+64
View File
@@ -0,0 +1,64 @@
# Shader wave-operation failures under D3DMetal: investigation
Part of the shader integration PR (#394). It began as the separate investigation PR #392, whose content is carried here. Evidence class B (runs on one machine: Apple M4, 24 GiB, macOS 27.0, CrossOver 26.3.0.39832, default backend), not independently reproduced. The two failures are the ones recorded in `victory-shader-integration.md`. This note separates what is **established** from what is **a hypothesis**.
## Device capabilities (measured with BetterXen's own host, `workloads/d3d12-wave-probe/d3d12_run.c caps`)
| Field | Value |
| --- | --- |
| Adapter reported | "AMD Compatibility Mode", vendor 0x1002, 18,186 MB (D3DMetal's reported identity; the hardware is the M4) |
| Device created at feature level | 12_1 |
| Highest shader model | 6.6 |
| `WaveOps` | supported |
| `WaveLaneCountMin` / `Max` | 32 / 32 (waves are exactly 32 lanes; `TotalLaneCount` 1024) |
| `DoublePrecisionFloatShaderOps` | **0** (no double-precision shader operations) |
| `Int64ShaderOps` | supported |
| Min-precision support | 0x2 (16-bit) |
## Failure 2: `a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit` (established)
**Cause: a wrong test precondition (a subgroup-size assumption), not a translation error.**
1. The test lowers the program with `lowered_on(.., 64)`, "for a host of 64-lane waves (AMD)" per its own comment, then dispatches it on the default device without asking that device's wave width.
2. The device's waves are exactly 32 lanes (table above). A program written for 64-lane waves reads lanes 32 to 63, which do not exist; the observed result was `0x0` against the expected tree `0x5914`.
3. It is the only test in that file that lowers for 64 lanes (line 238); the sibling `a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit` lowers for 32 (line 160) and passes on the same device.
4. Lowering this same program for a 32-lane host does not produce a wrong shader: the recompiler refuses it with `Unsupported: a wave sum of 16-bit floats where not every lane runs`. So the recompiler already behaves correctly; it states a limit instead of emitting something wrong.
5. The expected value `0x5914` is derived on the host by integer 16-bit float arithmetic in the test itself, independent of the recompiler.
**Correction made (test, not recompiler):** `Host::wave_lane_count_max()` (new, from `D3D12_OPTIONS1`), and the test now checks the device first. On a device narrower than 64 lanes it asserts the refusal above and returns, printing why; on a 64-lane device it runs the original hardware comparison unchanged. After the change the test passes on this device, and what it verifies there is "the recompiler refuses a 64-lane-only program for a 32-lane host", not "the sum is correct on the GPU". The correct-sum claim stays **unverified on 32-lane hardware** and has not been run on a 64-lane device.
## Failure 1: `whole_wave_f64_sum_and_cvt_f32_f64` (established: unsupported double-precision operations in D3DMetal; fixed in the recompiler)
Observed: a Wave32 program with 4 launched threads, each contributing 1.25, should store 5.0; it stored `0x00000000`. It is a Wave32 program on a 32-lane device, so wave width was never the cause.
**Independent evidence** (Microsoft's DXC compiled original HLSL, BetterXen's own host dispatched it; expected values derived by hand before running; DXC v1.9.2609 digest-verified and run under CrossOver 26.3):
| Probe (`workloads/d3d12-wave-probe/hlsl/`) | Expected | Observed |
| --- | --- | --- |
| `lanes4`: wave size and lane index, 4 threads | `0x2000`..`0x2003` (wave of 32) | exactly that |
| `sum_f32_4`: `WaveActiveSum(1.25f)`, 4 threads | `0x40a00000` in every lane | exactly that |
| `add_f32_4`: control, run-time load, float add, store | `0x40000000`, `0` per thread | exactly that |
| `add_f64_4`: a `double` add of run-time operands (DXIL contains `fadd fast double`) | low `0x00000000`, high `0x40000000` | **every dword still `0xDEADBEEF`: the shader wrote nothing** |
| `sum_f64_4`: `WaveActiveSum` over a run-time `double` (DXIL `waveActiveOp.f64`) | low `0x00000000`, high `0x40140000` | **every dword still `0xDEADBEEF`: the shader wrote nothing** |
An earlier version of `add_f64_4` used constant operands: the compiler folded the addition to `splitDouble(2.0)` with no `fadd` (reviewer finding by atesahmet0, confirmed with `dxc -dumpbin`), so it did not show a double *addition* failing. The probes above take their operands from the buffer at run time and were rerun; the result is the same.
So wave operations, wave width and partial waves are fine on this device. Any shader that uses a `double` runs without effect: pipeline creation succeeds, the dispatch completes, and nothing is stored. That matches the capability record (`DoublePrecisionFloatShaderOps = 0`; Metal has no fp64). Upstream's test harness zero-fills its output buffer, which is why it saw `0` instead of the sentinel. **Conclusion:** the failure comes from unsupported double-precision operations in the backend, combined with the recompiler emitting a native `double` in one place (`active_f64_sum`) while using integer emulation everywhere else. It is not a mistranslation of the wave operation and not a wave-semantics problem.
**Fix (recompiler, `active_f64_sum`):** the existing integer fp64 add (`add_f64`, checked upstream against the CPU's doubles) is reused to build the console's sum, which is the balanced tree over the lanes in their order. Each lane adds its partner run's partial sum, read through `waveReadLaneAt` from the first lane of that run that is present (found with a ballot, as `half_sum_present` already does for 16-bit sums), `+0.0` where none is, which is what a lane outside EXEC adds on the console. No `double` type is emitted and the doubles feature flag is no longer set. The same code covers the console wave64 on two host waves of 32 (an integer add for the last step).
**Validation** (M4, CrossOver 26.3, default backend; one machine, not independently reproduced):
- Whole suite under CrossOver: **232 passed, 0 failed, 3 ignored** (229 before the review's sampler tests) (was 224 passed, 2 failed). macOS: 179 + new tests pass (`cargo test -p victory-shader`).
- New test `f64_wave_sums_match_the_cpu_tree_bit_for_bit`: 24 cases (1, 4, 20 and 32 launched threads; six values including ones that round: 0.1, 123456.789, a value one ulp above 1.0, -3.75e10, 1e-300), comparing all 64 bits with a CPU model of the balanced tree using the CPU's own f64 additions and `+0.0` for lanes that are not launched. All 24 match. The model is independent of the recompiler.
- Negative controls: against the **original** lowering this GPU test fails (`got 0x0000000000000000, want 0x3ff4000000000000`) and the new `the_f64_wave_sum_is_lowered_without_native_doubles` test (the container's feature word must declare wave operations but not doubles) fails too; both pass with the fix.
**Limits:** (1) the tree order is what the recompiler's recognizer claims the console program computes (`wave::buddies`); this was not independently simulated from the DPP instructions, so bit-for-bit fidelity to the console for rounding values is only as good as that recognition. (2) The cost of the integer version was not measured and no performance claim is made. (3) Other fp64 wave operations (products, min/max) were not examined; only this one site emitted native doubles. (4) On a device with real fp64 the old native operation would work and is no longer used. (5) DXC is an external tool (University of Illinois/NCSA licence plus MIT components per its licence files), used only to compile probes; nothing from it is in the repository.
## Reproduce
```sh
scripts/hybrid/run-shader-gpu-tests.sh <llvm-mingw-dir> betterxen-test all # the runner script is in PR #395; or run the cross-built test executable with wine directly # expect: 0 failures with the fix in this branch (the vendored original has 2)
# probes: compile hlsl/*.hlsl with DXC under CrossOver, then d3d12_run.exe run <file>.dxil 1 <dwords>
# capabilities (needs the d3d12_run.exe built from workloads/d3d12-wave-probe/d3d12_run.c with llvm-mingw):
# x86_64-w64-mingw32-clang -O2 -o d3d12_run.exe d3d12_run.c -ld3d12 -ldxgi -ldxguid
# CrossOver bin/wine --bottle <bottle> ./d3d12_run.exe caps
```
-114
View File
@@ -1,114 +0,0 @@
# Upstream integration audit (2026-11-25)
Companion to the [upstream registry](upstream-registry.md) and [component reuse matrix](component-reuse-matrix.md); those two hold the canonical rows, this file holds the audit evidence behind the new ones. Evidence class D unless stated: public repository metadata, file trees and files read through the GitHub API, plus one Apple license read as text. **No upstream script, installer, binary or build hook was executed and no upstream code was copied.** Not legal advice. CrossOver is **not installed** on the reference machine (Apple M4, 24 GB, macOS 27.0 build 26A428), so nothing below was validated against CrossOver.
## Contributor-reported progress (unverified)
skakwy (a BetterXen contributor) maintains [skakwy/victory-mac](https://github.com/skakwy/victory-mac) (GPL-3.0 per GitHub; head `main` pushed 2026-11-25). Reports received: about 1 frame per second with a commercial game, and later "two rendered frames". Both are contributor statements. No hardware, macOS or CrossOver version, workload, instrumentation or raw data has been shared, and the repository's own README gives only build and run commands. Treat both as **unverified**; neither is a compatibility claim. The repository describes itself as a fork of VIctory, a project whose purpose is a leaked Xbox Series build of a commercial game (see the registry), so it is a discovery reference at documentation level only. Information worth requesting from skakwy is listed under "Contributor request" below.
## Projects reviewed
Pins are the default-branch head or the commit read on 2026-11-25. "Equivalent" is what BetterXen has or lacks. Status values: **implemented** (code and tests on this branch), **reference** (read, nothing taken), **rejected**.
| Project | URL | Pin | Licence (file read where stated) | Verified facts | BetterXen equivalent | Provenance | Classification | Status |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| victory-mac | github.com/skakwy/victory-mac | not pinned (not reviewed past README and tree) | GPL-3.0 (GitHub) | Rust workspace with `mac/` build and run scripts for CrossOver, D3DMetal, Rosetta 2; README says "VIctory fork with a Mac build" | none needed | Built on a game-specific upstream whose inputs are unauthorized; file-level review not done | Technical reference only | reference |
| VIctory-macOS | github.com/pragyaangaur/VIctory-macOS | see registry | GPL-3.0 (GitHub) | Described as an attempt to run one commercial game | none needed | Same concern | Rejected for reuse | rejected |
| MacBox | github.com/aykhanium/MacBox | not pinned | **GPL-2.0** (GitHub) | README is candid: "not playable", "retail gameplay is unverified", test suite "known failures"; layers on XCL, an Xbox Series runtime for unpacked console executables | none | Game-specific; also **GPL-2.0-only is not combinable with GPL-3.0-or-later** (see decisions) | Rejected for reuse | rejected |
| ScarlettMac | github.com/paveledits/ScarlettMac | not pinned | GPL-2.0 (GitHub); also `LICENSE-silicon-rans`, `SOURCE-NOTICES.md` | Patch set and shell scripts for XCL on CrossOver; README states game screenshots and a game-specific status | none | Game-specific; mixed licences | Rejected for reuse | rejected |
| PortWatch VI | portwatch-vi.xyz | see registry | NOASSERTION | Editorial tracker | none | Not engineering evidence | Reference only | reference |
| ossover | github.com/hemkum/ossover | `5c11bd7be8da` | GPL-3.0-or-later (README, `ATTRIBUTION.md` lists per-file adaptations from Whisky and highball) | Swift package: `SysInfo` (macOS, chip, memory, Rosetta probe), `Bench/MetalHUDLog` (parser for `metal-HUD:` log lines), `Bench/Harness`, `Store/EngineProbe`, `Renderer/CrossOverBottleConfig`, `doctor` command. README: alpha, one game verified on one machine, "no benchmark numbers have been published". Its design was derived from reverse engineering a CrossOver 26.3.0 bundle | Host receipt, frame statistics (this branch) | Clean, attribution explicit. Reverse-engineered CrossOver internals are **not** a supported interface | Technical reference; ideas re-implemented independently | reference |
| Whisky | github.com/Whisky-App/Whisky | `fd5480a76b3e` | GPL-3.0-or-later (file header read: "version 3 ... or (at your option) any later version") | Archived 2025-05-11. `WhiskyKit`: bottle settings, Wine process control, PE parser, Rosetta 2 check | Rust host receipt covers the Rosetta check | Clear | Technical reference only (Swift; no reuse path) | reference |
| rum | github.com/lunguini/rum | `657461b194e1` | GPL-3.0 (GitHub) | Active Whisky fork: DXMT/DXVK setup, run history, graphics settings views | none needed | Fork of Whisky | Technical reference only | reference |
| Sikarugir | github.com/Sikarugir-App/Sikarugir | `5446b7d18072` | none reported | 23 files; hosts copies of Apple's Game Porting Toolkit documents (`D3DMetal/<ver>/License.pdf`) | none | Redistributes Apple documents; no licence of its own | Reference only; no reuse | reference |
| Sikarugir-foss-sources | github.com/Sikarugir-App/Sikarugir-foss-sources | not reviewed | LGPL-2.1 (GitHub) | Fork of Wineskin sources | none | Unreviewed | Reference only | reference |
| Mythic | github.com/MythicApp/Mythic | see registry | GPL-3.0 | Launcher using a custom GPTK implementation | none | Not reviewed | Reference only | reference |
| DXMT | github.com/3Shain/dxmt | see registry | LGPL-2.1-or-later (LICENSE read by prior pass); GitHub shows NOASSERTION | D3D11/10 on Metal under Wine | Selected by CrossOver as a backend | Clear | External dependency (via CrossOver) | reference |
| DXVK, VKD3D-Proton, MoltenVK | see registry | see registry | zlib, LGPL-2.1, Apache-2.0 | No change from registry | none | Clear | External (via CrossOver) | reference |
| Gcenx macOS Wine builds | github.com/Gcenx/macOS_Wine_builds | `72f8915f2d01` | none reported | Community Wine packages | none | Binary provenance unreviewed | Reference only | reference |
| llvm-mingw | github.com/mstorsjo/llvm-mingw | `903f4cf7faa2` | NOASSERTION per GitHub; LICENSE not yet read | ARM64-capable mingw toolchain | `toolchain` probe (this branch) finds it if installed | Clear | External dependency (candidate for #364) | reference |
| Wine | github.com/wine-mirror/wine | see registry | LGPL-2.1 | Upstream of CrossOver's runtime | none | Clear | Reference | reference |
| Apple Game Porting Toolkit licence | text of `D3DMetal/4.0/License.pdf`, copy hosted by Sikarugir | document read, 6 pages | Apple proprietary agreement | See next section | none | Third-party copy of an Apple document; the original download was not read | Proprietary; user-supplied only | reference |
## Apple Game Porting Toolkit licence (for #354)
Read from the 4.0 `License.pdf` copy in the Sikarugir repository (not from Apple's site; confirm against Apple's download before relying on it). Section 2A grants a limited, personal licence to install, internally use and test the software "for the sole purpose of developing, testing, or evaluating video games for use on Apple-branded products", and to distribute it "solely for non-commercial purposes". Section 2C forbids use on non-Apple hardware, says components may not be separated from the bundle except that the Framework and Redistributables may be distributed separately (still non-commercial only), and section 2D forbids reverse engineering. Consequence for BetterXen: D3DMetal stays a user-supplied external component and is never bundled or redistributed by this repository. Whether running unrelated Windows software through it fits "evaluating video games for use on Apple-branded products" is a question for a lawyer, not answered here.
## Decisions
1. **No external code was incorporated.** The useful general-purpose ideas (host receipt, frame statistics, toolchain probe) are small, and the closest implementations are Swift, so they were written independently in Rust from public system interfaces. ossover and Whisky are credited as technical references in this file; nothing is adapted.
2. **GPL-2.0-only projects (MacBox, ScarlettMac) cannot be combined into this GPL-3.0-or-later workspace** regardless of provenance. Both are also game-specific.
3. **Undocumented CrossOver internals are not a stable interface.** ossover reads `cxbottle.conf` and bundle internals derived from reverse engineering. The new CrossOver module reads only `Info.plist`, `lipo -archs` and the `defaults` keys CodeWeavers documents, and states so in its output.
4. **The Metal HUD log parser in ossover was not ported.** Its line format (`metal-HUD: …`) is documented only by that project's observation; it was not verified against Apple documentation or a real trace here. Frame statistics therefore take plain intervals. A HUD parser can be added when a real trace is captured (#145).
## Implemented on this branch
New crate `crates/hybrid` (`betterxen-hybrid`, no third-party dependencies, native arm64 verified with `lipo -archs`: `arm64`).
| Command | Purpose | Issue | Validated |
| --- | --- | --- | --- |
| `host` | macOS version and build, chip, memory, core split, whether an x86_64 binary executes (Rosetta), GPU and Metal family from `system_profiler` | #353 | Run on the M4 reference machine; unit tests parse a GPU fixture |
| `crossover` | Finds `CrossOver.app` in standard locations and by Spotlight bundle identifier; reads version, build, executable architectures, minimum macOS, and the documented `BottleDir` and `ManagedBottleDirs` preferences | #350, #355 | Unit test on a **synthetic** bundle only. On the reference machine it reports `installed: false`. It has never inspected a real CrossOver |
| `toolchain` | Lists mingw-w64 and llvm-mingw cross-compilers on `PATH` with version and target | #364 | Stub-compiler unit test; on the reference machine it found Homebrew `x86_64-w64-mingw32-gcc` 16.2.0 and `i686-w64-mingw32-gcc`. No ARM64 Windows target is installed. No program was compiled or run |
| `frames <file>` | Frame-time statistics: mean, FPS, nearest-rank p50/p95/p99/p99.9, 1 % and 0.1 % lows, stutter count | #145 | Hand-derived known-answer tests, rejection of non-positive or non-finite intervals |
| `receipt` | The above as one JSON document, `betterxen-hybrid-receipt/0` | #353 | Run once; no second contributor has reproduced it |
Not implemented: launching programs, bottle management, graphics-backend selection or detection, GPU or thermal sampling, a HUD parser, any rendering workload. None is justified yet by Phase 1 evidence.
## Contributor request (to send, not sent)
Ask skakwy only for shareable, general information: Mac model, macOS and CrossOver versions, how frame rate was measured and over what duration, whether the two frames were presented or merely rendered, and any general-purpose tooling and authorized test workloads he wrote himself. Do not ask for game files, traces or instructions for running the leaked build.
## Remaining blockers
CrossOver is not installed here, so criteria 2 and 6 of Phase 1 cannot progress on this machine; `docs/research/primary-source-verification-2026-11-25.md` lists documents still to read. The Rust toolchain default (`stable`, 1.94.1) is older than the workspace's 1.100; use `rustup run 1.100.0 cargo`.
## skakwy/victory-mac: component-level review (second pass)
skakwy, the repository's maintainer and a BetterXen contributor, authorized integrating his independently developed work. His permission cannot cover third-party material, and the repository's purpose fixes what most of it is. Reviewed: full history (302 commits, 65 by skakwy, 194 tracked files at `22b3f8e45a59`, `main` on 2026-11-25), every file he authored under `mac/` and `tools/macos/`, and the headers and authorship of the game-facing crates. Nothing was executed; the checkout stayed outside this repository with git hooks disabled.
### What the reported result is
From his own `mac/PROGRESS.md` and `mac/run-victory.sh` (his statements, unverified): the workload is an unpacked Xbox Series X dump of a commercial game, about 209 GB, run through VIctory under a CrossOver Preview bottle with Rosetta 2 and D3DMetal 4.0b2 on an Apple M3 Max with 36 GB and macOS 27.2.1. "About 1 fps" is 1 to 1.9 seconds per frame in the game world over a 17-minute run ("run 31, ~1.1 fps"), with 5,000 to 7,000 draws per frame and a GPU share of 0.15 to 0.5 s of each frame, taken from VIctory's own per-frame log line. So it is real presented frames from a program VIctory drives, measured by that program, on an input that BetterXen's rules forbid. It is **not** reproducible here, was not measured with independent instrumentation, and says nothing about authorized workloads. It does indicate, as an unverified observation, that a Rust-built Windows x86-64 program using D3D12 can reach D3DMetal under CrossOver on macOS 27. BetterXen has no evidence of that yet; the original D3D11 workload built on this branch is the authorized way to test it once CrossOver is installed.
### Component record
Original repository for every row: https://github.com/skakwy/victory-mac (GPL-3.0, file `LICENSE`). Author: skakwy unless stated. Permission: granted by skakwy through the maintainer, not recorded in the repository itself.
| Component | Source path (commit) | Provenance | Classification | BetterXen destination and method | Validation | Limits |
| --- | --- | --- | --- | --- | --- | --- |
| Memory guard: do not start below N % free, stop a workload below M % | `mac/run-victory.sh` (`22b3f8e45a59`) | skakwy only; logic is general | **Integrated, adapted** | `crates/hybrid/src/memory.rs` and the `guard` command, reimplemented in Rust, SIGTERM then SIGKILL, unreadable memory is an error | 6 unit tests including a child stopped on a simulated drop; end-to-end runs of refuse, pass-through and stop; real `memory_pressure -Q` parsed on macOS 27.0 | Output format of `memory_pressure -Q` is not a documented stable interface; one machine |
| Windows cross-link wrapper for the gnullvm target | `tools/macos/gnullvm-cc.sh` (`22b3f8e45a59`) | skakwy only | **Unnecessary here** | Evaluated; not functional with Homebrew `llvm@17`; superseded by llvm-mingw (see hybrid-toolchain.md). Awaiting clarification of the LLVM version he uses | Link failure reproduced | Not integrated |
| Build wrapper for the victory exe | `mac/build.sh` | skakwy only | Unnecessary | Three lines around `cargo build`; `scripts/hybrid/build-windows-workloads.sh` replaces the idea | n/a | n/a |
| CrossOver launch conventions: `bin/wine --bottle B --cx-app EXE run`, `wineserver -k`, prefix at `~/Library/Application Support/CrossOver/Bottles/B`, `CX_GRAPHICS_BACKEND` and `_VERSION` | `mac/run-victory.sh` | skakwy only; observations of "CrossOver Preview" | **Awaiting clarification** / reference | Recorded for #350 as undocumented third-party observations. Not coded: they are not documented interfaces. His note that backend version 3 gave a black screen and 4 worked is game-specific evidence | none | Undocumented; version unknown beyond "Preview" |
| Rosetta observations: AVX masked stores and `vcvtps2ph` stores to write-watched memory hung on macOS 26, handled on 27; `ROSETTA_ADVERTISE_AVX` | `mac/PROGRESS.md`, `mac/run-victory.sh` | skakwy only | Reference | Hypotheses to test with an original workload; no code adopted | none | Unverified; tied to his loader |
| Native helpers: `mach_vm_remap` aliases as a Wine unixlib (`valias`), Metal zero-copy swizzle | `mac/unixlib/*` | skakwy only; the swizzle credits UTM's d3dmetal-native | **Rejected** | The swizzle acts on D3DMetal internals; Apple's licence section 2D forbids reverse engineering and his notes give D3DMetal struct offsets (`+0x58`, `+0x28c`) found that way. The alias code serves game-memory copy-back | none | Awaiting clarification only for `valias` as a generic Wine unixlib example |
| Instruction and shader scanner | `mac/scan/*` | skakwy only | **Rejected** | Parses the game's shader pack format and a Rosetta-unsafe instruction census of its image | none | Game-specific |
| Game-specific loader patches: watchdog stepping, masked-store and MWAIT patching, BCPack placeholder fills | `crates/victory-loader/*`, `mac/PROGRESS.md` | skakwy and others | **Rejected** | Defeats a title's own self-protection and patches a leaked image; never adopted | none | n/a |
| GPU layer, shader emitters, HLE (`victory-gpu`, `victory-shader`, `victory-hle`, `victory-loader`, `victory-core`) | skakwy commits `ea9da87` to `22b3f8e45a59` on top of Marvis, fxceless, Duff and others (about 260 inherited commits) | Mixed: inherited files carry other authors, and the content is console-game recompilation | **Rejected / requires provenance** | His share is real but inseparable from a runtime whose input is unauthorized; the console-shader work is also native-paused scope | none | File-level provenance would be needed for any future reuse |
| Run notes (`mac/PROGRESS.md`, `mac/new_agent.md`) | same | skakwy only | Reference | Source of the context above; not copied | none | Contains game-specific detail, not republished |
Counts for this pass: 11 component groups reviewed; 1 integrated (adapted); 0 integrated verbatim; 3 reference or awaiting clarification; 2 unnecessary; 5 rejected (some groups overlap categories above).
### Other repositories, completed
- **VIctory-macOS** (`pragyaangaur/VIctory-macOS`, 215 files): a fork whose README describes running "the Xbox Series build" of one game; PortWatch calls the efforts it tracks builds of a "leaked Xbox Series build". Workflow files `fleet-*.yml` orchestrate an agent fleet, not build or test infrastructure of value here. Its README says it was built "with Claude on a free Claude Pro plan" and asks for sponsorship; irrelevant to reuse. Rejected, unchanged.
- **PortWatch VI** (portwatch-vi.xyz): its own description says "leaked Xbox Series build of GTA VI". Reference for discovery only, unchanged.
- **MacBox, ScarlettMac:** see above; unchanged.
- **ossover CI** (`.github/workflows/ci.yml`): a macOS arm64 runner running `bash -n` over shell scripts, a standard-library Python manifest check with `python3 -I`, and `swift build`/`test`. The two cheap ideas (shell syntax check, isolated-interpreter script) match what `docs_hygiene.py` already does; a `bash -n` step for `scripts/hybrid/*.sh` is a candidate follow-up, not added.
### Per-file authorship of victory-mac (measured with `git blame` at `22b3f8e45a59`)
"Owned" means every line is attributed to skakwy. His permission covers these; it cannot cover lines written by others, and some owned files still carry other restrictions.
| File (lines, all his) | What it is | Decision |
| --- | --- | --- |
| `crates/victory-shader/src/emit/f64.rs` (409) | fp64 by 64-bit integer operations, with tests against the CPU's `f64` | General-purpose. Candidate for the native shader compiler; native work is paused, so it waits for a maintainer decision (#387) |
| `mac/run-victory.sh` (139), `crates/victory-core/src/notes.rs` (135) | Run script with memory guard; stall bookkeeping | Memory guard adapted (`guard`); stall detection and settle adapted in #385; the rest is game-specific launch configuration |
| `mac/unixlib/*`, `crates/victory-gpu/src/alias.rs` (369), `zerocopy.rs` (365), `crates/victory-hle/src/modules/vmem.rs` (208) | Alias mappings and a Metal swizzle over game memory | Not integrated: they act on D3DMetal internals and game memory (Apple's licence section 2D forbids reverse engineering; his notes give D3DMetal struct offsets) |
| `crates/victory-loader/src/maskmov.rs` (830), `masked_stores.rs` (243) | Rewrites masked AVX stores in a console title's image for Rosetta | Not integrated: the header says it follows XCL's `maskmov.rs`, which is GPL-2.0-only (incompatible with GPL-3.0-or-later), and it patches a title image |
| `crates/victory-gpu/src/ambient.rs` (193), `mac/scan/*` | Replaces one game's lighting output; scans its shader pack | Not integrated: game-specific |
| `crates/victory-gpu/src/dxc.rs` (110) | Loads Microsoft's `dxcompiler.dll` to compile HLSL under Wine | General-purpose. Not needed yet: D3D12 minimal tests can use SM 5.1 through `d3dcompiler_47`. Revisit when a workload needs SM 6 |
| `tools/macos/gnullvm-cc.sh`, `mac/build.sh` | Windows cross-link wrapper, build wrapper | Evaluated; failed with Homebrew `llvm@17`; superseded by llvm-mingw |
Everything else in the repository is mostly or entirely other authors' work (for example `victory-gpu/src/host.rs` is 8 % his, `victory-shader/src/emit/lower.rs` 1 %).
+4 -15
View File
@@ -15,6 +15,10 @@ Reviewed 2026-11-25. Every entry is **evidence class D** (non-normative official
| VIctory-macOS | [pragyaangaur/VIctory-macOS](https://github.com/pragyaangaur/VIctory-macOS) | `485b230ef596` | GPL-3.0 (GitHub) | Discovery reference only | A macOS port of VIctory using Rosetta, CrossOver Wine and D3DMetal per its README (also noted in [portwatch-native-macos.md](portwatch-native-macos.md)). Same input concern. Its test and "works" claims are self-reported and not verified here. The repository has no parent fork, so the "canonical upstream" is VIctory. |
| PortWatch VI | [portwatch-vi.xyz](https://portwatch-vi.xyz/), [4lwayz/portwatch-vi](https://github.com/4lwayz/portwatch-vi) | `ed00263cc0c9` | NOASSERTION | Project discovery reference | A tracker of community efforts; progress figures are editorial, with self-reported claims labelled. Not engineering evidence; flagged and ignored queues are not endorsed. |
## victory-shader import under review
`skakwy/victory-mac` `crates/victory-shader` at `22b3f8e45a59` is proposed for vendoring in PR #394. **Not approved.** See the [per-file provenance and licence review](victory-shader-provenance.md); the provenance decision below stands until a maintainer changes it.
## Additional candidates found by search (not reviewed)
Found by GitHub search on 2026-11-25. Only repository metadata was read; none was evaluated, installed or run, and none is a recommendation. Licenses are what GitHub reported.
@@ -27,21 +31,6 @@ Found by GitHub search on 2026-11-25. Only repository metadata was read; none wa
| Mythic | [MythicApp/Mythic](https://github.com/MythicApp/Mythic) | `754223978e61` | GPL-3.0 | Open-source macOS launcher that runs Windows games through Wine: an architecture reference for configuration and launching. |
| Playdock | [Jasonilization/Playdock](https://github.com/Jasonilization/Playdock) | `f58b8ef7fb70` | MIT | Describes itself as a free alternative to CrossOver; unreviewed. |
## Reviewed in the integration audit (2026-11-25)
Source read through the GitHub API; nothing executed. Detail and decisions are in [upstream-integration-audit.md](upstream-integration-audit.md).
| Project | Source | Pin (head) | License as reported | Role for BetterXen | Findings |
| --- | --- | --- | --- | --- | --- |
| victory-mac | [skakwy/victory-mac](https://github.com/skakwy/victory-mac) | `22b3f8e45a59` | GPL-3.0 (LICENSE file read) | Per-component review with contributor permission; one memory-guard idea adapted | The maintainer authorized integration of his own work. His runtime targets a leaked console-game dump, so game-facing code is not adopted. Component table in [upstream-integration-audit.md](upstream-integration-audit.md). Reported frame rates are his unverified statements. |
| llvm-mingw | [mstorsjo/llvm-mingw](https://github.com/mstorsjo/llvm-mingw) | release `20261117` | Apache-2.0 with LLVM exceptions plus component licences (LICENSE.TXT; not audited line by line) | External build tool for #364 | Digest verified, used to build original workloads for x86-64 and ARM64; see [hybrid-toolchain.md](hybrid-toolchain.md). |
| MacBox | [aykhanium/MacBox](https://github.com/aykhanium/MacBox) | not pinned | GPL-2.0 (GitHub) | Rejected for reuse | Game-specific XCL layer; GPL-2.0-only is not combinable with GPL-3.0-or-later. Its README states gameplay is unverified. |
| ScarlettMac | [paveledits/ScarlettMac](https://github.com/paveledits/ScarlettMac) | not pinned | GPL-2.0 (GitHub), extra licence files | Rejected for reuse | Game-specific patches and scripts. |
| ossover | [hemkum/ossover](https://github.com/hemkum/ossover) | `5c11bd7be8da` | GPL-3.0-or-later (README, attribution file) | Technical reference | Swift CLI with system-info, Metal HUD log parsing and benchmark harness. Uses reverse-engineered CrossOver internals, which BetterXen does not treat as an interface. |
| Whisky | [Whisky-App/Whisky](https://github.com/Whisky-App/Whisky) | `fd5480a76b3e` | GPL-3.0-or-later (file header read) | Technical reference | Archived 2025-05-11. |
| rum | [lunguini/rum](https://github.com/lunguini/rum) | `657461b194e1` | GPL-3.0 (GitHub) | Technical reference | Active Whisky fork. |
| Game Porting Toolkit licence | copy of `D3DMetal/4.0/License.pdf` in Sikarugir | read | Apple proprietary | User-supplied only | Non-commercial distribution, evaluation purpose, no reverse engineering. See audit file. |
## Not yet researched
Apple's Game Porting Toolkit documentation and license (D3DMetal's actual terms), Rosetta 2's support lifetime, CrossOver's documented command-line interfaces and bottle management, and other established projects. These are issues #349, #350 and #354; nothing is claimed about them here.
+10 -9
View File
@@ -1,6 +1,6 @@
# victory-shader integration (GFX10 to DXIL recompiler)
Evidence: classes noted per row. Everything ran on one machine (Apple M4, 24 GiB, macOS 27.0, CrossOver 26.3.0.39832, bottle `betterxen-test`, default backend) and has **not been independently reproduced**. No game, console title or leaked material was used.
Evidence: classes noted per row. Everything ran on one machine (Apple M4, 24 GiB, macOS 27.0, CrossOver 26.3.0.39832, bottle `betterxen-test`, default backend) and has **not been independently reproduced**. BetterXen's runs used no game files or leaked material. **The vendored code itself was developed against one commercial title's shaders** and is not approved for merge: see [victory-shader-provenance.md](victory-shader-provenance.md).
## What was integrated
@@ -12,7 +12,7 @@ Left out on purpose: the upstream repository's loader, HLE, GPU runtime and game
- `emit::translate_native` (BetterXen addition, `emit/betterxen.rs`): the crate only accepted shaders inside console containers; this entry point takes a compute program as machine code plus root layout, which is what BetterXen has.
- `emit/betterxen_tests.rs`: BetterXen's own synthetic gfx1030 Wave32 fixtures (`fixtures/rdna2/*.bin`, original, assembled with LLVM's `llvm-mc`) are wrapped in a short descriptor-table prologue, translated to DXIL, and compared with the expected words in `fixtures/manifest.toml`. Those expectations were derived by hand in the manifest and are checked by BetterXen's independent reference; none comes from the recompiler. Six of the eleven manifest fixtures have input and expected words (add, float-exact, bitwise-branch, or, shifts, ashr); the five graphics-stage fixtures (`x9-*`) have none and are not bridged.
- `scripts/hybrid/run-shader-gpu-tests.sh`: cross-builds the test executable (llvm-mingw, `x86_64-pc-windows-gnullvm`) and runs it through `betterxen-hybrid run`, so the supervision, memory guard, stall detection and JSON record apply.
- Running the cross-built Windows test executable under CrossOver is done by `scripts/hybrid/run-shader-gpu-tests.sh` through `betterxen-hybrid run`. Those live in separate pull requests (the hybrid runner, and the script on top of it); the GPU results below were produced with them.
## Results
@@ -24,23 +24,24 @@ Left out on purpose: the upstream repository's loader, HLE, GPU runtime and game
| BetterXen fixtures run on the GPU: D3D12 under CrossOver 26.3 (D3DMetal) | **6 of 6 output words match the manifest** | via `betterxen-hybrid run`, 2.3 to 2.6 s including bottle start; the GPU is a D3D12 device with shader model 6.6 as upstream's host layer requires |
| Negative control | a flipped expected word is rejected; the output is not the zeroed buffer | `a_wrong_expectation_is_detected` |
| Same GPU tests on DXMT, DXVK and wined3d (no D3D12) | fail with "no SM 6.6 D3D12 hardware device: not verified" | confirms they cannot pass by skipping; upstream's own tests print "skipped" instead |
| Whole suite under CrossOver (default backend), 229 tests including BetterXen's 4 | 224 passed, **2 failed**, 3 ignored | see below |
| Whole upstream suite, vendored unchanged, under CrossOver (default backend), 229 tests | 224 passed, **2 failed**, 3 ignored | the two failures are explained in `shader-wave-semantics.md` |
| Whole suite with the fixes in this PR, under CrossOver | **232 tests: 229 passed, 0 failed, 3 ignored** | the 3 additional tests are BetterXen's f64 tests; see below |
| Upstream suite on a backend without D3D12 (DXMT) | 201 passed, 25 failed, 3 ignored | see the classification below |
The two failures are `whole_wave_f64_sum_and_cvt_f32_f64` (a wave-wide fp64 sum returned 0, expected `0x40a00000`) and `a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit` (64 lanes: got 0, expected `0x5914`). Both are cross-lane wave reductions of the console's 64-lane waves. Hypothesis, **not verified**: the host's waves are 32 lanes wide (Apple GPU) and D3DMetal does not honour the required wave size or wave operation semantics. The cause, and whether upstream passes them on a Windows GPU, were not investigated.
## Which tests actually executed on the GPU
The harness reports a test as passed whether or not it touched the GPU; many return early when no device is available. Each of the 229 tests was therefore run on both the default backend (D3D12 via D3DMetal) and DXMT (no D3D12), with libtest JSON output including each test's own printed output (`--format json --show-output`). A test counts as GPU-dependent if its outcome changes without D3D12 or it prints "no SM 6.6 hardware device; skipped" there.
The harness reports a test as passed whether or not it touched the GPU; many return early when no device is available. Each test was therefore run on the default backend (D3D12 via D3DMetal) and on DXMT (no D3D12), with libtest JSON output including each test's own printed output (`--format json --show-output`). A test counts as GPU-dependent if its outcome changes without D3D12 or it prints "no SM 6.6 hardware device; skipped" there. Final content of this PR (232 tests: 225 upstream, 7 BetterXen):
| Group | Tests |
| --- | --- |
| Executed on the D3D12 hardware device and passed | 30 (25 of them fail without D3D12; 5 pass only by skipping without it) |
| Executed on the D3D12 hardware device and failed | 2 (they "pass" without D3D12 by skipping, which hides the failure) |
| Not GPU-dependent: CPU-side (decode, structurize, lower, emit, container) or ignored | 197, including 3 ignored |
| Total | 229 (225 upstream + 4 BetterXen; BetterXen's 2 GPU tests are among the 32 GPU-dependent) |
| Executed on the D3D12 hardware device and passed | **31** (26 of them fail without D3D12; 5 pass only by skipping there) |
| Executed on the D3D12 hardware device and failed | **0** |
| Not GPU-dependent: CPU-side (decode, structurize, lower, emit, container) or ignored | 201, including 3 ignored |
| Total | 232 |
Counts are by name from the JSON events and are exact for this binary and machine. "WARP" skips (the software adapter, which Wine does not provide) and "no `dxil.dll`" skips are not GPU runs and are not counted as such.
For the vendored upstream code before the fixes in this PR the same method gave 229 tests: 32 GPU-dependent, 30 passed on the device and 2 failed (they "passed" without D3D12 by skipping, which hid the failures), see `shader-wave-semantics.md`. Three of the 31 are BetterXen's GPU tests (fixtures, negative control, bit-exact f64 sums). Counts are by name from the JSON events and are exact for this binary and machine. "WARP" skips (the software adapter, which Wine does not provide) and "no `dxil.dll`" skips are not GPU runs and are not counted as such.
## Limits
@@ -0,0 +1,66 @@
# victory-shader: per-file provenance and licence review
**Status: NOT APPROVED. A maintainer decision is required before PR #394 can merge.** This is the review the engineering rules require for VIctory-family code. It records facts; it does not grant approval, and its author is the person who proposed the import, so it is not an independent review.
Upstream: <https://github.com/skakwy/victory-mac>, revision `22b3f8e45a59f7d11fef7718988c58d0b3f1d0f9`. Method: every tracked file of `crates/victory-shader/` at that revision; authors from `git shortlog`; licence from the repository `LICENSE` and a search of each file for other notices; title references by searching for shader names of the form `module:CS_Name` and the words title, titles, game, games. The search finds references, not every dependence: a file without one may still have been developed against the same title.
## Findings
1. **Licence:** GPL-3.0, compatible with BetterXen's GPL-3.0-or-later. One third-party notice (Mesa-derived opcode names, MIT, Valve) in `src/gfx10/opcodes.rs`, kept. Some comments cite Mesa behaviour and LLVM definitions. skakwy and the VIctory-macOS maintainer authorized reuse of their own contributions (relayed by the maintainer); other authors' lines rest on the repository licence.
2. **The crate was developed against one commercial title's shaders.** 17 of 36 files refer to "the title" or "the game"; comments describe that title's programs, layouts and structures, and four places cite its shaders by name (`wave64_tests.rs`, `wave.rs`, `own_bits.rs`). The upstream project's stated purpose is to run that title's Xbox Series build; this registry and PortWatch record that build as leaked.
3. **What is not in the crate:** a search found no shader binaries, shader dumps, game assets, keys or decryption code. The references are in comments, test descriptions and handling of shader constructs.
4. **Earlier statements that were wrong:** the integration record and PR descriptions said the crate had nothing game-specific. That claim came from searching only for the game's and publisher's names. It is withdrawn.
## How this meets the engineering rules (`AGENTS.md`)
| Rule | Assessment |
| --- | --- |
| "Projects whose stated purpose depends on leaked or unauthorized builds ... are discovery references at documentation level; adopt nothing from them without a per-file provenance and license review recorded in the registry." | This file is that record. Recording it does not by itself approve adoption. |
| "Game-specific, asset-specific and decryption-related code is never adopted." | Handling written for and documented against one title's shaders is present in at least some files. Whether that makes a file "game-specific code" is the decision to make; it is a general GFX10 recompiler in structure, with title-driven behaviour inside it. |
| "Provenance first: exclude anything derived from leaked proprietary material or unauthorized software." | Layouts "as observed in shipped titles" (`native.rs`) and behaviour tuned to the title's programs are plausibly derived from that material. |
| "Never copy, port, translate or adapt source from emulator projects built for leaked or unauthorized material." | Read plainly, this applies to this import. Author permission does not change it. |
**Reviewer's recommendation to the maintainer:** under the rules as written, do not merge the import. Either decline it (keep the crate as a documentation-level reference; BetterXen's own fixtures, probes and findings stand on their own), or change the rule explicitly in `AGENTS.md` with the legal question considered, and then decide file by file. This is not legal advice.
## Per-file record
| File (under `crates/victory-shader/`) | Lines | Upstream authors (commits) | Licence and third-party notes | Shader names of a title | Lines saying title/game |
| --- | --- | --- | --- | --- | --- |
| `Cargo.toml` | 40 | Marvis (2), fxceless (1) | GPL-3.0 (repository licence) | - | - |
| `src/bvh.rs` | 696 | fxceless (2) | GPL-3.0 (repository licence) | - | 5 |
| `src/dxbc.rs` | 181 | Marvis (2) | GPL-3.0 (repository licence) | - | - |
| `src/dxil.rs` | 211 | Marvis (1) | GPL-3.0 (repository licence); cites LLVM | - | - |
| `src/emit/bitcode.rs` | 1240 | Marvis (3), fxceless (2), Lyrnc (1) +2 more | GPL-3.0 (repository licence); cites LLVM | - | - |
| `src/emit/bitcode/census.rs` | 174 | fxceless (1) | GPL-3.0 (repository licence) | - | - |
| `src/emit/bitcode/opt.rs` | 2140 | armin (1), fxceless (1) | GPL-3.0 (repository licence) | - | 1 |
| `src/emit/container.rs` | 419 | Duff (1), Marvis (1), fxceless (1) +1 more | GPL-3.0 (repository licence) | - | - |
| `src/emit/diff_tests.rs` | 1287 | Marvis (3), fxceless (1) | GPL-3.0 (repository licence) | - | 5 |
| `src/emit/f64.rs` | 409 | skakwy (1) | GPL-3.0 (repository licence) | - | - |
| `src/emit/host.rs` | 1472 | fxceless (3), Marvis (1), skakwy (1) | GPL-3.0 (repository licence) | - | - |
| `src/emit/intersect.rs` | 557 | fxceless (1) | GPL-3.0 (repository licence) | - | 12 |
| `src/emit/intersect_tests.rs` | 690 | fxceless (1) | GPL-3.0 (repository licence) | - | 15 |
| `src/emit/lower.rs` | 12268 | Marvis (21), skakwy (9), fxceless (6) +23 more | GPL-3.0 (repository licence); comment cites Mesa behaviour; cites LLVM | - | 18 |
| `src/emit/mod.rs` | 1755 | Marvis (7), fxceless (6), skakwy (4) +8 more | GPL-3.0 (repository licence) | - | 16 |
| `src/emit/own_bits.rs` | 914 | fxceless (1) | GPL-3.0 (repository licence) | 1 | 3 |
| `src/emit/rect.rs` | 484 | fxceless (2) | GPL-3.0 (repository licence) | - | 2 |
| `src/emit/sampler.rs` | 125 | Marvis (1) | GPL-3.0 (repository licence) | - | 1 |
| `src/emit/shader.rs` | 908 | fxceless (4), Claude (1), Duff (1) +4 more | GPL-3.0 (repository licence) | - | 8 |
| `src/emit/threading.rs` | 218 | fxceless (1) | GPL-3.0 (repository licence) | - | - |
| `src/emit/validator.rs` | 221 | Marvis (1), lameloball2813-ui (1) | GPL-3.0 (repository licence) | - | - |
| `src/emit/valu_tests.rs` | 1624 | Marvis (6), r4. (5), fxceless (4) +6 more | GPL-3.0 (repository licence) | - | - |
| `src/emit/waterfall_tests.rs` | 435 | r4. (3), Marvis (1), Noname0202 (1) +1 more | GPL-3.0 (repository licence) | - | - |
| `src/emit/wave.rs` | 1228 | fxceless (3), skakwy (2), AscilCH (1) +1 more | GPL-3.0 (repository licence) | 1 | - |
| `src/emit/wave64_tests.rs` | 532 | fxceless (1), triippywhale (1) | GPL-3.0 (repository licence) | 2 | - |
| `src/gfx10/fields.rs` | 815 | Marvis (1), fxceless (1) | GPL-3.0 (repository licence) | - | - |
| `src/gfx10/mod.rs` | 496 | Marvis (3), tedin7 (1) | GPL-3.0 (repository licence) | - | - |
| `src/gfx10/opcodes.rs` | 1333 | Duff (1), Marvis (1) | GPL-3.0 (repository licence); Mesa-derived, MIT (Valve), notice in header; cites LLVM | - | - |
| `src/gfx10/sp3.rs` | 784 | Marvis (1) | GPL-3.0 (repository licence) | - | - |
| `src/io.rs` | 826 | Marvis (1), fxceless (1), local (1) | GPL-3.0 (repository licence) | - | - |
| `src/ir.rs` | 1791 | fxceless (4), Marvis (2), Yaekai (1) +1 more | GPL-3.0 (repository licence) | - | 1 |
| `src/lib.rs` | 38 | Marvis (3), fxceless (1) | GPL-3.0 (repository licence); cites LLVM | - | - |
| `src/native.rs` | 1103 | Marvis (4), fxceless (1), local (1) | GPL-3.0 (repository licence) | - | 1 |
| `src/resource.rs` | 3848 | Claude (3), fxceless (3), Marvis (2) +2 more | GPL-3.0 (repository licence); cites LLVM | - | 10 |
| `src/spill.rs` | 380 | fxceless (2) | GPL-3.0 (repository licence) | - | 1 |
| `src/structure.rs` | 1899 | Marvis (2), fxceless (2), DexNom (1) +2 more | GPL-3.0 (repository licence) | - | - |
BetterXen's additions (`src/emit/betterxen.rs`, `src/emit/betterxen_tests.rs`, `Cargo.toml`, `UPSTREAM.md`) are original, GPL-3.0-or-later. Functional edits to upstream files are listed in `crates/victory-shader/UPSTREAM.md`.
-50
View File
@@ -1,50 +0,0 @@
#!/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,
# Apache-2.0 with LLVM exceptions); see 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=${1:?usage: $0 <llvm-mingw-dir>}
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; }
for arch in x86_64 aarch64; 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/workloads/win-selfcheck-c/selfcheck.c"
"$TC/bin/$arch-w64-mingw32-clang" -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
-o "$d/d3d11-clear.exe" "$ROOT/workloads/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/workloads/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"
cd "$ROOT/workloads/win-selfcheck-rust"
CARGO_TARGET_DIR="$OUT/rust-target" rustup run "$RUSTC_TC" cargo build --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 "$OUT"/aarch64/*.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
+39 -6
View File
@@ -16,19 +16,52 @@ BOTTLE=${2:-betterxen-test}
WHICH=${3:-fixtures}
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
cd "$ROOT"
# Build the host tool first, into the normal target directory, before the Windows build redirects it.
rustup run 1.100.0 cargo build -q -p betterxen-hybrid
# Both executables are taken from the messages of the cargo invocation that built them, and only
# when that invocation succeeded: no path is guessed and nothing left over from an earlier build can
# be run. (Cargo is not piped into the parser: under /bin/sh a pipeline reports only the parser's
# exit status.)
LOG=$(mktemp)
trap 'rm -f "$LOG"' EXIT
# built_exe <target name> <is test: true|false>: the executable named in $LOG.
built_exe() {
python3 -I -c '
import json, sys
name, test, exe = sys.argv[1], sys.argv[2] == "true", ""
for line in open(sys.argv[3]):
try:
m = json.loads(line)
except ValueError:
continue
t = m.get("target", {})
if (m.get("reason") == "compiler-artifact" and m.get("executable")
and t.get("name", "").replace("-", "_") == name
and bool(m.get("profile", {}).get("test")) == test):
exe = m["executable"]
print(exe)' "$1" "$2" "$LOG"
}
# The host tool first, before the environment is pointed at the Windows toolchain.
rustup run 1.100.0 cargo build -q -p betterxen-hybrid --message-format=json-render-diagnostics >"$LOG" \
|| { echo "building betterxen-hybrid failed" >&2; exit 1; }
B=$(built_exe betterxen_hybrid false)
[ -n "$B" ] && [ -x "$B" ] || { echo "the host build named no betterxen-hybrid executable" >&2; exit 1; }
export PATH="$TC/bin:$PATH"
export CARGO_TARGET_X86_64_PC_WINDOWS_GNULLVM_LINKER="$TC/bin/x86_64-w64-mingw32-clang"
export CARGO_TARGET_DIR="$ROOT/artifacts/victory-win"
rustup run 1.100.0 cargo test -q -p victory-shader --target x86_64-pc-windows-gnullvm --no-run
EXE=$(ls -t "$CARGO_TARGET_DIR"/x86_64-pc-windows-gnullvm/debug/build/victory-shader/*/out/victory_shader-*.exe | head -1)
rustup run 1.100.0 cargo test -q -p victory-shader --target x86_64-pc-windows-gnullvm --no-run \
--message-format=json-render-diagnostics >"$LOG" \
|| { echo "building the victory-shader test executable failed" >&2; exit 1; }
EXE=$(built_exe victory_shader true)
[ -n "$EXE" ] && [ -f "$EXE" ] || { echo "the build named no victory-shader test executable" >&2; exit 1; }
file "$EXE" | grep -q "PE32+ executable.*x86-64" || { echo "not an x86-64 PE: $EXE" >&2; exit 1; }
B="$ROOT/target/debug/betterxen-hybrid"
rm -f "$LOG"
if [ "$WHICH" = all ]; then
exec "$B" run --bottle "$BOTTLE" --timeout 900 --stall-timeout 120 --expect "test result: ok" \
--out artifacts/hybrid-runs -- "$EXE" --test-threads=1
else
exec "$B" run --bottle "$BOTTLE" --timeout 300 --stall-timeout 120 --expect "test result: ok. 4 passed" \
# The exact count is deliberate: a looser marker would also accept a filter that matches nothing
# ("0 passed"). Update it when BetterXen adds or removes tests in emit/betterxen_tests.rs.
exec "$B" run --bottle "$BOTTLE" --timeout 300 --stall-timeout 120 --expect "test result: ok. 10 passed" \
--out artifacts/hybrid-runs -- "$EXE" betterxen --test-threads=1
fi
+79
View File
@@ -0,0 +1,79 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Regression test for run-shader-gpu-tests.sh with a stubbed `rustup`/cargo and a stubbed runner:
# no toolchain, CrossOver or GPU is needed. Checks that
# 1. a failed Windows test build stops the script and the runner is never invoked, even when an
# older test executable is lying in the target directory;
# 2. a successful build runs exactly the executable that build named;
# 3. the host runner is the one the host build named, also with an inherited CARGO_TARGET_DIR.
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
T=$(mktemp -d)
trap 'rm -rf "$T"' EXIT
fails=0
check() { if eval "$2"; then echo "ok $1"; else echo "FAIL $1"; fails=1; fi; }
# A file `file` reports as an x86-64 PE32+ executable.
make_pe() {
python3 -I -c '
import struct, sys
b = bytearray(512); b[0:2] = b"MZ"; struct.pack_into("<I", b, 0x3C, 0x80)
b[0x80:0x84] = b"PE\0\0"; struct.pack_into("<HHIIIHH", b, 0x84, 0x8664, 0, 0, 0, 0, 240, 0x22)
struct.pack_into("<H", b, 0x98, 0x20B); struct.pack_into("<H", b, 0x98 + 68, 3)
open(sys.argv[1], "wb").write(b)' "$1"
}
setup() { # $1 = case directory
R=$1/repo
mkdir -p "$R/scripts/hybrid" "$1/bin" "$1/tc/bin"
cp "$HERE/run-shader-gpu-tests.sh" "$R/scripts/hybrid/"
: > "$1/tc/bin/x86_64-w64-mingw32-clang"; chmod +x "$1/tc/bin/x86_64-w64-mingw32-clang"
# The stub runner records how it was called.
runner() { mkdir -p "$(dirname "$1")"; printf '#!/bin/sh\necho "$0 $*" >> "%s"\n' "$2" > "$1"; chmod +x "$1"; }
# A runner left over from an earlier build at the old hard-coded place.
runner "$R/target/debug/betterxen-hybrid" "$1/stale-runner.log"
# An older test executable lying around in the target directory.
old="$R/artifacts/victory-win/x86_64-pc-windows-gnullvm/debug/deps"
mkdir -p "$old"; make_pe "$old/victory_shader-0000stale.exe"
cat > "$1/bin/rustup" <<STUB
#!/bin/sh
# stands in for: rustup run 1.100.0 cargo <build|test> ...
shift 3
cmd=\$1
dir=\${CARGO_TARGET_DIR:-$R/target}
case "\$cmd" in
build)
mkdir -p "\$dir/debug"
printf '#!/bin/sh\necho "\$0 \$*" >> "%s"\n' "$1/runner.log" > "\$dir/debug/betterxen-hybrid"
chmod +x "\$dir/debug/betterxen-hybrid"
echo "{\"reason\":\"compiler-artifact\",\"target\":{\"name\":\"betterxen-hybrid\",\"kind\":[\"bin\"]},\"profile\":{\"test\":false},\"executable\":\"\$dir/debug/betterxen-hybrid\"}"
;;
test)
[ "\${STUB_TEST_BUILD_FAILS:-0}" = 1 ] && exit 101
mkdir -p "\$dir/fresh"; cp "$old/victory_shader-0000stale.exe" "\$dir/fresh/victory_shader-1111new.exe"
echo "{\"reason\":\"compiler-artifact\",\"target\":{\"name\":\"victory_shader\",\"kind\":[\"lib\"]},\"profile\":{\"test\":true},\"executable\":\"\$dir/fresh/victory_shader-1111new.exe\"}"
;;
esac
STUB
chmod +x "$1/bin/rustup"
}
# 1. failed test build
c=$T/fail; setup "$c"
STUB_TEST_BUILD_FAILS=1 PATH="$c/bin:$PATH" sh "$c/repo/scripts/hybrid/run-shader-gpu-tests.sh" "$c/tc" >/dev/null 2>&1; rc=$?
check "failed build: script exits non-zero (got $rc)" "[ $rc -ne 0 ]"
check "failed build: no runner is invoked" "[ ! -e '$c/runner.log' ] && [ ! -e '$c/stale-runner.log' ]"
# 2. successful build
c=$T/ok; setup "$c"
PATH="$c/bin:$PATH" sh "$c/repo/scripts/hybrid/run-shader-gpu-tests.sh" "$c/tc" >/dev/null 2>&1; rc=$?
check "good build: script succeeds (got $rc)" "[ $rc -eq 0 ]"
check "good build: runs the executable this build named" "grep -q 'victory_shader-1111new.exe' '$c/runner.log' 2>/dev/null"
# 3. inherited CARGO_TARGET_DIR
c=$T/dir; setup "$c"
CARGO_TARGET_DIR="$c/elsewhere" PATH="$c/bin:$PATH" sh "$c/repo/scripts/hybrid/run-shader-gpu-tests.sh" "$c/tc" >/dev/null 2>&1; rc=$?
check "inherited target dir: script succeeds (got $rc)" "[ $rc -eq 0 ]"
check "inherited target dir: the freshly built runner is used" "grep -q '$c/elsewhere/debug/betterxen-hybrid' '$c/runner.log' 2>/dev/null"
check "inherited target dir: the stale runner is not used" "[ ! -e '$c/stale-runner.log' ]"
exit $fails
+1 -30
View File
@@ -15,7 +15,7 @@ def dump(obj, path):
WF = os.path.join(ROOT, ".github", "workflows")
QUEUE_WORKFLOWS = ["agent-claims.yml", "agent-pr-checks.yml"]
QUEUE_WORKFLOWS = ["agent-claims.yml"]
USER_TEXT = re.compile(r"\$\{\{\s*github\.event\.(comment|issue|pull_request)\.(body|title)|github\.head_ref")
@@ -58,11 +58,6 @@ class Workflows(unittest.TestCase):
bad = "jobs:\n a:\n steps:\n - run: |\n echo ${{ github.event.comment.body }}\n"
self.assertTrue(any(re.search(r"\$\{\{", b) for b in run_blocks(bad)))
def test_pr_workflow_never_checks_out_pr_code(self):
text = self.read("agent-pr-checks.yml")
self.assertNotRegex(text, r"github\.event\.pull_request\.head|ref:\s*\$\{\{")
self.assertIn("pull_request_target", text)
def job(self, name, job):
"""Text of one job block: from ` <job>:` to the next two-space-indented key."""
m = re.search(r"(?ms)^ %s:\n(.*?)(?=^ \S|\Z)" % re.escape(job), self.read(name))
@@ -74,9 +69,7 @@ class Workflows(unittest.TestCase):
def test_only_command_comments_start_runs(self):
# Ordinary comments must not start a claim run or a verification re-run.
self.assertIn("startsWith(github.event.comment.body, '/verified')", self.job_if("agent-pr-checks.yml", "verify"))
self.assertIn("startsWith(github.event.comment.body, '/')", self.job_if("agent-claims.yml", "command"))
self.assertNotIn("issue_comment", self.job_if("agent-pr-checks.yml", "check"))
def test_claim_jobs_share_one_group_and_replay(self):
for job in ("command", "audit"):
@@ -87,15 +80,6 @@ class Workflows(unittest.TestCase):
self.assertIn("--recent-commands", text, job)
self.assertNotIn("agent_queue decide", self.job("agent-claims.yml", "command"))
def test_rerun_needs_an_accepted_verification(self):
text = self.job("agent-pr-checks.yml", "verify")
self.assertIn('if ! python3 -m agent_queue should-rerun --actions "$RUNNER_TEMP/actions.json"; then exit 0; fi', text)
self.assertLess(text.index("agent_queue should-rerun"), text.index("agent_queue pr-check"))
# The check is evaluated in this job: pull_request_target runs cannot be found by head SHA.
self.assertNotIn("gh run", text)
self.assertNotIn("actions: write", text)
self.assertIn("::warning title=Agent PR check (advisory)::", text)
def test_should_rerun_exit_codes(self):
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "a.json")
@@ -104,19 +88,6 @@ class Workflows(unittest.TestCase):
dump(actions, p)
self.assertEqual(Cli.run_cli(self, "should-rerun", "--actions", p).returncode, code, actions)
def test_verify_runs_one_at_a_time_per_pull_request(self):
text = self.job("agent-pr-checks.yml", "verify")
self.assertRegex(text, r"group: agent-verify-\$\{\{ github\.event\.issue\.number \}\}\n\s+cancel-in-progress: false")
def test_pr_check_is_advisory(self):
# Exit status 1 (problems found) only warns until the live smoke test and issue migration.
text = self.job("agent-pr-checks.yml", "check")
found = re.search(r'if \[ "\$status" -eq 1 \]; then\n(.*?)\n\s+elif \[ "\$status" -ne 0 \]; then\n\s+exit "\$status"', text, re.S)
self.assertIsNotNone(found, text)
self.assertIn("::warning title=Agent PR check (advisory)::", found.group(1))
self.assertNotIn("exit", found.group(1))
self.assertEqual(text.count("exit "), 1)
def test_actions_pinned_by_sha(self):
for name in QUEUE_WORKFLOWS:
for use in re.findall(r"uses:\s*(\S+)", self.read(name)):
-71
View File
@@ -1,71 +0,0 @@
// 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;
}
-147
View File
@@ -1,147 +0,0 @@
// 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; QueryPerformanceFrequency(&freq);
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;
while (ID3D11DeviceContext_GetData(ctx, (ID3D11Asynchronous *)q, &done, sizeof done, 0) != S_OK || !done) { }
QueryPerformanceCounter(&now);
printf("frame_ms %.4f\n", (double)(now.QuadPart - prev.QuadPart) * 1000.0 / (double)freq.QuadPart);
prev = now;
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;
}
+143
View File
@@ -0,0 +1,143 @@
// 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));
}
}
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);
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; }
fseek(fp, 0, SEEK_END); long n = ftell(fp); fseek(fp, 0, SEEK_SET);
void *code = malloc((size_t)n);
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_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);
CK(ID3D12CommandQueue_Signal(q, fence, 1), "signal");
ID3D12Fence_SetEventOnCompletion(fence, 1, ev);
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]);
return 0;
}
int main(int argc, char **argv) {
if (argc == 2 && !strcmp(argv[1], "caps")) return caps();
if (argc == 5 && !strcmp(argv[1], "run")) return run(argv[2], (unsigned)atoi(argv[3]), (unsigned)atoi(argv[4]));
printf("usage: d3d12_run caps | run <shader.dxil> <groups_x> <out_dwords>\n");
return 1;
}
+12
View File
@@ -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 `ad31b1fc...a7e7f1`, equal to
the release digest; an external tool, not vendored) and dispatched with `d3d12_run.exe run <shader.dxil> 1 <dwords>`
under CrossOver. Expected values were worked out by hand before running. Results and what they show:
`docs/research/shader-wave-semantics.md`.
```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));
}
-51
View File
@@ -1,51 +0,0 @@
// 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;
}
-7
View File
@@ -1,7 +0,0 @@
# 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"
-10
View File
@@ -1,10 +0,0 @@
[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]
-44
View File
@@ -1,44 +0,0 @@
// 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
// 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");
}