mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 19:30:43 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
34a78edab6 | ||
|
|
e1b6a24a4f | ||
|
|
566272082a | ||
|
|
64ba56079f | ||
|
|
e266670e87 | ||
|
|
54b06fea3e | ||
|
|
8eb25fb9fe | ||
|
|
40ffea2789 | ||
|
|
80eacf9ac2 | ||
|
|
d9816e4cb5 |
No files matched your search
@@ -10,6 +10,14 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
- 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.
|
||||
- Documented the original Windows workload set and Phase 1 hybrid measurement protocol (#353), including receipt-field sources, percentile definitions, negative controls and independent reproduction requirements. The protocol identifies the unmerged runner candidate and its missing raw traces and measurements; it adds no execution or compatibility claim.
|
||||
- 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.
|
||||
@@ -54,6 +62,7 @@ remains unsupported.
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Fixed
|
||||
- Hybrid run and benchmark reports now use exclusive, unique filenames and report persistence failures as CLI errors. Earlier reports are preserved; this fixes evidence loss during baseline collection (#398).
|
||||
- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed.
|
||||
- Startup reports now reject existing destinations before guest execution, surface journal write failures, and preserve late errors alongside signal termination.
|
||||
- Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command.
|
||||
|
||||
Generated
+17
-13
@@ -2,6 +2,23 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "betterxen"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-decoder",
|
||||
"xenora-import-gen",
|
||||
"xenora-isa",
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "betterxen-hybrid"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
@@ -149,19 +166,6 @@ version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "betterxen"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-decoder",
|
||||
"xenora-import-gen",
|
||||
"xenora-isa",
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-benchmarks"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -15,3 +15,5 @@ Cargo resolves the Rust packages from crates.io at the source checksums in [Carg
|
||||
[LLVM 23.1.6](https://github.com/llvm/llvm-project/tree/5b10d2d74929eae78912771222c9855af97496f4) is used as an external fixture tool under Apache-2.0 WITH LLVM-exception. Xcode and Metal are separate Apple tools under Apple's license terms.
|
||||
|
||||
The [isolated fuzz workspace](fuzz/Cargo.lock) resolves developer-only dependencies, including [libfuzzer-sys](https://github.com/rust-fuzz/libfuzzer/tree/719e4efb9b8857ebaa782ae59376c8cbb78fed0f). See the [fuzz dependency inventory](docs/licenses.md#fuzz-development-dependencies) for locked revisions and selected licenses.
|
||||
|
||||
llvm-mingw release 20261117 is used as an external build tool for original Windows test programs under Apache-2.0 with LLVM exceptions plus its component licences; nothing from it is shipped or copied (see [hybrid-toolchain](docs/research/hybrid-toolchain.md)). `crates/hybrid/src/memory.rs` is a Rust reimplementation of the memory-guard logic in skakwy's [victory-mac](https://github.com/skakwy/victory-mac) `mac/run-victory.sh` (commit 22b3f8e45a59, GPL-3.0), used with the author's permission.
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "betterxen-hybrid"
|
||||
description = "Host receipt, CrossOver discovery, frame-time statistics and Windows cross-toolchain probes for the hybrid direction"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "betterxen-hybrid"
|
||||
path = "src/main.rs"
|
||||
@@ -0,0 +1,13 @@
|
||||
//! Run a system tool and capture trimmed stdout. A missing tool or non-zero exit is `None`,
|
||||
//! never a guessed value.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
pub fn run(program: &str, args: &[&str]) -> Option<String> {
|
||||
let out = Command::new(program).args(args).output().ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
Some(s)
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Discover installed CrossOver bundles and read standard bundle metadata.
|
||||
//!
|
||||
//! Only documented or standard macOS interfaces are used: the app bundle's `Info.plist`
|
||||
//! (read through `plutil`), `lipo -archs` on the bundle's main executable, and the
|
||||
//! `defaults` keys CodeWeavers documents in "Advanced CrossOver Mac Configuration"
|
||||
//! (`BottleDir`, `ManagedBottleDirs` in `com.codeweavers.CrossOver`). Bundle internals such
|
||||
//! as `Contents/SharedSupport` are NOT interpreted: they are undocumented and not a stable
|
||||
//! interface (#350). The graphics backend of a bottle is deliberately not read.
|
||||
|
||||
use crate::cmdutil::run;
|
||||
use crate::json::Json;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const BUNDLE_ID: &str = "com.codeweavers.CrossOver";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Install {
|
||||
pub path: PathBuf,
|
||||
pub bundle_id: Option<String>,
|
||||
pub short_version: Option<String>,
|
||||
pub build_version: Option<String>,
|
||||
pub executable_archs: Option<Vec<String>>,
|
||||
pub minimum_macos: Option<String>,
|
||||
}
|
||||
|
||||
/// Candidate bundle locations: standard application directories. Spotlight is consulted too.
|
||||
pub fn candidate_paths(home: &Path) -> Vec<PathBuf> {
|
||||
let mut v = vec![
|
||||
PathBuf::from("/Applications/CrossOver.app"),
|
||||
home.join("Applications/CrossOver.app"),
|
||||
];
|
||||
if let Some(found) = run(
|
||||
"/usr/bin/mdfind",
|
||||
&[&format!("kMDItemCFBundleIdentifier == '{BUNDLE_ID}'")],
|
||||
) {
|
||||
for line in found.lines().filter(|l| !l.is_empty()) {
|
||||
let p = PathBuf::from(line);
|
||||
if !v.contains(&p) {
|
||||
v.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
pub fn discover(candidates: &[PathBuf]) -> Vec<Install> {
|
||||
candidates.iter().filter_map(|p| inspect(p)).collect()
|
||||
}
|
||||
|
||||
/// Inspect one bundle. Returns None if the path has no readable `Contents/Info.plist`.
|
||||
pub fn inspect(app: &Path) -> Option<Install> {
|
||||
let plist = app.join("Contents/Info.plist");
|
||||
if !plist.is_file() {
|
||||
return None;
|
||||
}
|
||||
let json = run(
|
||||
"/usr/bin/plutil",
|
||||
&["-convert", "json", "-o", "-", plist.to_str()?],
|
||||
)?;
|
||||
let exe = crate::host_string(&json, "CFBundleExecutable");
|
||||
let archs = exe.and_then(|e| {
|
||||
let p = app.join("Contents/MacOS").join(e);
|
||||
run("/usr/bin/lipo", &["-archs", p.to_str()?])
|
||||
.map(|s| s.split_whitespace().map(String::from).collect())
|
||||
});
|
||||
Some(Install {
|
||||
path: app.to_path_buf(),
|
||||
bundle_id: crate::host_string(&json, "CFBundleIdentifier"),
|
||||
short_version: crate::host_string(&json, "CFBundleShortVersionString"),
|
||||
build_version: crate::host_string(&json, "CFBundleVersion"),
|
||||
executable_archs: archs,
|
||||
minimum_macos: crate::host_string(&json, "LSMinimumSystemVersion"),
|
||||
})
|
||||
}
|
||||
|
||||
/// A documented CrossOver preference, or None when unset or unreadable.
|
||||
pub fn preference(key: &str) -> Option<String> {
|
||||
run("/usr/bin/defaults", &["read", BUNDLE_ID, key])
|
||||
}
|
||||
|
||||
impl Install {
|
||||
pub fn to_json(&self) -> Json {
|
||||
Json::obj(vec![
|
||||
("path", Json::str(self.path.display().to_string())),
|
||||
("bundle_id", Json::opt_str(self.bundle_id.clone())),
|
||||
("short_version", Json::opt_str(self.short_version.clone())),
|
||||
("build_version", Json::opt_str(self.build_version.clone())),
|
||||
(
|
||||
"executable_archs",
|
||||
self.executable_archs.as_ref().map_or(Json::Null, |a| {
|
||||
Json::Arr(a.iter().map(|s| Json::str(s.clone())).collect())
|
||||
}),
|
||||
),
|
||||
("minimum_macos", Json::opt_str(self.minimum_macos.clone())),
|
||||
(
|
||||
"bundle_id_is_codeweavers_crossover",
|
||||
Json::Bool(self.bundle_id.as_deref() == Some(BUNDLE_ID)),
|
||||
),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
// A synthetic bundle written by the test: it proves the metadata path, not that
|
||||
// any real CrossOver build has this layout.
|
||||
fn fake_bundle(dir: &Path) -> PathBuf {
|
||||
let app = dir.join("CrossOver.app");
|
||||
fs::create_dir_all(app.join("Contents/MacOS")).unwrap();
|
||||
fs::write(
|
||||
app.join("Contents/Info.plist"),
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict>
|
||||
<key>CFBundleExecutable</key><string>CrossOver</string>
|
||||
<key>CFBundleIdentifier</key><string>com.codeweavers.CrossOver</string>
|
||||
<key>CFBundleShortVersionString</key><string>99.1.2</string>
|
||||
<key>CFBundleVersion</key><string>12345</string>
|
||||
<key>LSMinimumSystemVersion</key><string>14.0</string>
|
||||
</dict></plist>"#,
|
||||
)
|
||||
.unwrap();
|
||||
// Copy a real system executable so `lipo -archs` has a Mach-O to read.
|
||||
fs::copy("/usr/bin/true", app.join("Contents/MacOS/CrossOver")).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_bundle_metadata() {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return;
|
||||
}
|
||||
let tmp = std::env::temp_dir().join(format!("bxhybrid-co-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&tmp);
|
||||
fs::create_dir_all(&tmp).unwrap();
|
||||
let app = fake_bundle(&tmp);
|
||||
let i = inspect(&app).expect("inspect");
|
||||
assert_eq!(i.short_version.as_deref(), Some("99.1.2"));
|
||||
assert_eq!(i.build_version.as_deref(), Some("12345"));
|
||||
assert_eq!(i.minimum_macos.as_deref(), Some("14.0"));
|
||||
assert_eq!(i.bundle_id.as_deref(), Some(BUNDLE_ID));
|
||||
assert!(
|
||||
i.executable_archs.as_ref().is_some_and(|a| !a.is_empty()),
|
||||
"{:?}",
|
||||
i.executable_archs
|
||||
);
|
||||
assert_eq!(discover(&[app.clone(), tmp.join("Missing.app")]).len(), 1);
|
||||
fs::remove_dir_all(&tmp).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_or_plistless_bundle_is_none() {
|
||||
let tmp = std::env::temp_dir().join(format!("bxhybrid-co2-{}", std::process::id()));
|
||||
fs::create_dir_all(tmp.join("X.app/Contents")).unwrap();
|
||||
assert!(inspect(&tmp.join("X.app")).is_none());
|
||||
assert!(inspect(&tmp.join("Nope.app")).is_none());
|
||||
fs::remove_dir_all(&tmp).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//! Frame-time statistics from a list of frame intervals in milliseconds (issue #145).
|
||||
//!
|
||||
//! Percentiles use the nearest-rank method on the sorted intervals: the p-th percentile is
|
||||
//! the value at rank ceil(p/100 * n) (1-based). "1 % low FPS" is 1000 divided by the 99th
|
||||
//! percentile interval. These definitions are fixed here so reports are comparable; other
|
||||
//! tools define lows differently (for example as the mean of the worst 1 %).
|
||||
|
||||
use crate::json::Json;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct FrameStats {
|
||||
pub frames: usize,
|
||||
pub total_ms: f64,
|
||||
pub mean_ms: f64,
|
||||
pub avg_fps: f64,
|
||||
pub min_ms: f64,
|
||||
pub max_ms: f64,
|
||||
pub p50_ms: f64,
|
||||
pub p95_ms: f64,
|
||||
pub p99_ms: f64,
|
||||
pub p999_ms: f64,
|
||||
pub low_1pct_fps: f64,
|
||||
pub low_01pct_fps: f64,
|
||||
/// Frames longer than twice the median interval.
|
||||
pub stutters: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum FrameError {
|
||||
Empty,
|
||||
Invalid { index: usize, value: f64 },
|
||||
Parse { line: usize, text: String },
|
||||
}
|
||||
|
||||
impl std::fmt::Display for FrameError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
FrameError::Empty => write!(f, "no frame intervals"),
|
||||
FrameError::Invalid { index, value } => {
|
||||
write!(
|
||||
f,
|
||||
"frame {index}: interval {value} is not a positive finite number of milliseconds"
|
||||
)
|
||||
}
|
||||
FrameError::Parse { line, text } => {
|
||||
write!(f, "line {line}: cannot parse {text:?} as milliseconds")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for FrameError {}
|
||||
|
||||
fn nearest_rank(sorted: &[f64], pct: f64) -> f64 {
|
||||
let n = sorted.len();
|
||||
let rank = ((pct / 100.0) * n as f64).ceil().max(1.0) as usize;
|
||||
sorted[rank.min(n) - 1]
|
||||
}
|
||||
|
||||
pub fn analyze(intervals_ms: &[f64]) -> Result<FrameStats, FrameError> {
|
||||
if intervals_ms.is_empty() {
|
||||
return Err(FrameError::Empty);
|
||||
}
|
||||
for (index, &value) in intervals_ms.iter().enumerate() {
|
||||
if !value.is_finite() || value <= 0.0 {
|
||||
return Err(FrameError::Invalid { index, value });
|
||||
}
|
||||
}
|
||||
let mut sorted = intervals_ms.to_vec();
|
||||
sorted.sort_by(|a, b| a.total_cmp(b));
|
||||
let total: f64 = intervals_ms.iter().sum();
|
||||
let n = sorted.len();
|
||||
let p50 = nearest_rank(&sorted, 50.0);
|
||||
let p99 = nearest_rank(&sorted, 99.0);
|
||||
let p999 = nearest_rank(&sorted, 99.9);
|
||||
Ok(FrameStats {
|
||||
frames: n,
|
||||
total_ms: total,
|
||||
mean_ms: total / n as f64,
|
||||
avg_fps: n as f64 / (total / 1000.0),
|
||||
min_ms: sorted[0],
|
||||
max_ms: sorted[n - 1],
|
||||
p50_ms: p50,
|
||||
p95_ms: nearest_rank(&sorted, 95.0),
|
||||
p99_ms: p99,
|
||||
p999_ms: p999,
|
||||
low_1pct_fps: 1000.0 / p99,
|
||||
low_01pct_fps: 1000.0 / p999,
|
||||
stutters: intervals_ms.iter().filter(|&&v| v > 2.0 * p50).count(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse one interval per line; blank lines and lines starting with `#` are skipped.
|
||||
pub fn parse_intervals(text: &str) -> Result<Vec<f64>, FrameError> {
|
||||
let mut out = Vec::new();
|
||||
for (i, line) in text.lines().enumerate() {
|
||||
let t = line.trim();
|
||||
if t.is_empty() || t.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let v: f64 = t.parse().map_err(|_| FrameError::Parse {
|
||||
line: i + 1,
|
||||
text: t.to_string(),
|
||||
})?;
|
||||
out.push(v);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl FrameStats {
|
||||
pub fn to_json(&self) -> Json {
|
||||
Json::obj(vec![
|
||||
("frames", Json::Num(self.frames as f64)),
|
||||
("total_ms", Json::Num(self.total_ms)),
|
||||
("mean_ms", Json::Num(self.mean_ms)),
|
||||
("avg_fps", Json::Num(self.avg_fps)),
|
||||
("min_ms", Json::Num(self.min_ms)),
|
||||
("max_ms", Json::Num(self.max_ms)),
|
||||
("p50_ms", Json::Num(self.p50_ms)),
|
||||
("p95_ms", Json::Num(self.p95_ms)),
|
||||
("p99_ms", Json::Num(self.p99_ms)),
|
||||
("p999_ms", Json::Num(self.p999_ms)),
|
||||
("low_1pct_fps", Json::Num(self.low_1pct_fps)),
|
||||
("low_0_1pct_fps", Json::Num(self.low_01pct_fps)),
|
||||
("stutters_over_2x_median", Json::Num(self.stutters as f64)),
|
||||
("percentile_method", Json::str("nearest-rank")),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Expected values below are worked out by hand, not produced by analyze().
|
||||
#[test]
|
||||
fn known_answer_ten_frames() {
|
||||
// Sorted: 10,10,10,10,10,10,10,10,20,100. Total 200 ms, n = 10.
|
||||
let v = [10.0, 10.0, 10.0, 10.0, 20.0, 10.0, 10.0, 10.0, 100.0, 10.0];
|
||||
let s = analyze(&v).unwrap();
|
||||
assert_eq!(s.frames, 10);
|
||||
assert_eq!(s.total_ms, 200.0);
|
||||
assert_eq!(s.mean_ms, 20.0);
|
||||
assert_eq!(s.avg_fps, 50.0);
|
||||
assert_eq!(s.p50_ms, 10.0); // rank 5
|
||||
assert_eq!(s.p95_ms, 100.0); // rank ceil(9.5) = 10
|
||||
assert_eq!(s.p99_ms, 100.0);
|
||||
assert_eq!(s.low_1pct_fps, 10.0);
|
||||
assert_eq!(s.stutters, 1); // threshold is 2 * 10 = 20; 20 is not > 20, only 100 is.
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stutter_threshold_is_strict() {
|
||||
let s = analyze(&[10.0, 10.0, 10.0, 20.0, 21.0]).unwrap();
|
||||
assert_eq!(s.stutters, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_frame_per_second() {
|
||||
let s = analyze(&[1000.0, 1000.0]).unwrap();
|
||||
assert_eq!(s.avg_fps, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_input() {
|
||||
assert_eq!(analyze(&[]), Err(FrameError::Empty));
|
||||
assert!(matches!(
|
||||
analyze(&[1.0, 0.0]),
|
||||
Err(FrameError::Invalid { index: 1, .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
analyze(&[f64::NAN]),
|
||||
Err(FrameError::Invalid { .. })
|
||||
));
|
||||
assert!(matches!(analyze(&[-3.0]), Err(FrameError::Invalid { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_text() {
|
||||
assert_eq!(
|
||||
parse_intervals("# c\n16.5\n\n 8 \n").unwrap(),
|
||||
vec![16.5, 8.0]
|
||||
);
|
||||
assert_eq!(
|
||||
parse_intervals("1\nabc\n"),
|
||||
Err(FrameError::Parse {
|
||||
line: 2,
|
||||
text: "abc".into()
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
//! Host receipt: what this Mac is, from documented system interfaces (issue #353).
|
||||
//!
|
||||
//! Every field is `Option` where the probe can fail; absence is reported as null, not guessed.
|
||||
|
||||
use crate::cmdutil::run;
|
||||
use crate::json::Json;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct HostReceipt {
|
||||
pub macos_version: Option<String>,
|
||||
pub macos_build: Option<String>,
|
||||
pub chip: Option<String>,
|
||||
pub apple_silicon: Option<bool>,
|
||||
pub memory_bytes: Option<u64>,
|
||||
pub logical_cpus: Option<u32>,
|
||||
pub performance_cores: Option<u32>,
|
||||
pub efficiency_cores: Option<u32>,
|
||||
/// True only if an x86_64 slice of a system binary actually executed.
|
||||
pub rosetta_executes_x86_64: Option<bool>,
|
||||
pub gpu_name: Option<String>,
|
||||
pub gpu_cores: Option<String>,
|
||||
pub metal_support: Option<String>,
|
||||
pub host_arch_of_this_binary: &'static str,
|
||||
}
|
||||
|
||||
fn sysctl(name: &str) -> Option<String> {
|
||||
run("/usr/sbin/sysctl", &["-n", name])
|
||||
}
|
||||
|
||||
pub fn collect() -> HostReceipt {
|
||||
let gpu = run(
|
||||
"/usr/sbin/system_profiler",
|
||||
&["SPDisplaysDataType", "-json"],
|
||||
)
|
||||
.and_then(|j| parse_gpu(&j));
|
||||
HostReceipt {
|
||||
macos_version: run("/usr/bin/sw_vers", &["-productVersion"]),
|
||||
macos_build: sysctl("kern.osversion"),
|
||||
chip: sysctl("machdep.cpu.brand_string"),
|
||||
apple_silicon: sysctl("hw.optional.arm64").map(|v| v == "1"),
|
||||
memory_bytes: sysctl("hw.memsize").and_then(|v| v.parse().ok()),
|
||||
logical_cpus: sysctl("hw.logicalcpu").and_then(|v| v.parse().ok()),
|
||||
performance_cores: sysctl("hw.perflevel0.physicalcpu").and_then(|v| v.parse().ok()),
|
||||
efficiency_cores: sysctl("hw.perflevel1.physicalcpu").and_then(|v| v.parse().ok()),
|
||||
// Executes the x86_64 slice of /usr/bin/true. Failure means Rosetta cannot run it
|
||||
// now; it does not distinguish "not installed" from "disabled".
|
||||
rosetta_executes_x86_64: Some(
|
||||
run("/usr/bin/arch", &["-x86_64", "/usr/bin/true"]).is_some(),
|
||||
),
|
||||
gpu_name: gpu.as_ref().map(|g| g.0.clone()),
|
||||
gpu_cores: gpu.as_ref().and_then(|g| g.1.clone()),
|
||||
metal_support: gpu.as_ref().and_then(|g| g.2.clone()),
|
||||
host_arch_of_this_binary: std::env::consts::ARCH,
|
||||
}
|
||||
}
|
||||
|
||||
/// Pull `sppci_model`, `sppci_cores` and `spdisplays_mtlgpufamilysupport` of the first display
|
||||
/// entry from `system_profiler SPDisplaysDataType -json` output. Returns None if the model
|
||||
/// key is absent. Uses a small string scan because this crate has no JSON parser dependency.
|
||||
pub fn parse_gpu(json: &str) -> Option<(String, Option<String>, Option<String>)> {
|
||||
let model = string_value(json, "sppci_model")?;
|
||||
Some((
|
||||
model,
|
||||
string_value(json, "sppci_cores"),
|
||||
string_value(json, "spdisplays_mtlgpufamilysupport"),
|
||||
))
|
||||
}
|
||||
|
||||
fn string_value(json: &str, key: &str) -> Option<String> {
|
||||
let needle = format!("\"{key}\"");
|
||||
let at = json.find(&needle)? + needle.len();
|
||||
let rest = json[at..].trim_start().strip_prefix(':')?.trim_start();
|
||||
let rest = rest.strip_prefix('"')?;
|
||||
let end = rest.find('"')?;
|
||||
Some(rest[..end].to_string())
|
||||
}
|
||||
|
||||
impl HostReceipt {
|
||||
pub fn to_json(&self) -> Json {
|
||||
let n = |v: Option<u32>| v.map_or(Json::Null, |x| Json::Num(x as f64));
|
||||
Json::obj(vec![
|
||||
("macos_version", Json::opt_str(self.macos_version.clone())),
|
||||
("macos_build", Json::opt_str(self.macos_build.clone())),
|
||||
("chip", Json::opt_str(self.chip.clone())),
|
||||
(
|
||||
"apple_silicon",
|
||||
self.apple_silicon.map_or(Json::Null, Json::Bool),
|
||||
),
|
||||
(
|
||||
"memory_bytes",
|
||||
self.memory_bytes
|
||||
.map_or(Json::Null, |x| Json::Num(x as f64)),
|
||||
),
|
||||
("logical_cpus", n(self.logical_cpus)),
|
||||
("performance_cores", n(self.performance_cores)),
|
||||
("efficiency_cores", n(self.efficiency_cores)),
|
||||
(
|
||||
"rosetta_executes_x86_64",
|
||||
self.rosetta_executes_x86_64.map_or(Json::Null, Json::Bool),
|
||||
),
|
||||
("gpu_name", Json::opt_str(self.gpu_name.clone())),
|
||||
("gpu_cores", Json::opt_str(self.gpu_cores.clone())),
|
||||
("metal_support", Json::opt_str(self.metal_support.clone())),
|
||||
(
|
||||
"receipt_binary_arch",
|
||||
Json::str(self.host_arch_of_this_binary),
|
||||
),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_gpu_fixture() {
|
||||
let j = r#"{"SPDisplaysDataType":[{"sppci_cores":"10","sppci_model":"Apple M4",
|
||||
"spdisplays_mtlgpufamilysupport":"spdisplays_metal4"}]}"#;
|
||||
let g = parse_gpu(j).unwrap();
|
||||
assert_eq!(g.0, "Apple M4");
|
||||
assert_eq!(g.1.as_deref(), Some("10"));
|
||||
assert_eq!(g.2.as_deref(), Some("spdisplays_metal4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_gpu_is_none() {
|
||||
assert!(parse_gpu("{}").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_runs_on_this_host() {
|
||||
let r = collect();
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(r.macos_version.is_some());
|
||||
assert!(r.memory_bytes.unwrap() > 0);
|
||||
}
|
||||
assert!(r.to_json().render().contains("receipt_binary_arch"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Minimal JSON value and writer. Output only; no parsing is needed by this crate.
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Json {
|
||||
Null,
|
||||
Bool(bool),
|
||||
Num(f64),
|
||||
Str(String),
|
||||
Arr(Vec<Json>),
|
||||
Obj(Vec<(String, Json)>),
|
||||
}
|
||||
|
||||
impl Json {
|
||||
pub fn str(s: impl Into<String>) -> Json {
|
||||
Json::Str(s.into())
|
||||
}
|
||||
pub fn opt_str(s: Option<String>) -> Json {
|
||||
s.map_or(Json::Null, Json::Str)
|
||||
}
|
||||
pub fn obj(fields: Vec<(&str, Json)>) -> Json {
|
||||
Json::Obj(
|
||||
fields
|
||||
.into_iter()
|
||||
.map(|(k, v)| (k.to_string(), v))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn render(&self) -> String {
|
||||
let mut out = String::new();
|
||||
self.write(&mut out, 0);
|
||||
out.push('\n');
|
||||
out
|
||||
}
|
||||
|
||||
fn write(&self, out: &mut String, depth: usize) {
|
||||
let pad = |out: &mut String, d: usize| out.push_str(&" ".repeat(d));
|
||||
match self {
|
||||
Json::Null => out.push_str("null"),
|
||||
Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
|
||||
Json::Num(n) if n.is_finite() => {
|
||||
if n.fract() == 0.0 && n.abs() < 1e15 {
|
||||
out.push_str(&format!("{}", *n as i64));
|
||||
} else {
|
||||
out.push_str(&format!("{n}"));
|
||||
}
|
||||
}
|
||||
// JSON has no NaN or infinity; refuse to invent a number.
|
||||
Json::Num(_) => out.push_str("null"),
|
||||
Json::Str(s) => escape(s, out),
|
||||
Json::Arr(items) if items.is_empty() => out.push_str("[]"),
|
||||
Json::Arr(items) => {
|
||||
out.push_str("[\n");
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
pad(out, depth + 1);
|
||||
item.write(out, depth + 1);
|
||||
out.push_str(if i + 1 < items.len() { ",\n" } else { "\n" });
|
||||
}
|
||||
pad(out, depth);
|
||||
out.push(']');
|
||||
}
|
||||
Json::Obj(fields) if fields.is_empty() => out.push_str("{}"),
|
||||
Json::Obj(fields) => {
|
||||
out.push_str("{\n");
|
||||
for (i, (k, v)) in fields.iter().enumerate() {
|
||||
pad(out, depth + 1);
|
||||
escape(k, out);
|
||||
out.push_str(": ");
|
||||
v.write(out, depth + 1);
|
||||
out.push_str(if i + 1 < fields.len() { ",\n" } else { "\n" });
|
||||
}
|
||||
pad(out, depth);
|
||||
out.push('}');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn escape(s: &str, out: &mut String) {
|
||||
out.push('"');
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn escapes_and_nests() {
|
||||
let j = Json::obj(vec![
|
||||
("a", Json::str("q\"\\\n\u{1}")),
|
||||
(
|
||||
"b",
|
||||
Json::Arr(vec![Json::Num(1.0), Json::Num(0.5), Json::Null]),
|
||||
),
|
||||
("c", Json::Num(f64::NAN)),
|
||||
]);
|
||||
let r = j.render();
|
||||
assert!(r.contains(r#""a": "q\"\\\n\u0001""#), "{r}");
|
||||
assert!(r.contains("0.5"));
|
||||
assert!(r.contains(r#""c": null"#));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
//! 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 records;
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
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] [--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 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")?,
|
||||
"--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,
|
||||
},
|
||||
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, kind: &str, j: &Json) -> Result<(), String> {
|
||||
betterxen_hybrid::records::save(dir, kind, j)
|
||||
.map(|path| eprintln!("report saved: {}", path.display()))
|
||||
.map_err(|error| format!("cannot save {kind} report in {}: {error}", dir.display()))
|
||||
}
|
||||
|
||||
fn finish_report(passed: bool, out: Option<&std::path::Path>, kind: &str, j: &Json) -> ExitCode {
|
||||
print!("{}", j.render());
|
||||
if let Some(dir) = out
|
||||
&& let Err(error) = save(dir, kind, j)
|
||||
{
|
||||
eprintln!("{error}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
if passed {
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
|
||||
fn run_cmd(args: &[String]) -> ExitCode {
|
||||
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());
|
||||
finish_report(
|
||||
r.class == run::Class::Passed,
|
||||
a.out.as_deref(),
|
||||
"run",
|
||||
&r.json,
|
||||
)
|
||||
}
|
||||
|
||||
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)),
|
||||
]);
|
||||
finish_report(all_ok, a.out.as_deref(), "bench", &doc)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod report_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn requested_evidence_failure_overrides_a_passing_workload() {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"bx-report-invalid-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
std::fs::write(&path, "keep this file").unwrap();
|
||||
for kind in ["run", "bench"] {
|
||||
assert_eq!(
|
||||
finish_report(true, Some(&path), kind, &Json::Null),
|
||||
ExitCode::from(1)
|
||||
);
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "keep this file");
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdout_only_reporting_preserves_workload_status() {
|
||||
assert_eq!(
|
||||
finish_report(true, None, "run", &Json::Null),
|
||||
ExitCode::SUCCESS
|
||||
);
|
||||
assert_eq!(
|
||||
finish_report(false, None, "bench", &Json::Null),
|
||||
ExitCode::from(1)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
//! Memory-pressure supervision of a child process.
|
||||
//!
|
||||
//! Adapted in concept from the memory guard in `mac/run-victory.sh` of
|
||||
//! <https://github.com/skakwy/victory-mac> (author skakwy, GPL-3.0; commit 22b3f8e, used with
|
||||
//! the author's permission): do not start a workload when little memory is free, and stop it
|
||||
//! when system-wide free memory falls below a limit, because GPU memory is wired under
|
||||
//! unified memory and a runaway workload can take the whole Mac down. This version is
|
||||
//! reimplemented in Rust, stops the child with SIGTERM before SIGKILL, and reports why it
|
||||
//! stopped. It supervises any command; it contains nothing game-specific.
|
||||
//!
|
||||
//! The reading is the "System-wide memory free percentage" line of `memory_pressure -Q`.
|
||||
//! That line was observed on macOS 27.0 (build 26A428); its format is not a documented
|
||||
//! stable interface, so an unreadable value is an error, never "assume enough memory".
|
||||
|
||||
use crate::cmdutil::run;
|
||||
use std::process::{Child, Command};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub fn parse_free_percentage(output: &str) -> Option<u8> {
|
||||
let line = output
|
||||
.lines()
|
||||
.find(|l| l.contains("System-wide memory free percentage"))?;
|
||||
let digits: String = line
|
||||
.split(':')
|
||||
.nth(1)?
|
||||
.trim()
|
||||
.chars()
|
||||
.take_while(|c| c.is_ascii_digit())
|
||||
.collect();
|
||||
let v: u8 = digits.parse().ok()?;
|
||||
(v <= 100).then_some(v)
|
||||
}
|
||||
|
||||
pub fn free_percentage() -> Option<u8> {
|
||||
run("/usr/bin/memory_pressure", &["-Q"]).and_then(|o| parse_free_percentage(&o))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Limits {
|
||||
/// Refuse to start below this percent free.
|
||||
pub min_start_free: u8,
|
||||
/// Stop the child when free memory drops below this percent.
|
||||
pub min_free: u8,
|
||||
pub poll: Duration,
|
||||
/// Time between SIGTERM and SIGKILL.
|
||||
pub grace: Duration,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Outcome {
|
||||
/// The child ran to completion; `None` means it ended by a signal.
|
||||
Exited(Option<i32>),
|
||||
RefusedToStart {
|
||||
free: u8,
|
||||
need: u8,
|
||||
},
|
||||
StoppedLowMemory {
|
||||
free: u8,
|
||||
limit: u8,
|
||||
},
|
||||
/// Memory could not be read, so no guarantee can be given.
|
||||
MemoryUnreadable,
|
||||
SpawnFailed(String),
|
||||
}
|
||||
|
||||
pub(crate) fn terminate(child: &mut Child, grace: Duration) {
|
||||
let _ = Command::new("/bin/kill")
|
||||
.args(["-TERM", &child.id().to_string()])
|
||||
.status();
|
||||
let t0 = Instant::now();
|
||||
while t0.elapsed() < grace {
|
||||
if matches!(child.try_wait(), Ok(Some(_))) {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
/// Run `program` under `limits`, reading memory through `read_free`.
|
||||
pub fn supervise(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
limits: Limits,
|
||||
read_free: &mut dyn FnMut() -> Option<u8>,
|
||||
) -> Outcome {
|
||||
match read_free() {
|
||||
None => return Outcome::MemoryUnreadable,
|
||||
Some(free) if free < limits.min_start_free => {
|
||||
return Outcome::RefusedToStart {
|
||||
free,
|
||||
need: limits.min_start_free,
|
||||
};
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
let mut child = match Command::new(program).args(args).spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => return Outcome::SpawnFailed(format!("{program}: {e}")),
|
||||
};
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => return Outcome::Exited(status.code()),
|
||||
Ok(None) => {}
|
||||
Err(e) => return Outcome::SpawnFailed(e.to_string()),
|
||||
}
|
||||
match read_free() {
|
||||
None => {
|
||||
terminate(&mut child, limits.grace);
|
||||
return Outcome::MemoryUnreadable;
|
||||
}
|
||||
Some(free) if free < limits.min_free => {
|
||||
terminate(&mut child, limits.grace);
|
||||
return Outcome::StoppedLowMemory {
|
||||
free,
|
||||
limit: limits.min_free,
|
||||
};
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
std::thread::sleep(limits.poll);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn limits() -> Limits {
|
||||
Limits {
|
||||
min_start_free: 50,
|
||||
min_free: 20,
|
||||
poll: Duration::from_millis(20),
|
||||
grace: Duration::from_millis(500),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_memory_pressure_output() {
|
||||
let real = "The system has 25769803776 (1572864 pages with a page size of 16384).\nSystem-wide memory free percentage: 71%\n";
|
||||
assert_eq!(parse_free_percentage(real), Some(71));
|
||||
assert_eq!(
|
||||
parse_free_percentage("System-wide memory free percentage: 100%"),
|
||||
Some(100)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_free_percentage("System-wide memory free percentage: 101%"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
parse_free_percentage("System-wide memory free percentage: x"),
|
||||
None
|
||||
);
|
||||
assert_eq!(parse_free_percentage("nothing"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_to_start_when_low() {
|
||||
let out = supervise("/usr/bin/true", &[], limits(), &mut || Some(30));
|
||||
assert_eq!(out, Outcome::RefusedToStart { free: 30, need: 50 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_memory_is_an_error() {
|
||||
assert_eq!(
|
||||
supervise("/usr/bin/true", &[], limits(), &mut || None),
|
||||
Outcome::MemoryUnreadable
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn child_exit_code_is_reported() {
|
||||
let out = supervise(
|
||||
"/bin/sh",
|
||||
&["-c".into(), "exit 7".into()],
|
||||
limits(),
|
||||
&mut || Some(90),
|
||||
);
|
||||
assert_eq!(out, Outcome::Exited(Some(7)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stops_child_when_memory_drops() {
|
||||
let mut calls = 0;
|
||||
let t0 = Instant::now();
|
||||
let out = supervise("/bin/sleep", &["30".into()], limits(), &mut || {
|
||||
calls += 1;
|
||||
Some(if calls < 4 { 90 } else { 10 })
|
||||
});
|
||||
assert_eq!(
|
||||
out,
|
||||
Outcome::StoppedLowMemory {
|
||||
free: 10,
|
||||
limit: 20
|
||||
}
|
||||
);
|
||||
assert!(
|
||||
t0.elapsed() < Duration::from_secs(10),
|
||||
"child was not stopped promptly"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_reading_is_available_on_macos() {
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(free_percentage().is_some());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Exclusive report creation: previous evidence is never replaced.
|
||||
|
||||
use crate::json::Json;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Save a run or benchmark report under a unique name, reporting all I/O errors.
|
||||
pub fn save(dir: &Path, kind: &str, report: &Json) -> io::Result<PathBuf> {
|
||||
if !matches!(kind, "run" | "bench") {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"unknown report kind",
|
||||
));
|
||||
}
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let nanos = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(io::Error::other)?
|
||||
.as_nanos();
|
||||
let bytes = report.render();
|
||||
loop {
|
||||
let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed);
|
||||
let path = dir.join(format!(
|
||||
"{kind}-{nanos}-{}-{sequence}.json",
|
||||
std::process::id()
|
||||
));
|
||||
match write_new(&path, bytes.as_bytes(), |file, bytes| file.write_all(bytes)) {
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(e),
|
||||
Ok(()) => return Ok(path),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_new(
|
||||
path: &Path,
|
||||
bytes: &[u8],
|
||||
write: impl FnOnce(&mut File, &[u8]) -> io::Result<()>,
|
||||
) -> io::Result<()> {
|
||||
let mut file = OpenOptions::new().write(true).create_new(true).open(path)?;
|
||||
if let Err(error) = write(&mut file, bytes).and_then(|()| file.sync_all()) {
|
||||
drop(file);
|
||||
// Remove only the incomplete file this call exclusively created.
|
||||
return match std::fs::remove_file(path) {
|
||||
Ok(()) => Err(error),
|
||||
Err(cleanup) => Err(io::Error::new(
|
||||
error.kind(),
|
||||
format!(
|
||||
"{error}; cannot remove incomplete report {}: {cleanup}",
|
||||
path.display()
|
||||
),
|
||||
)),
|
||||
};
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn directory() -> PathBuf {
|
||||
let id = SEQUENCE.fetch_add(1, Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("bx-records-{}-{id}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_run_and_bench_reports_preserve_prior_evidence() {
|
||||
let dir = directory();
|
||||
std::fs::write(dir.join("bench.json"), "previous evidence").unwrap();
|
||||
let first = save(&dir, "run", &Json::str("first")).unwrap();
|
||||
let second = save(&dir, "run", &Json::str("second")).unwrap();
|
||||
let bench1 = save(&dir, "bench", &Json::str("bench one")).unwrap();
|
||||
let bench2 = save(&dir, "bench", &Json::str("bench two")).unwrap();
|
||||
assert_ne!(first, second);
|
||||
assert_ne!(bench1, bench2);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(first).unwrap(),
|
||||
Json::str("first").render()
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(second).unwrap(),
|
||||
Json::str("second").render()
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(bench1).unwrap(),
|
||||
Json::str("bench one").render()
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(bench2).unwrap(),
|
||||
Json::str("bench two").render()
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.join("bench.json")).unwrap(),
|
||||
"previous evidence"
|
||||
);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_destination_is_never_truncated() {
|
||||
let dir = directory();
|
||||
let path = dir.join("record.json");
|
||||
std::fs::write(&path, "original").unwrap();
|
||||
let error =
|
||||
write_new(&path, b"replacement", |file, bytes| file.write_all(bytes)).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "original");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_directory_is_an_error() {
|
||||
let dir = directory();
|
||||
let path = dir.join("not-a-directory");
|
||||
std::fs::write(&path, "original").unwrap();
|
||||
assert!(save(&path, "run", &Json::Null).is_err());
|
||||
assert_eq!(std::fs::read_to_string(path).unwrap(), "original");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_write_failure_is_reported_and_incomplete_file_removed() {
|
||||
let dir = directory();
|
||||
let path = dir.join("record.json");
|
||||
let error = write_new(&path, b"a complete report", |file, _| {
|
||||
file.write_all(b"partial")?;
|
||||
Err(io::Error::other("injected write failure"))
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("injected write failure"));
|
||||
assert!(!path.exists());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
//! 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
|
||||
//! 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,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Class {
|
||||
Passed,
|
||||
FailedExit(i32),
|
||||
MissingExpectedMarker,
|
||||
TimedOut,
|
||||
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::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 thermal_before = thermal();
|
||||
let free_start = memory::free_percentage();
|
||||
|
||||
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;
|
||||
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 memory::free_percentage() {
|
||||
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),
|
||||
}
|
||||
if stop.is_none() && started.elapsed() > cfg.timeout {
|
||||
stop = Some(Class::TimedOut);
|
||||
}
|
||||
if stop.is_some() {
|
||||
memory::terminate(&mut child, cfg.limits.grace);
|
||||
if let Some(dir) = cfg.wine.parent() {
|
||||
let _ = Command::new(dir.join("wineserver"))
|
||||
.arg("-k")
|
||||
.env("CX_BOTTLE", &cfg.bottle)
|
||||
.status();
|
||||
}
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(cfg.limits.poll);
|
||||
}
|
||||
result.duration = started.elapsed();
|
||||
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())),
|
||||
(
|
||||
"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
|
||||
}
|
||||
|
||||
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())),
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
//! Probe Windows cross-compilers for original test programs (issue #364).
|
||||
//!
|
||||
//! Reports what is installed and what each compiler targets; it does not install anything.
|
||||
|
||||
use crate::cmdutil::run;
|
||||
use crate::json::Json;
|
||||
|
||||
/// (name, kind). Order is the discovery order only, not a preference.
|
||||
pub const CANDIDATES: &[&str] = &[
|
||||
"aarch64-w64-mingw32-clang",
|
||||
"x86_64-w64-mingw32-clang",
|
||||
"x86_64-w64-mingw32-gcc",
|
||||
"i686-w64-mingw32-gcc",
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Compiler {
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
pub version_line: Option<String>,
|
||||
pub target_machine: Option<String>,
|
||||
}
|
||||
|
||||
pub fn probe(search_path: &str) -> Vec<Compiler> {
|
||||
CANDIDATES
|
||||
.iter()
|
||||
.filter_map(|name| {
|
||||
let path = search_path
|
||||
.split(':')
|
||||
.map(|d| std::path::Path::new(d).join(name))
|
||||
.find(|p| p.is_file())?;
|
||||
let p = path.to_str()?.to_string();
|
||||
Some(Compiler {
|
||||
name: name.to_string(),
|
||||
version_line: run(&p, &["--version"])
|
||||
.and_then(|s| s.lines().next().map(String::from)),
|
||||
target_machine: run(&p, &["-dumpmachine"]),
|
||||
path: p,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl Compiler {
|
||||
pub fn to_json(&self) -> Json {
|
||||
Json::obj(vec![
|
||||
("name", Json::str(self.name.clone())),
|
||||
("path", Json::str(self.path.clone())),
|
||||
("version", Json::opt_str(self.version_line.clone())),
|
||||
("target_machine", Json::opt_str(self.target_machine.clone())),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn empty_path_finds_nothing() {
|
||||
assert!(probe("").is_empty());
|
||||
assert!(probe("/nonexistent-dir").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_a_stub_compiler_and_reports_its_output() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = std::env::temp_dir().join(format!("bxhybrid-tc-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let f = dir.join("x86_64-w64-mingw32-gcc");
|
||||
std::fs::write(&f, "#!/bin/sh\nif [ \"$1\" = -dumpmachine ]; then echo x86_64-w64-mingw32; else echo stub 1.0; fi\n").unwrap();
|
||||
std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let found = probe(dir.to_str().unwrap());
|
||||
assert_eq!(found.len(), 1);
|
||||
assert_eq!(
|
||||
found[0].target_machine.as_deref(),
|
||||
Some("x86_64-w64-mingw32")
|
||||
);
|
||||
assert_eq!(found[0].version_line.as_deref(), Some("stub 1.0"));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,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`.
|
||||
- [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.
|
||||
- [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.
|
||||
|
||||
@@ -12,6 +12,7 @@ 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 |
|
||||
| Xcode and Metal tools | Xcode 27.2 | Apple proprietary terms | External host tools, not distributed |
|
||||
|
||||
## Runtime redistribution review
|
||||
|
||||
@@ -18,5 +18,14 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
|
||||
| x86-64 decode and ARM64 translation, runtime, gfx1030 compiler, Metal backend | BetterXen native implementation | **Preserved, paused** | Reuse only where hybrid needs it and it shows a demonstrated advantage; not forced into the architecture. |
|
||||
| Test and diagnostics methodology | BetterXen existing audits, benchmark harness, claims registry | **Reuse** | Existing evidence classes, claims audit and benchmark gating apply to hybrid work (Phase 1 onward). |
|
||||
| Configuration, diagnostics, benchmarking around CrossOver | BetterXen | **Build** (Phase 2, provisional) | Only after Phase 1 shows what CrossOver does not already provide (#351). |
|
||||
| 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.
|
||||
@@ -0,0 +1,69 @@
|
||||
# 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.
|
||||
|
||||
## Saving new baseline evidence
|
||||
|
||||
The runner now writes `run-<nanoseconds>-<pid>-<sequence>.json` and
|
||||
`bench-<nanoseconds>-<pid>-<sequence>.json` when `--out` is supplied. Exclusive
|
||||
creation preserves existing reports, including older `bench.json` files. The
|
||||
selected path is printed to stderr; stdout retains the workload classification
|
||||
and report JSON. A directory, creation or write error returns a nonzero CLI
|
||||
status even if the workload itself passed. These persistence changes do not
|
||||
revalidate or replace the historical results above.
|
||||
@@ -0,0 +1,36 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,98 @@
|
||||
# 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.
|
||||
@@ -27,6 +27,21 @@ 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.
|
||||
|
||||
Executable
+50
@@ -0,0 +1,50 @@
|
||||
#!/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
|
||||
@@ -0,0 +1,71 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original BetterXen workload (issue #365, first step): Direct3D 11 clear and readback.
|
||||
// Creates a hardware device, clears a 64x64 RGBA8 render target to (0.25, 0.5, 0.75, 1.0),
|
||||
// copies it to a staging texture, maps it, and checks every pixel. Expected bytes by the ideal
|
||||
// FLOAT->UNORM rule (c*255, add 0.5, drop the fraction): 64, 128, 191, 255. The Direct3D data
|
||||
// conversion rules also permit a tolerance of 0.6 unit-last-place on the integer side
|
||||
// (D3D11/D3D12_FLOAT32_TO_INTEGER_TOLERANCE_IN_ULP = 0.6f), so a byte passes when it is
|
||||
// within 0.6 of c*255. 0.5*255 = 127.5 is an exact tie, so both 127 and 128 are permitted.
|
||||
// The program prints whether the result matched the ideal exactly. This corrects an earlier
|
||||
// version that required exact equality, which was stricter than the specification.
|
||||
// Exit codes: 0 pass, 1 wrong pixel, 2 no device (reported, not a pass), 3 other API failure.
|
||||
#define COBJMACROS
|
||||
#include <d3d11.h>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
// `--negative-control` expects a deliberately wrong colour; the program must then exit 1.
|
||||
int main(int argc, char **argv) {
|
||||
const int negative = argc > 1 && !strcmp(argv[1], "--negative-control");
|
||||
ID3D11Device *dev = NULL;
|
||||
ID3D11DeviceContext *ctx = NULL;
|
||||
D3D_FEATURE_LEVEL got;
|
||||
HRESULT hr = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, NULL, 0,
|
||||
D3D11_SDK_VERSION, &dev, &got, &ctx);
|
||||
if (FAILED(hr)) { printf("NO DEVICE hr=0x%08lx\n", (unsigned long)hr); return 2; }
|
||||
printf("device ok feature_level=0x%x\n", (unsigned)got);
|
||||
|
||||
D3D11_TEXTURE2D_DESC d = {0};
|
||||
d.Width = 64; d.Height = 64; d.MipLevels = 1; d.ArraySize = 1;
|
||||
d.Format = DXGI_FORMAT_R8G8B8A8_UNORM; d.SampleDesc.Count = 1;
|
||||
d.Usage = D3D11_USAGE_DEFAULT; d.BindFlags = D3D11_BIND_RENDER_TARGET;
|
||||
ID3D11Texture2D *rt = NULL, *st = NULL;
|
||||
if (FAILED(ID3D11Device_CreateTexture2D(dev, &d, NULL, &rt))) { printf("FAIL create rt\n"); return 3; }
|
||||
d.Usage = D3D11_USAGE_STAGING; d.BindFlags = 0; d.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
|
||||
if (FAILED(ID3D11Device_CreateTexture2D(dev, &d, NULL, &st))) { printf("FAIL create staging\n"); return 3; }
|
||||
ID3D11RenderTargetView *rtv = NULL;
|
||||
if (FAILED(ID3D11Device_CreateRenderTargetView(dev, (ID3D11Resource *)rt, NULL, &rtv))) {
|
||||
printf("FAIL create rtv\n"); return 3;
|
||||
}
|
||||
const float color[4] = {0.25f, 0.5f, 0.75f, 1.0f};
|
||||
ID3D11DeviceContext_ClearRenderTargetView(ctx, rtv, color);
|
||||
ID3D11DeviceContext_CopyResource(ctx, (ID3D11Resource *)st, (ID3D11Resource *)rt);
|
||||
D3D11_MAPPED_SUBRESOURCE m;
|
||||
if (FAILED(ID3D11DeviceContext_Map(ctx, (ID3D11Resource *)st, 0, D3D11_MAP_READ, 0, &m))) {
|
||||
printf("FAIL map\n"); return 3;
|
||||
}
|
||||
const unsigned char ideal[4] = {64, 128, 191, 255};
|
||||
const float tol = 0.6f;
|
||||
int bad = 0, inexact = 0;
|
||||
for (UINT y = 0; y < 64; y++) {
|
||||
const unsigned char *row = (const unsigned char *)m.pData + (size_t)y * m.RowPitch;
|
||||
for (UINT x = 0; x < 64; x++) {
|
||||
const unsigned char *p = row + x * 4;
|
||||
int off_ideal = 0, off_tol = 0;
|
||||
for (int ch = 0; ch < 4; ch++) {
|
||||
if (p[ch] != ideal[ch] + (negative ? 100 : 0)) off_ideal = 1;
|
||||
if (fabsf(color[ch] * 255.0f + (negative ? 100.0f : 0.0f) - (float)p[ch]) > tol) off_tol = 1;
|
||||
}
|
||||
if (off_ideal) inexact++;
|
||||
if (off_tol) {
|
||||
if (bad < 3) printf("pixel (%u,%u) = %u %u %u %u\n", x, y, p[0], p[1], p[2], p[3]);
|
||||
bad++;
|
||||
}
|
||||
}
|
||||
}
|
||||
ID3D11DeviceContext_Unmap(ctx, (ID3D11Resource *)st, 0);
|
||||
if (bad) { printf("FAIL %d wrong pixels\n", bad); return 1; }
|
||||
printf("PASS 4096 pixels within tolerance; %d differ from the ideal rounding\n", inexact);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// 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 <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;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
#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;
|
||||
}
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "win-selfcheck-rust"
|
||||
version = "0.1.0"
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "win-selfcheck-rust"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "GPL-3.0-or-later"
|
||||
publish = false
|
||||
|
||||
# Standalone: built for a Windows target by scripts/hybrid/build-windows-workloads.sh, not a
|
||||
# member of the BetterXen workspace.
|
||||
[workspace]
|
||||
@@ -0,0 +1,44 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original BetterXen workload (issue #364): a Rust Windows console program that checks itself.
|
||||
// Exercises thread-local storage and threads, which the contributor notes in
|
||||
// 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");
|
||||
}
|
||||
Reference in new issue
Block a user