mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 20:10:44 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7d7249ee8b | ||
|
|
d0395a61da |
No files matched your search
@@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
- `bx-cli run` gained `--timeout <secs>`, cleanup of the launcher process group and the selected bottle or prefix on timeout, SIGINT, SIGTERM or SIGHUP, `--backend` (bottle mode only), and a printed trace summary after a run with `--log`. The bottle to stop is located through CrossOver itself, so bottles outside the default directory are covered. A normal exit does not stop the environment. Recorded a one-host observation that D3D12 swapchains stay referenced under D3DMetal (#408).
|
||||
- Added file-mapping-backed 64 KiB and 2 MiB physical pages, contiguous and scatter aliases (including intra-span duplicate-tag aliasing), exact-span unmap validation, physical region queries (`bx_xmem_query_region`), and shared working-set accounting / combined title memory budget enforcement across heap, virtual, and physical allocations in `xmem.dll`. Synthetic `XMemAllocatePhysicalPages` / `XMemFreePhysicalPages` signatures follow Win32 AWE (`memoryapi.h`) pending a public console flag encoding (#412).
|
||||
- Added Win32 bridge conformance coverage for a hidden window, message dispatch, concurrent PSM registrations, and per-event JSONL log verification. Offline PSM registration tokens are tracked without C++ exceptions using disjoint family tags so cross-family unregisters log `foreign_token` and retired or invalid tokens log `unknown_token` (#410).
|
||||
- Implemented synthetic APU heap mappings, per-connection APU and DSP queues, and the GameInput ordinal 1 COM stub. Added an audio/input conformance executable covering all four shim DLLs (#419).
|
||||
@@ -71,6 +72,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
|
||||
- Fixed `bx-cli run --bottle` losing the shim DLL overrides: CrossOver's `bin/wine` discards `WINEDLLOVERRIDES`, so they are now passed with `--dll` (found by jelly013) (#408).
|
||||
- `test_integration_boot.exe` now creates a real texture address computer, checks a two-mip layout against hand-computed values and requires the final `Release` to return 0, instead of reporting that stage as pending after a null-descriptor probe (#446).
|
||||
- `bx-cli trace` reports the highest sampled CLWB total as a lower bound, labels counterless CLWB records as samples, and lists unhandled exceptions with their code, module base, RVA, and RIP (#438).
|
||||
- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed.
|
||||
|
||||
Generated
+7
@@ -9,6 +9,7 @@ dependencies = [
|
||||
"bx-probe",
|
||||
"bx-telemetry",
|
||||
"dxbc-accc",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -29,3 +30,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "dxbc-accc"
|
||||
version = "0.2.0"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) currently has **zero external crates.io dependencies** and is original `GPL-3.0-or-later` source.
|
||||
|
||||
`bx-cli` links the unmodified `libc` 0.2.191 crate (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX process groups and signals, under its MIT option. Preserve the Rust Project Developers notice and permission text.
|
||||
|
||||
## External Host Tools & Runtime Dependencies (Never Bundled)
|
||||
|
||||
| Component | Role | Licensing & Provenance |
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
|
||||
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
|
||||
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
|
||||
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — One-host observation to check before M2 presentation work.
|
||||
- [Public Technical References](research/sources.md), [Xbox GDK Notes](research/xbox-gdk.md), [RDNA 2 Notes](research/rdna2.md), and [Shader Containers](research/shader-containers.md) — Public specification references for shim and shader work.
|
||||
|
||||
## Governance, Security & Legal
|
||||
|
||||
@@ -20,5 +20,6 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
|
||||
| x86-64 decode and ARM64 translation, runtime, gfx1030 compiler, Metal backend | BetterXen native implementation | **Preserved, paused** | Reuse only where hybrid needs it and it shows a demonstrated advantage; not forced into the architecture. |
|
||||
| Test and diagnostics methodology | BetterXen existing audits, benchmark harness, claims registry | **Reuse** | Existing evidence classes, claims audit and benchmark gating apply to hybrid work (Phase 1 onward). |
|
||||
| Configuration, diagnostics, benchmarking around CrossOver | BetterXen | **Build** (Phase 2, provisional) | Only after Phase 1 shows what CrossOver does not already provide (#351). |
|
||||
| Process groups and signals for `bx-cli run` | rust-lang/libc 0.2.191 (MIT) | **Reuse** | Unmodified crates.io dependency (#408). |
|
||||
|
||||
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,20 @@
|
||||
# D3D12 swapchain references under D3DMetal
|
||||
|
||||
An observation to check before M2 builds presentation on `IDXGISwapChain3`. One Apple M4,
|
||||
macOS 27, CrossOver 26.3.0 (26.3.0.39832), 2026-11-26. Not independently reproduced, and not an
|
||||
Xbox hardware result.
|
||||
|
||||
| | D3DMetal | Wine `vkd3d` path |
|
||||
| --- | --- | --- |
|
||||
| References on the swapchain right after creation | 2 | 1 |
|
||||
| Count returned by the application's final `Release` | 1 | 0 |
|
||||
| Swapchains still referenced after 12 create/release cycles | 12 | 0 |
|
||||
|
||||
The same program was used for both, and it submitted no GPU work of its own. Under D3DMetal
|
||||
each retained swapchain also kept a device reference. The cause inside D3DMetal is unknown. A
|
||||
program that recreates swapchains (for example on resize) should be expected to grow until this
|
||||
is explained.
|
||||
|
||||
The probe is
|
||||
[`lifetime.c` at `7c512af`](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d12_lifetime/lifetime.c)
|
||||
on the branch of #425; it is not part of this branch. Tracked in #450.
|
||||
@@ -14,6 +14,7 @@ Reviewed 2026-11-25. Every entry is **evidence class D** (non-normative official
|
||||
| VIctory | [Marvisak/VIctory](https://github.com/Marvisak/VIctory) | `13f91caee25f` | GPL-3.0 (GitHub); a prior local review found per-file notices (see `experiments/victory-native/licenses.md`, local, untracked) | Discovery reference only | Described as an attempt at running one commercial game on PC. Its inputs are an Xbox Series build of that game. PortWatch describes the efforts it tracks as targeting a "leaked Xbox Series build". |
|
||||
| VIctory-macOS | [pragyaangaur/VIctory-macOS](https://github.com/pragyaangaur/VIctory-macOS) | `485b230ef596` | GPL-3.0 (GitHub) | Discovery reference only | A macOS port of VIctory using Rosetta, CrossOver Wine and D3DMetal per its README (also noted in retired `portwatch-native-macos.md` at tag `native-first-final`). Same input concern. Its test and "works" claims are self-reported and not verified here. The repository has no parent fork, so the "canonical upstream" is VIctory. |
|
||||
| PortWatch VI | [portwatch-vi.xyz](https://portwatch-vi.xyz/), [4lwayz/portwatch-vi](https://github.com/4lwayz/portwatch-vi) | `ed00263cc0c9` | NOASSERTION | Project discovery reference | A tracker of community efforts; progress figures are editorial, with self-reported claims labelled. Not engineering evidence; flagged and ignored queues are not endorsed. |
|
||||
| libc | [rust-lang/libc](https://github.com/rust-lang/libc) | `0.2.191` (`ccc2ff4aaab9`) | MIT OR Apache-2.0 (used under MIT) | `bx-cli` process groups and signals (#408) | Unmodified crates.io dependency, locked checksum. |
|
||||
|
||||
## Built and run for M1-D2 (#417)
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ path = "src/main.rs"
|
||||
bx-probe = { path = "../bx-probe" }
|
||||
bx-telemetry = { path = "../bx-telemetry" }
|
||||
dxbc-accc = { path = "../../../shader-transpiler/crates/dxbc-accc" }
|
||||
# POSIX signals and process groups for `run` supervision.
|
||||
libc = "=0.2.191"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,20 +1,28 @@
|
||||
//! Track A (M1-A1): Native ARM64 macOS CLI for BetterXen hybrid execution.
|
||||
|
||||
mod supervise;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::env;
|
||||
use std::fmt::Write as _;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitCode};
|
||||
use std::time::Duration;
|
||||
|
||||
use bx_probe::{ShimTrack, classify_dll, probe_pe32_plus};
|
||||
use bx_telemetry::summarize_jsonl;
|
||||
use dxbc_accc::inspect_dxbc;
|
||||
use supervise::{Outcome, Stop};
|
||||
|
||||
const SHIM_DLL_OVERRIDES: &str = "bx_runtime_veh,d3d12_xs,xg_xs,xmem,XCRDAPI,xgameruntime,AcpHal,xapu,chad,GameInput,\
|
||||
api-ms-win-core-psm-appnotify-l1-1-0,api-ms-win-core-psm-appnotify-l1-1-1,\
|
||||
ext-ms-win-rtcore-ntuser-message-l1-1-0,ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0,\
|
||||
ext-ms-win-rtcore-ntuser-window-l1-1-0,ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0=n,b";
|
||||
|
||||
/// Accepted `--backend` values. CrossOver ignores an unknown value silently, so one is refused.
|
||||
const BACKENDS: [&str; 4] = ["d3dmetal", "dxmt", "dxvk", "wined3d"];
|
||||
|
||||
const SAFE_CHILD_PATH: &str = "/usr/bin:/bin:/usr/sbin:/sbin";
|
||||
|
||||
const HOST_ENV_ALLOWLIST: &[&str] = &[
|
||||
@@ -39,7 +47,8 @@ fn print_usage() {
|
||||
bx-cli probe <pe32+_path> Classify PE32+ imports by BetterXen track (A-E)\n\
|
||||
bx-cli shader <dxbc_blob_path> Classify a DXBC shader container (DXIL vs ACCC/FSPX)\n\
|
||||
bx-cli trace <log.jsonl> Summarize bx_runtime_veh JSONL diagnostics\n\
|
||||
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env]\n"
|
||||
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env] [--timeout <secs>] [--backend d3dmetal|dxmt|dxvk|wined3d (needs --bottle)]\n\
|
||||
(shims default to build-shims/bin; a timeout or signal stops the whole bottle or prefix)\n"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -171,20 +180,29 @@ fn cmd_trace(path: &str) -> ExitCode {
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let summary = summarize_jsonl(&text);
|
||||
println!("Trace events : {}", summary.total_lines);
|
||||
println!(
|
||||
print!("{}", render_trace(&text));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn render_trace(text: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let summary = summarize_jsonl(text);
|
||||
let _ = writeln!(out, "Trace events : {}", summary.total_lines);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{}",
|
||||
format_clwb_line(summary.clwb_events, summary.clwb_trap_lower_bound)
|
||||
);
|
||||
println!("ADX illegal ops : {}", summary.adx_errors);
|
||||
let _ = writeln!(out, "ADX illegal ops : {}", summary.adx_errors);
|
||||
if !summary.unhandled_exceptions.is_empty() {
|
||||
println!(
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nUnhandled exceptions ({}):",
|
||||
summary.unhandled_exceptions.len()
|
||||
);
|
||||
for crash in summary.unhandled_exceptions {
|
||||
println!(
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" code={} module_base={} + RVA={} RIP={}",
|
||||
crash.exception_code.as_deref().unwrap_or("unknown"),
|
||||
crash.module_base.as_deref().unwrap_or("unknown"),
|
||||
@@ -194,18 +212,18 @@ fn cmd_trace(path: &str) -> ExitCode {
|
||||
}
|
||||
}
|
||||
if !summary.unimpl_apis.is_empty() {
|
||||
println!("\nUnimplemented APIs:");
|
||||
let _ = writeln!(out, "\nUnimplemented APIs:");
|
||||
for (api, count) in summary.unimpl_apis {
|
||||
println!(" {count:5}x {api}");
|
||||
let _ = writeln!(out, " {count:5}x {api}");
|
||||
}
|
||||
}
|
||||
if !summary.unimpl_vtables.is_empty() {
|
||||
println!("\nUnimplemented COM vtable slots:");
|
||||
let _ = writeln!(out, "\nUnimplemented COM vtable slots:");
|
||||
for (slot, count) in summary.unimpl_vtables {
|
||||
println!(" {count:5}x {slot}");
|
||||
let _ = writeln!(out, " {count:5}x {slot}");
|
||||
}
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
out
|
||||
}
|
||||
|
||||
fn unix_to_wine_z_path(path: &Path) -> String {
|
||||
@@ -227,7 +245,20 @@ where
|
||||
env_map
|
||||
}
|
||||
|
||||
fn cmd_run(args: &[String]) -> ExitCode {
|
||||
#[derive(Debug)]
|
||||
struct RunArgs {
|
||||
exe: PathBuf,
|
||||
shims_dir: PathBuf,
|
||||
profile: String,
|
||||
bottle: Option<String>,
|
||||
prefix: Option<PathBuf>,
|
||||
log: Option<PathBuf>,
|
||||
inherit_env: bool,
|
||||
timeout: Option<Duration>,
|
||||
backend: Option<String>,
|
||||
}
|
||||
|
||||
fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
|
||||
let mut exe_path: Option<PathBuf> = None;
|
||||
let mut shims_dir = PathBuf::from("build-shims/bin");
|
||||
let mut profile = String::from("lockhart");
|
||||
@@ -235,6 +266,8 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
let mut wine_prefix: Option<PathBuf> = None;
|
||||
let mut log_file: Option<PathBuf> = None;
|
||||
let mut inherit_env = false;
|
||||
let mut timeout = None;
|
||||
let mut backend: Option<String> = None;
|
||||
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
@@ -263,21 +296,132 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
log_file = Some(PathBuf::from(&args[i + 1]));
|
||||
i += 2;
|
||||
}
|
||||
"--timeout" if i + 1 < args.len() => {
|
||||
let seconds: u64 = args[i + 1]
|
||||
.parse()
|
||||
.ok()
|
||||
.filter(|s| *s > 0)
|
||||
.ok_or("--timeout needs a whole number of seconds above 0")?;
|
||||
timeout = Some(Duration::from_secs(seconds));
|
||||
i += 2;
|
||||
}
|
||||
"--backend" if i + 1 < args.len() => {
|
||||
let name = args[i + 1].clone();
|
||||
if !BACKENDS.contains(&name.as_str()) {
|
||||
return Err(format!(
|
||||
"unknown backend {name:?}; use one of {}",
|
||||
BACKENDS.join(", ")
|
||||
));
|
||||
}
|
||||
backend = Some(name);
|
||||
i += 2;
|
||||
}
|
||||
"--inherit-env" => {
|
||||
inherit_env = true;
|
||||
i += 1;
|
||||
}
|
||||
other => {
|
||||
eprintln!("unknown argument: {other}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
other => return Err(format!("unknown argument: {other}")),
|
||||
}
|
||||
}
|
||||
|
||||
let Some(exe) = exe_path else {
|
||||
eprintln!("error: --exe <path> is required");
|
||||
return ExitCode::FAILURE;
|
||||
if let Some(name) = &bottle
|
||||
&& (name.is_empty() || name.starts_with(['-', '.']) || name.contains('/'))
|
||||
{
|
||||
return Err(format!("invalid bottle name {name:?}"));
|
||||
}
|
||||
if backend.is_some() && bottle.is_none() {
|
||||
// A bare prefix loads Wine's own D3D12 whatever CX_GRAPHICS_BACKEND says (observed on
|
||||
// CrossOver 26.3), so accepting it would claim a backend that is not in use.
|
||||
return Err("--backend needs --bottle; a bare prefix cannot be made to use it".into());
|
||||
}
|
||||
Ok(RunArgs {
|
||||
exe: exe_path.ok_or("error: --exe <path> is required")?,
|
||||
shims_dir,
|
||||
profile,
|
||||
bottle,
|
||||
prefix: wine_prefix,
|
||||
log: log_file,
|
||||
inherit_env,
|
||||
timeout,
|
||||
backend,
|
||||
})
|
||||
}
|
||||
|
||||
/// Asks CrossOver's installed `CXBottle` module where `--bottle` points, so cleanup targets the
|
||||
/// prefix the launch uses. `bin/wine` searches `CX_BOTTLE_PATH`, configured paths and managed
|
||||
/// bottles, so a fixed directory would be wrong for some bottles.
|
||||
const BOTTLE_PREFIX_QUERY: &str = r#"
|
||||
use lib "$ENV{CX_ROOT}/lib/perl";
|
||||
require CXBottle;
|
||||
CXBottle::get_crossover_config();
|
||||
my ($scope, $found) = CXBottle::setup_bottle_wineprefix(undef);
|
||||
die "$@\n" unless defined $scope;
|
||||
print $ENV{WINEPREFIX};
|
||||
"#;
|
||||
|
||||
/// The environment `bin/wine` starts from, shared by the launch and the bottle lookup.
|
||||
fn apply_host_env(command: &mut Command, inherit_env: bool) {
|
||||
if !inherit_env {
|
||||
command.env_clear();
|
||||
for (k, v) in collect_isolated_host_env(|k| env::var(k).ok()) {
|
||||
command.env(k, v);
|
||||
}
|
||||
}
|
||||
// Inherited values must not point the launcher at a different bottle than cleanup does.
|
||||
command.env_remove("WINEPREFIX").env_remove("CX_BOTTLE");
|
||||
}
|
||||
|
||||
fn resolve_bottle_prefix(
|
||||
cx_root: &Path,
|
||||
mut command: Command,
|
||||
name: &str,
|
||||
) -> Result<PathBuf, String> {
|
||||
let output = command
|
||||
.env("CX_ROOT", cx_root)
|
||||
.env("CX_BOTTLE", name)
|
||||
.args(["-e", BOTTLE_PREFIX_QUERY])
|
||||
.output()
|
||||
.map_err(|e| format!("cannot ask CrossOver where bottle {name:?} is: {e}"))?;
|
||||
let path = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
|
||||
if !output.status.success() || !path.is_absolute() || !path.is_dir() {
|
||||
return Err(format!(
|
||||
"CrossOver cannot locate bottle {name:?}: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// `bin/wine` deletes an inherited `WINEDLLOVERRIDES` and applies the bottle's
|
||||
/// `[EnvironmentVariables]` over what it is given, so bottle mode passes both as options.
|
||||
fn bottle_options(backend: Option<&str>) -> Vec<String> {
|
||||
let mut options = vec!["--dll".to_string(), SHIM_DLL_OVERRIDES.to_string()];
|
||||
if let Some(backend) = backend {
|
||||
options.push("--env".to_string());
|
||||
options.push(format!("CX_GRAPHICS_BACKEND={backend}"));
|
||||
}
|
||||
options
|
||||
}
|
||||
|
||||
fn cmd_run(args: &[String]) -> ExitCode {
|
||||
let run = match parse_run_args(args) {
|
||||
Ok(run) => run,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let RunArgs {
|
||||
exe,
|
||||
shims_dir,
|
||||
profile,
|
||||
bottle,
|
||||
prefix: wine_prefix,
|
||||
log: log_file,
|
||||
inherit_env,
|
||||
timeout,
|
||||
backend,
|
||||
} = run;
|
||||
|
||||
let cx_root = Path::new("/Applications/CrossOver.app/Contents/SharedSupport/CrossOver");
|
||||
let wine_wrapper = cx_root.join("bin/wine");
|
||||
@@ -294,9 +438,27 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
let resolved_prefix =
|
||||
wine_prefix.unwrap_or_else(|| PathBuf::from("/tmp/betterxen-wine-prefix"));
|
||||
|
||||
// The environment a timeout or signal has to stop.
|
||||
let environment_dir = match &bottle {
|
||||
Some(name) => {
|
||||
let mut query = Command::new("/usr/bin/perl");
|
||||
apply_host_env(&mut query, inherit_env);
|
||||
match resolve_bottle_prefix(cx_root, query, name) {
|
||||
Ok(path) => path,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
None => resolved_prefix.clone(),
|
||||
};
|
||||
|
||||
let mut cmd = if let Some(ref bname) = bottle {
|
||||
let mut c = Command::new(&wine_wrapper);
|
||||
c.args(["--bottle", bname]).arg(&abs_exe);
|
||||
c.args(["--bottle", bname])
|
||||
.args(bottle_options(backend.as_deref()))
|
||||
.arg(&abs_exe);
|
||||
c
|
||||
} else {
|
||||
let _ = fs::create_dir_all(&resolved_prefix);
|
||||
@@ -305,12 +467,7 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
c
|
||||
};
|
||||
|
||||
if !inherit_env {
|
||||
cmd.env_clear();
|
||||
for (k, v) in collect_isolated_host_env(|k| env::var(k).ok()) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
}
|
||||
apply_host_env(&mut cmd, inherit_env);
|
||||
|
||||
if bottle.is_none() {
|
||||
cmd.env("WINEPREFIX", &resolved_prefix)
|
||||
@@ -340,26 +497,69 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
.env("BX_PROFILE", &profile)
|
||||
.env("WINEDEBUG", "-all");
|
||||
|
||||
if let Some(ref lf) = log_file {
|
||||
let abs_log = if lf.is_absolute() {
|
||||
lf.clone()
|
||||
let abs_log = log_file.map(|lf| {
|
||||
if lf.is_absolute() {
|
||||
lf
|
||||
} else {
|
||||
env::current_dir().unwrap_or_default().join(lf)
|
||||
};
|
||||
cmd.env("BX_LOG_FILE", unix_to_wine_z_path(&abs_log));
|
||||
}
|
||||
});
|
||||
if let Some(log) = &abs_log {
|
||||
cmd.env("BX_LOG_FILE", unix_to_wine_z_path(log));
|
||||
}
|
||||
let log_size = |log: &PathBuf| fs::metadata(log).map_or(0, |m| m.len());
|
||||
let log_size_before = abs_log.as_ref().map_or(0, log_size);
|
||||
|
||||
supervise::install_signal_handlers();
|
||||
let outcome = supervise::supervise(cmd, timeout, supervise::received_signal);
|
||||
let code = match &outcome {
|
||||
Ok(outcome) => outcome.exit_code(),
|
||||
Err(e) => {
|
||||
eprintln!("failed to run CrossOver wine: {e}");
|
||||
1
|
||||
}
|
||||
};
|
||||
let mut cleanup_failed = false;
|
||||
match &outcome {
|
||||
Ok(Outcome::Exited(status)) if !status.success() => {
|
||||
eprintln!("guest exited with status: {status}");
|
||||
}
|
||||
Ok(Outcome::Stopped(stop)) => {
|
||||
match stop {
|
||||
Stop::TimedOut => eprintln!("timed out; stopping the environment"),
|
||||
Stop::Signalled(signal) => {
|
||||
eprintln!("received signal {signal}; stopping the environment");
|
||||
}
|
||||
}
|
||||
let server_env: Vec<(String, String)> = collect_isolated_host_env(|k| env::var(k).ok())
|
||||
.into_iter()
|
||||
.collect();
|
||||
if let Err(e) = supervise::stop_server(
|
||||
&cx_root.join("bin/wineserver"),
|
||||
&environment_dir,
|
||||
&server_env,
|
||||
) {
|
||||
eprintln!("cleanup failed, programs may still be running: {e}");
|
||||
cleanup_failed = true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
match cmd.status() {
|
||||
Ok(st) if st.success() => ExitCode::SUCCESS,
|
||||
Ok(st) => {
|
||||
eprintln!("guest exited with status: {st}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("failed to launch CrossOver wine: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
// Printed for failed and stopped runs too, which is when it matters most.
|
||||
if let Some(log) = &abs_log
|
||||
&& log_size(log) > log_size_before
|
||||
&& let Ok(bytes) = fs::read(log)
|
||||
{
|
||||
// Guest text may not be valid UTF-8; a summary is still worth printing.
|
||||
print!(
|
||||
"\nTrace summary of {}:\n{}",
|
||||
log.display(),
|
||||
render_trace(&String::from_utf8_lossy(&bytes))
|
||||
);
|
||||
}
|
||||
// The reason for the stop is kept; a failed cleanup only turns success into failure.
|
||||
ExitCode::from(if cleanup_failed { code.max(1) } else { code })
|
||||
}
|
||||
|
||||
fn cmd_shader(path: &str) -> ExitCode {
|
||||
@@ -416,6 +616,110 @@ fn main() -> ExitCode {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn args(list: &[&str]) -> Vec<String> {
|
||||
list.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_run_arguments() {
|
||||
for bare in [&["--prefix", "/tmp/p"][..], &[]] {
|
||||
let mut list = args(&["--exe", "a.exe", "--backend", "d3dmetal"]);
|
||||
list.extend(args(bare));
|
||||
let error = parse_run_args(&list).unwrap_err();
|
||||
assert!(error.contains("--backend needs --bottle"), "{error}");
|
||||
}
|
||||
let run = parse_run_args(&args(&[
|
||||
"--exe",
|
||||
"a.exe",
|
||||
"--bottle",
|
||||
"b",
|
||||
"--timeout",
|
||||
"30",
|
||||
"--backend",
|
||||
"d3dmetal",
|
||||
]))
|
||||
.unwrap();
|
||||
assert_eq!(run.timeout, Some(Duration::from_secs(30)));
|
||||
assert_eq!(run.backend.as_deref(), Some("d3dmetal"));
|
||||
assert_eq!(run.shims_dir, PathBuf::from("build-shims/bin"));
|
||||
assert_eq!(run.profile, "lockhart");
|
||||
let plain = parse_run_args(&args(&["--exe", "a.exe"])).unwrap();
|
||||
assert!(plain.timeout.is_none() && plain.bottle.is_none() && plain.prefix.is_none());
|
||||
for bad in [
|
||||
&["--exe", "a.exe", "--timeout", "0"][..],
|
||||
&["--exe", "a.exe", "--timeout", "soon"],
|
||||
&["--exe", "a.exe", "--backend", "dmxt2"],
|
||||
&["--exe", "a.exe", "--bottle", "../x"],
|
||||
&["--exe", "a.exe", "--timeout"],
|
||||
&["--bottle", "b"],
|
||||
] {
|
||||
assert!(parse_run_args(&args(bad)).is_err(), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
// A stub CXBottle stands in for CrossOver's: this checks the lookup's environment and that
|
||||
// a timeout's cleanup is aimed at the prefix it returns, not at the default directory.
|
||||
#[test]
|
||||
fn a_timeout_cleans_up_a_bottle_outside_the_default_directory() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let root = env::temp_dir().join(format!("bx-cli-altbottle-{}", std::process::id()));
|
||||
let bottle = root.join("elsewhere/mine");
|
||||
fs::create_dir_all(&bottle).unwrap();
|
||||
fs::create_dir_all(root.join("cx/lib/perl")).unwrap();
|
||||
fs::write(
|
||||
root.join("cx/lib/perl/CXBottle.pm"),
|
||||
r#"package CXBottle;
|
||||
sub get_crossover_config {}
|
||||
sub setup_bottle_wineprefix {
|
||||
my $p = "$ENV{CX_BOTTLE_PATH}/$ENV{CX_BOTTLE}";
|
||||
return (undef, undef) unless -d $p;
|
||||
$ENV{WINEPREFIX} = $p;
|
||||
return ('private', $p);
|
||||
}
|
||||
1;
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let query = |name: &str| {
|
||||
let mut command = Command::new("/usr/bin/perl");
|
||||
command.env("CX_BOTTLE_PATH", root.join("elsewhere"));
|
||||
resolve_bottle_prefix(&root.join("cx"), command, name)
|
||||
};
|
||||
assert!(query("absent").is_err());
|
||||
let prefix = query("mine").unwrap();
|
||||
assert_eq!(prefix, bottle);
|
||||
|
||||
let server = root.join("wineserver");
|
||||
let seen = root.join("seen");
|
||||
fs::write(
|
||||
&server,
|
||||
format!(
|
||||
"#!/bin/sh\necho \"$1 $WINEPREFIX\" >> '{}'\n",
|
||||
seen.display()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&server, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let mut sleeper = Command::new("/bin/sh");
|
||||
sleeper.args(["-c", "sleep 30"]);
|
||||
let outcome =
|
||||
supervise::supervise(sleeper, Some(Duration::from_millis(200)), || 0).unwrap();
|
||||
assert!(matches!(outcome, Outcome::Stopped(Stop::TimedOut)));
|
||||
supervise::stop_server(&server, &prefix, &[]).unwrap();
|
||||
let expected = format!("-k {0}\n-w {0}\n", bottle.display());
|
||||
assert_eq!(fs::read_to_string(&seen).unwrap(), expected);
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bottle_mode_passes_overrides_and_backend_as_launcher_options() {
|
||||
assert_eq!(bottle_options(None), ["--dll", SHIM_DLL_OVERRIDES]);
|
||||
assert_eq!(
|
||||
bottle_options(Some("dxvk"))[2..],
|
||||
["--env", "CX_GRAPHICS_BACKEND=dxvk"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isolated_env_strips_secrets_and_pins_path() {
|
||||
let host = BTreeMap::from([
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
//! Supervision for `bx-cli run` (#408): the launcher gets its own process group, and a timeout
|
||||
//! or signal stops that group and then the environment's `wineserver`.
|
||||
//!
|
||||
//! The `wineserver` is stopped only after a timeout or signal, never after a normal exit,
|
||||
//! because it ends every program in that bottle or prefix, not only this run's.
|
||||
|
||||
use std::io::IsTerminal;
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::path::Path;
|
||||
use std::process::{Child, Command, ExitStatus, Stdio};
|
||||
use std::sync::atomic::{AtomicI32, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const POLL: Duration = Duration::from_millis(50);
|
||||
/// How long the launcher group has to exit after SIGTERM before SIGKILL.
|
||||
const GRACE: Duration = Duration::from_secs(5);
|
||||
const SERVER_WAIT: Duration = Duration::from_secs(15);
|
||||
|
||||
static SIGNAL: AtomicI32 = AtomicI32::new(0);
|
||||
|
||||
extern "C" fn note_signal(signal: libc::c_int) {
|
||||
SIGNAL.store(signal, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Records SIGINT, SIGTERM and SIGHUP instead of dying, so the run can be cleaned up.
|
||||
pub fn install_signal_handlers() {
|
||||
for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] {
|
||||
// SAFETY: the handler only stores to an atomic, which is async-signal-safe.
|
||||
unsafe {
|
||||
libc::signal(
|
||||
signal,
|
||||
note_signal as extern "C" fn(libc::c_int) as libc::sighandler_t,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn received_signal() -> i32 {
|
||||
SIGNAL.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum Stop {
|
||||
TimedOut,
|
||||
Signalled(i32),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Outcome {
|
||||
Exited(ExitStatus),
|
||||
Stopped(Stop),
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
/// 0 or 1 for the guest's own result, 124 for a timeout (as `timeout(1)`), 128 + N for a
|
||||
/// signal.
|
||||
pub fn exit_code(&self) -> u8 {
|
||||
match self {
|
||||
Outcome::Exited(status) => u8::from(!status.success()),
|
||||
Outcome::Stopped(Stop::TimedOut) => 124,
|
||||
Outcome::Stopped(Stop::Signalled(signal)) => 128u8.saturating_add(*signal as u8),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn signal_group(child: &Child, signal: libc::c_int) {
|
||||
// SAFETY: kill takes no pointers. The child leads its own group and has not been reaped,
|
||||
// so the group id cannot have been reused.
|
||||
unsafe {
|
||||
libc::kill(-(child.id() as libc::pid_t), signal);
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_until(child: &mut Child, deadline: Instant) -> std::io::Result<Option<ExitStatus>> {
|
||||
loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
return Ok(Some(status));
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Ok(None);
|
||||
}
|
||||
std::thread::sleep(POLL);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `command` in a new process group until it exits, `timeout` passes, or `signal`
|
||||
/// returns non-zero. On a stop the whole group is terminated before this returns.
|
||||
pub fn supervise(
|
||||
mut command: Command,
|
||||
timeout: Option<Duration>,
|
||||
signal: impl Fn() -> i32,
|
||||
) -> std::io::Result<Outcome> {
|
||||
// A background process group is stopped by SIGTTIN if it reads the terminal, so a terminal
|
||||
// is replaced by end-of-file. Piped and redirected input is passed through.
|
||||
if std::io::stdin().is_terminal() {
|
||||
command.stdin(Stdio::null());
|
||||
}
|
||||
let mut child = command.process_group(0).spawn()?;
|
||||
let started = Instant::now();
|
||||
let stop = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
return Ok(Outcome::Exited(status));
|
||||
}
|
||||
let received = signal();
|
||||
if received != 0 {
|
||||
break Stop::Signalled(received);
|
||||
}
|
||||
if timeout.is_some_and(|limit| started.elapsed() >= limit) {
|
||||
break Stop::TimedOut;
|
||||
}
|
||||
std::thread::sleep(POLL);
|
||||
};
|
||||
signal_group(&child, libc::SIGTERM);
|
||||
// Wait without reaping first, so SIGKILL still reaches members that outlive the leader.
|
||||
std::thread::sleep(POLL);
|
||||
let deadline = Instant::now() + GRACE;
|
||||
while Instant::now() < deadline && group_leader_running(&child) {
|
||||
std::thread::sleep(POLL);
|
||||
}
|
||||
signal_group(&child, libc::SIGKILL);
|
||||
wait_until(&mut child, Instant::now() + GRACE)?;
|
||||
Ok(Outcome::Stopped(stop))
|
||||
}
|
||||
|
||||
/// True while the leader has not exited; does not reap it.
|
||||
fn group_leader_running(child: &Child) -> bool {
|
||||
// SAFETY: `info` is a valid, writable siginfo_t and WNOWAIT leaves the child unreaped.
|
||||
unsafe {
|
||||
let mut info: libc::siginfo_t = std::mem::zeroed();
|
||||
libc::waitid(
|
||||
libc::P_PID,
|
||||
child.id() as libc::id_t,
|
||||
&mut info,
|
||||
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
|
||||
) == 0
|
||||
&& info.si_pid() == 0
|
||||
}
|
||||
}
|
||||
|
||||
/// `wineserver -k` then `-w` for the environment at `prefix`.
|
||||
///
|
||||
/// `-k` exits 1 when no server is running (observed on CrossOver 26.3), so 1 is accepted
|
||||
/// there; `-w` must still succeed, which a surviving server prevents.
|
||||
pub fn stop_server(
|
||||
wineserver: &Path,
|
||||
prefix: &Path,
|
||||
environment: &[(String, String)],
|
||||
) -> Result<(), String> {
|
||||
for (flag, idle_code) in [("-k", Some(1)), ("-w", None)] {
|
||||
let mut child = Command::new(wineserver)
|
||||
.arg(flag)
|
||||
.env_clear()
|
||||
.envs(environment.iter().map(|(k, v)| (k, v)))
|
||||
.env("WINEPREFIX", prefix)
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.map_err(|e| format!("cannot start wineserver {flag}: {e}"))?;
|
||||
match wait_until(&mut child, Instant::now() + SERVER_WAIT) {
|
||||
Ok(Some(status)) if status.success() => {}
|
||||
Ok(Some(status)) if idle_code.is_some() && status.code() == idle_code => {}
|
||||
other => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(format!("wineserver {flag} did not succeed: {other:?}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
fn shell(script: &str) -> Command {
|
||||
let mut command = Command::new("/bin/sh");
|
||||
command.args(["-c", script]);
|
||||
command
|
||||
}
|
||||
|
||||
fn scratch(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("bx-cli-{name}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_exit_timeout_and_signal() {
|
||||
let ok = supervise(shell("exit 0"), None, || 0).unwrap();
|
||||
assert_eq!(ok.exit_code(), 0);
|
||||
let failed = supervise(shell("exit 7"), Some(Duration::from_secs(10)), || 0).unwrap();
|
||||
assert_eq!(failed.exit_code(), 1);
|
||||
let slow = supervise(shell("sleep 30"), Some(Duration::from_millis(200)), || 0).unwrap();
|
||||
assert!(matches!(slow, Outcome::Stopped(Stop::TimedOut)));
|
||||
assert_eq!(slow.exit_code(), 124);
|
||||
let interrupted = supervise(shell("sleep 30"), None, || libc::SIGTERM).unwrap();
|
||||
assert_eq!(interrupted.exit_code(), 128 + libc::SIGTERM as u8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timeout_stops_children_that_ignore_sigterm() {
|
||||
let dir = scratch("group");
|
||||
let pid_file = dir.join("child.pid");
|
||||
let script = format!(
|
||||
"(trap '' TERM; exec sleep 30) & echo $! > '{}'; wait",
|
||||
pid_file.display()
|
||||
);
|
||||
supervise(shell(&script), Some(Duration::from_millis(500)), || 0).unwrap();
|
||||
let pid: libc::pid_t = std::fs::read_to_string(&pid_file)
|
||||
.unwrap()
|
||||
.trim()
|
||||
.parse()
|
||||
.unwrap();
|
||||
let gone = (0..100).any(|_| {
|
||||
std::thread::sleep(POLL);
|
||||
// SAFETY: signal 0 only checks whether the process exists.
|
||||
unsafe { libc::kill(pid, 0) != 0 }
|
||||
});
|
||||
assert!(gone, "grandchild {pid} survived the timeout");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_idle_server_is_accepted_only_when_the_wait_succeeds() {
|
||||
let dir = scratch("server");
|
||||
for (name, kill, wait, ok) in [
|
||||
("running", 0, 0, true),
|
||||
("idle", 1, 0, true),
|
||||
("stuck", 1, 1, false),
|
||||
("broken", 2, 0, false),
|
||||
] {
|
||||
let server = dir.join(name);
|
||||
std::fs::write(
|
||||
&server,
|
||||
format!("#!/bin/sh\n[ \"$1\" = -k ] && exit {kill}\nexit {wait}\n"),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert_eq!(stop_server(&server, &dir, &[]).is_ok(), ok, "{name}");
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user