mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 17:30:43 +00:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7d7249ee8b | ||
|
|
d0395a61da | ||
|
|
eec56dd028 | ||
|
|
486f7b197f | ||
|
|
390e85fc8d | ||
|
|
bfa80dee8b | ||
|
|
829a94fa2f | ||
|
|
02b8924de7 | ||
|
|
925311e852 | ||
|
|
f7194d0255 | ||
|
|
7ea4f1f6ca | ||
|
|
bd8edd8f70 | ||
|
|
a8c4dbb77e | ||
|
|
cee636193a | ||
|
|
ab696f1f07 |
No files matched your search
@@ -10,6 +10,9 @@ 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).
|
||||
- Added structured unhandled exception logging with module-relative addresses and x64 registers, and expanded the CLWB conformance test to require six traps across ModRM, SIB, REX and RIP-relative operands (#409).
|
||||
- Enforced the configured title memory cap for default heap allocations and virtual commits in `xmem.dll`. Added working-set accounting and a synthetic fixture for alignment, commit overlap, decommit, release, and memory transfer (#411).
|
||||
@@ -69,6 +72,9 @@ 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.
|
||||
- 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
+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"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -153,6 +162,16 @@ fn cmd_probe(path: &str) -> ExitCode {
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn format_clwb_line(clwb_events: usize, clwb_trap_lower_bound: Option<u64>) -> String {
|
||||
if let Some(lower_bound) = clwb_trap_lower_bound {
|
||||
format!("clwb VEH traps : at least {lower_bound} (sampled)")
|
||||
} else if clwb_events == 0 {
|
||||
"clwb VEH traps : 0".to_string()
|
||||
} else {
|
||||
format!("clwb VEH samples : {clwb_events}")
|
||||
}
|
||||
}
|
||||
|
||||
fn cmd_trace(path: &str) -> ExitCode {
|
||||
let text = match fs::read_to_string(path) {
|
||||
Ok(s) => s,
|
||||
@@ -161,23 +180,50 @@ fn cmd_trace(path: &str) -> ExitCode {
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let summary = summarize_jsonl(&text);
|
||||
println!("Trace events : {}", summary.total_lines);
|
||||
println!("clwb VEH traps : {}", summary.clwb_events);
|
||||
println!("ADX illegal ops : {}", summary.adx_errors);
|
||||
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)
|
||||
);
|
||||
let _ = writeln!(out, "ADX illegal ops : {}", summary.adx_errors);
|
||||
if !summary.unhandled_exceptions.is_empty() {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nUnhandled exceptions ({}):",
|
||||
summary.unhandled_exceptions.len()
|
||||
);
|
||||
for crash in summary.unhandled_exceptions {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" code={} module_base={} + RVA={} RIP={}",
|
||||
crash.exception_code.as_deref().unwrap_or("unknown"),
|
||||
crash.module_base.as_deref().unwrap_or("unknown"),
|
||||
crash.rva.as_deref().unwrap_or("unknown"),
|
||||
crash.rip.as_deref().unwrap_or("unknown"),
|
||||
);
|
||||
}
|
||||
}
|
||||
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 {
|
||||
@@ -199,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");
|
||||
@@ -207,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() {
|
||||
@@ -235,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");
|
||||
@@ -266,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);
|
||||
@@ -277,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)
|
||||
@@ -312,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 {
|
||||
@@ -388,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([
|
||||
@@ -414,4 +746,14 @@ mod tests {
|
||||
"Z:\\tmp\\bx-test.jsonl"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_clwb_summary_lines() {
|
||||
assert_eq!(format_clwb_line(0, None), "clwb VEH traps : 0");
|
||||
assert_eq!(format_clwb_line(2, None), "clwb VEH samples : 2");
|
||||
assert_eq!(
|
||||
format_clwb_line(3, Some(4)),
|
||||
"clwb VEH traps : at least 4 (sampled)"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,32 @@
|
||||
//! Track A / F: Structured JSONL shim trace aggregator.
|
||||
//!
|
||||
//! Summarizes `bx_runtime_veh.dll` logs (stub API calls, unimplemented COM vtable
|
||||
//! slots, `clwb` traps, and ADX illegal-instruction tripwires) so tracks can prioritize
|
||||
//! the exact next blocking API.
|
||||
//! slots, `clwb` traps, ADX illegal-instruction tripwires, and unhandled exceptions)
|
||||
//! so tracks can identify guest failures and missing APIs.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct TraceSummary {
|
||||
pub total_lines: usize,
|
||||
/// Number of `clwb_trapped` records in the log.
|
||||
pub clwb_events: usize,
|
||||
/// Highest cumulative counter in the sampled CLWB records, if available.
|
||||
pub clwb_trap_lower_bound: Option<u64>,
|
||||
pub adx_errors: usize,
|
||||
pub unhandled_exceptions: Vec<UnhandledException>,
|
||||
pub unimpl_apis: BTreeMap<String, usize>,
|
||||
pub unimpl_vtables: BTreeMap<String, usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct UnhandledException {
|
||||
pub exception_code: Option<String>,
|
||||
pub module_base: Option<String>,
|
||||
pub rva: Option<String>,
|
||||
pub rip: Option<String>,
|
||||
}
|
||||
|
||||
fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
|
||||
let needle = format!("\"{key}\":\"");
|
||||
let start = line.find(&needle)? + needle.len();
|
||||
@@ -34,8 +46,23 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
|
||||
let event = extract_json_str(trimmed, "event").unwrap_or("");
|
||||
let detail = extract_json_str(trimmed, "detail").unwrap_or("");
|
||||
match event {
|
||||
"clwb_trapped" => summary.clwb_events += 1,
|
||||
"clwb_trapped" => {
|
||||
summary.clwb_events += 1;
|
||||
let sample = detail
|
||||
.split_ascii_whitespace()
|
||||
.find_map(|field| field.strip_prefix("total_traps="))
|
||||
.and_then(|count| count.parse::<u64>().ok());
|
||||
summary.clwb_trap_lower_bound = summary.clwb_trap_lower_bound.max(sample);
|
||||
}
|
||||
"adx_illegal_instruction" => summary.adx_errors += 1,
|
||||
"unhandled_exception" => {
|
||||
summary.unhandled_exceptions.push(UnhandledException {
|
||||
exception_code: extract_json_str(trimmed, "exception_code").map(str::to_owned),
|
||||
module_base: extract_json_str(trimmed, "module_base").map(str::to_owned),
|
||||
rva: extract_json_str(trimmed, "rva").map(str::to_owned),
|
||||
rip: extract_json_str(trimmed, "rip").map(str::to_owned),
|
||||
});
|
||||
}
|
||||
"unimpl_api" => *summary.unimpl_apis.entry(detail.to_string()).or_insert(0) += 1,
|
||||
"unimpl_vtable" => {
|
||||
*summary
|
||||
@@ -64,7 +91,9 @@ mod tests {
|
||||
let s = summarize_jsonl(sample);
|
||||
assert_eq!(s.total_lines, 4);
|
||||
assert_eq!(s.clwb_events, 1);
|
||||
assert_eq!(s.clwb_trap_lower_bound, Some(1));
|
||||
assert_eq!(s.adx_errors, 0);
|
||||
assert!(s.unhandled_exceptions.is_empty());
|
||||
assert_eq!(
|
||||
s.unimpl_apis.get("d3d12_xs.dll!D3D12XboxCreateDevice"),
|
||||
Some(&2)
|
||||
@@ -75,4 +104,65 @@ mod tests {
|
||||
Some(&1)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_highest_counter_from_sampled_clwb_records() {
|
||||
for (actual_traps, records, expected_bound) in [
|
||||
(1, &[1][..], 1),
|
||||
(6, &[1, 4, 2], 4),
|
||||
(100, &[1, 2, 4, 8, 16, 32, 64], 64),
|
||||
] {
|
||||
let mut log = String::new();
|
||||
for counter in records {
|
||||
log.push_str(&format!(
|
||||
"{{\"event\":\"clwb_trapped\",\"detail\":\"rip=0x1000 len=4 total_traps={counter}\"}}\n"
|
||||
));
|
||||
}
|
||||
let summary = summarize_jsonl(&log);
|
||||
assert_eq!(summary.clwb_events, records.len(), "{actual_traps} traps");
|
||||
assert_eq!(
|
||||
summary.clwb_trap_lower_bound,
|
||||
Some(expected_bound),
|
||||
"{actual_traps} traps"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_clwb_record_count_without_valid_counters() {
|
||||
let summary = summarize_jsonl(
|
||||
r#"{"event":"clwb_trapped","detail":"rip=0x1000 len=4"}
|
||||
{"event":"clwb_trapped","detail":"rip=0x1000 len=4 total_traps=invalid"}
|
||||
{"event":"unimpl_api","detail":"total_traps=100"}"#,
|
||||
);
|
||||
assert_eq!(summary.clwb_events, 2);
|
||||
assert_eq!(summary.clwb_trap_lower_bound, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collects_unhandled_exceptions_in_log_order() {
|
||||
let log = r#"
|
||||
{"ts_ms":16,"tid":1,"level":"ERROR","sub":"runtime_veh","event":"unhandled_exception","exception_code":"0xc0000005","module_base":"0x0000000140000000","rva":"0x0000000000001234","rip":"0x0000000140001234","rsp":"0x000000000021fd80","registers":{"rax":"0x0123456789abcdef","rbx":"0x0000000000000000","rcx":"0x0000000000000000","rdx":"0x0000000000000000","rsi":"0x0000000000000000","rdi":"0x0000000000000000","rbp":"0x0000000000000000","r8":"0x0000000000000000","r9":"0x0000000000000000","r10":"0x0000000000000000","r11":"0x0000000000000000","r12":"0x0000000000000000","r13":"0x0000000000000000","r14":"0x0000000000000000","r15":"0x0000000000000000"}}
|
||||
{"ts_ms":20,"tid":1,"level":"ERROR","sub":"runtime_veh","event":"unhandled_exception","exception_code":"0xc000001d","module_base":"0x0000000000000000","rva":"0x0000000000000000","rip":"0x0000000000410000","rsp":"0x000000000021fd80","registers":{}}
|
||||
"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.total_lines, 2);
|
||||
assert_eq!(
|
||||
summary.unhandled_exceptions,
|
||||
[
|
||||
UnhandledException {
|
||||
exception_code: Some("0xc0000005".into()),
|
||||
module_base: Some("0x0000000140000000".into()),
|
||||
rva: Some("0x0000000000001234".into()),
|
||||
rip: Some("0x0000000140001234".into()),
|
||||
},
|
||||
UnhandledException {
|
||||
exception_code: Some("0xc000001d".into()),
|
||||
module_base: Some("0x0000000000000000".into()),
|
||||
rva: Some("0x0000000000000000".into()),
|
||||
rip: Some("0x0000000000410000".into()),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,37 +1,249 @@
|
||||
#include <windows.h>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
namespace {
|
||||
std::atomic<uintptr_t> g_next_token{1};
|
||||
|
||||
static_assert(sizeof(uintptr_t) == 8, "BetterXen Win32 shims target x86-64");
|
||||
|
||||
constexpr uintptr_t kPrefixMask = 0xFFFFFFFF00000000ULL;
|
||||
constexpr uintptr_t kSequenceMask = 0x00000000FFFFFFFFULL;
|
||||
constexpr uintptr_t kStatePrefix = 0x50534D3100000000ULL; // "PSM1"
|
||||
constexpr uintptr_t kConstrainedPrefix = 0x50534D3200000000ULL; // "PSM2"
|
||||
constexpr uintptr_t kEmptySlot = 0;
|
||||
constexpr uintptr_t kTombstoneSlot = ~uintptr_t{0};
|
||||
|
||||
struct SrwLockGuard {
|
||||
SRWLOCK& lock;
|
||||
explicit SrwLockGuard(SRWLOCK& l) : lock(l) { AcquireSRWLockExclusive(&lock); }
|
||||
~SrwLockGuard() { ReleaseSRWLockExclusive(&lock); }
|
||||
SrwLockGuard(const SrwLockGuard&) = delete;
|
||||
SrwLockGuard& operator=(const SrwLockGuard&) = delete;
|
||||
};
|
||||
|
||||
// Exception-free open-addressed hash set backed by the Win32 process heap so
|
||||
// both PSM DLLs stay on -fno-exceptions and map OOM to ERROR_NOT_ENOUGH_MEMORY.
|
||||
struct TokenSet {
|
||||
uintptr_t* slots = nullptr;
|
||||
size_t capacity = 0;
|
||||
size_t count = 0;
|
||||
size_t used = 0; // active entries + tombstones
|
||||
|
||||
static size_t hash(uintptr_t value) {
|
||||
uint64_t x = static_cast<uint64_t>(value);
|
||||
x ^= x >> 30;
|
||||
x *= 0xbf58476d1ce4e5b9ULL;
|
||||
x ^= x >> 27;
|
||||
x *= 0x94d049bb133111ebULL;
|
||||
x ^= x >> 31;
|
||||
return static_cast<size_t>(x);
|
||||
}
|
||||
|
||||
bool rehash(size_t new_capacity) {
|
||||
if (new_capacity == 0 || new_capacity > SIZE_MAX / sizeof(uintptr_t)) {
|
||||
return false;
|
||||
}
|
||||
HANDLE heap = GetProcessHeap();
|
||||
if (!heap) {
|
||||
return false;
|
||||
}
|
||||
auto* fresh = static_cast<uintptr_t*>(
|
||||
HeapAlloc(heap, HEAP_ZERO_MEMORY, new_capacity * sizeof(uintptr_t)));
|
||||
if (!fresh) {
|
||||
return false;
|
||||
}
|
||||
const size_t mask = new_capacity - 1;
|
||||
for (size_t i = 0; i < capacity; ++i) {
|
||||
const uintptr_t entry = slots[i];
|
||||
if (entry != kEmptySlot && entry != kTombstoneSlot) {
|
||||
size_t idx = hash(entry) & mask;
|
||||
while (fresh[idx] != kEmptySlot) {
|
||||
idx = (idx + 1) & mask;
|
||||
}
|
||||
fresh[idx] = entry;
|
||||
}
|
||||
}
|
||||
if (slots) {
|
||||
HeapFree(heap, 0, slots);
|
||||
}
|
||||
slots = fresh;
|
||||
capacity = new_capacity;
|
||||
used = count;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool insert(uintptr_t token) {
|
||||
if (capacity == 0 || (used + 1) * 4 >= capacity * 3) {
|
||||
size_t next_capacity = 64;
|
||||
if (capacity != 0) {
|
||||
if (count * 2 >= capacity) {
|
||||
if (capacity > (SIZE_MAX / sizeof(uintptr_t)) / 2) {
|
||||
return false;
|
||||
}
|
||||
next_capacity = capacity * 2;
|
||||
} else {
|
||||
// Compact tombstones in place without growing the table.
|
||||
next_capacity = capacity;
|
||||
}
|
||||
}
|
||||
if (!rehash(next_capacity)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const size_t mask = capacity - 1;
|
||||
size_t idx = hash(token) & mask;
|
||||
size_t first_tombstone = capacity;
|
||||
while (true) {
|
||||
const uintptr_t entry = slots[idx];
|
||||
if (entry == token) {
|
||||
return true;
|
||||
}
|
||||
if (entry == kEmptySlot) {
|
||||
if (first_tombstone != capacity) {
|
||||
slots[first_tombstone] = token;
|
||||
} else {
|
||||
slots[idx] = token;
|
||||
++used;
|
||||
}
|
||||
++count;
|
||||
return true;
|
||||
}
|
||||
if (entry == kTombstoneSlot && first_tombstone == capacity) {
|
||||
first_tombstone = idx;
|
||||
}
|
||||
idx = (idx + 1) & mask;
|
||||
}
|
||||
}
|
||||
|
||||
bool erase(uintptr_t token) {
|
||||
if (capacity == 0 || count == 0 || token == kEmptySlot || token == kTombstoneSlot) {
|
||||
return false;
|
||||
}
|
||||
const size_t mask = capacity - 1;
|
||||
size_t idx = hash(token) & mask;
|
||||
for (size_t probed = 0; probed < capacity; ++probed) {
|
||||
const uintptr_t entry = slots[idx];
|
||||
if (entry == kEmptySlot) {
|
||||
return false;
|
||||
}
|
||||
if (entry == token) {
|
||||
slots[idx] = kTombstoneSlot;
|
||||
--count;
|
||||
return true;
|
||||
}
|
||||
idx = (idx + 1) & mask;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
if (slots) {
|
||||
HANDLE heap = GetProcessHeap();
|
||||
if (heap) {
|
||||
HeapFree(heap, 0, slots);
|
||||
}
|
||||
slots = nullptr;
|
||||
}
|
||||
capacity = 0;
|
||||
count = 0;
|
||||
used = 0;
|
||||
}
|
||||
};
|
||||
|
||||
struct Registrations {
|
||||
SRWLOCK lock;
|
||||
TokenSet active;
|
||||
uintptr_t own_prefix;
|
||||
uintptr_t foreign_prefix;
|
||||
uint64_t next_seq;
|
||||
};
|
||||
|
||||
// Each DLL exposes one family. Disjoint tagged token spaces prevent an
|
||||
// unregister call on the wrong DLL from removing another registration and let
|
||||
// logs distinguish foreign-family tokens from retired or invalid ones.
|
||||
Registrations g_state{SRWLOCK_INIT, {}, kStatePrefix, kConstrainedPrefix, 1};
|
||||
Registrations g_constrained{SRWLOCK_INIT, {}, kConstrainedPrefix, kStatePrefix, 1};
|
||||
|
||||
ULONG register_notification(Registrations& registrations, PVOID callback,
|
||||
PVOID* out_reg, const char* event) {
|
||||
if (!out_reg) {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
}
|
||||
*out_reg = nullptr;
|
||||
if (!callback) {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
}
|
||||
|
||||
uintptr_t token = 0;
|
||||
{
|
||||
const SrwLockGuard guard(registrations.lock);
|
||||
// Never recycle a token that a caller may still retain.
|
||||
if (registrations.next_seq > kSequenceMask) {
|
||||
return ERROR_NOT_ENOUGH_MEMORY;
|
||||
}
|
||||
token = registrations.own_prefix | static_cast<uintptr_t>(registrations.next_seq);
|
||||
if (!registrations.active.insert(token)) {
|
||||
return ERROR_NOT_ENOUGH_MEMORY;
|
||||
}
|
||||
++registrations.next_seq;
|
||||
}
|
||||
|
||||
*out_reg = reinterpret_cast<PVOID>(token);
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", event, "registered_offline");
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
void unregister_notification(Registrations& registrations, PVOID reg, const char* event) {
|
||||
const uintptr_t token = reinterpret_cast<uintptr_t>(reg);
|
||||
bool removed = false;
|
||||
{
|
||||
const SrwLockGuard guard(registrations.lock);
|
||||
removed = registrations.active.erase(token);
|
||||
}
|
||||
const char* detail = "unknown_token";
|
||||
if (removed) {
|
||||
detail = "unregistered";
|
||||
} else if ((token & kPrefixMask) == registrations.foreign_prefix &&
|
||||
(token & kSequenceMask) != 0) {
|
||||
detail = "foreign_token";
|
||||
}
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", event, detail);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
ULONG WINAPI RegisterAppStateChangeNotification(PVOID /*callback*/, PVOID /*context*/, PVOID* out_reg) {
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", "RegisterAppStateChangeNotification", "noop_ok");
|
||||
if (out_reg) {
|
||||
*out_reg = reinterpret_cast<PVOID>(g_next_token.fetch_add(1));
|
||||
BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID reserved) {
|
||||
if (reason == DLL_PROCESS_DETACH && reserved == nullptr) {
|
||||
{
|
||||
const SrwLockGuard guard(g_state.lock);
|
||||
g_state.active.reset();
|
||||
}
|
||||
{
|
||||
const SrwLockGuard guard(g_constrained.lock);
|
||||
g_constrained.active.reset();
|
||||
}
|
||||
}
|
||||
return ERROR_SUCCESS;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
VOID WINAPI UnregisterAppStateChangeNotification(PVOID /*reg*/) {
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", "UnregisterAppStateChangeNotification", "noop_ok");
|
||||
ULONG WINAPI RegisterAppStateChangeNotification(PVOID callback, PVOID /*context*/, PVOID* out_reg) {
|
||||
return register_notification(g_state, callback, out_reg, "RegisterAppStateChangeNotification");
|
||||
}
|
||||
|
||||
ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID /*callback*/, PVOID /*context*/, PVOID* out_reg) {
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", "RegisterAppConstrainedChangeNotification", "noop_ok");
|
||||
if (out_reg) {
|
||||
*out_reg = reinterpret_cast<PVOID>(g_next_token.fetch_add(1));
|
||||
}
|
||||
return ERROR_SUCCESS;
|
||||
VOID WINAPI UnregisterAppStateChangeNotification(PVOID reg) {
|
||||
unregister_notification(g_state, reg, "UnregisterAppStateChangeNotification");
|
||||
}
|
||||
|
||||
VOID WINAPI UnregisterAppConstrainedChangeNotification(PVOID /*reg*/) {
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", "UnregisterAppConstrainedChangeNotification", "noop_ok");
|
||||
ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID callback, PVOID /*context*/, PVOID* out_reg) {
|
||||
return register_notification(g_constrained, callback, out_reg, "RegisterAppConstrainedChangeNotification");
|
||||
}
|
||||
|
||||
VOID WINAPI UnregisterAppConstrainedChangeNotification(PVOID reg) {
|
||||
unregister_notification(g_constrained, reg, "UnregisterAppConstrainedChangeNotification");
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -1,4 +1,5 @@
|
||||
bx_add_shim_dll(xmem xmem xmem.def
|
||||
xmem.cpp
|
||||
physical_pages.cpp
|
||||
)
|
||||
target_link_libraries(xmem PRIVATE bx_runtime_veh kernel32)
|
||||
@@ -0,0 +1,385 @@
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
#include "xmem_accounting.h"
|
||||
|
||||
namespace {
|
||||
constexpr SIZE_T small_page = 64 * 1024;
|
||||
constexpr SIZE_T large_page = 2 * 1024 * 1024;
|
||||
|
||||
struct PageBlock;
|
||||
|
||||
struct Page {
|
||||
PageBlock* block;
|
||||
HANDLE section;
|
||||
bool releasing;
|
||||
};
|
||||
|
||||
struct PageBlock {
|
||||
ULONG_PTR first_tag;
|
||||
SIZE_T count;
|
||||
SIZE_T size;
|
||||
SIZE_T live;
|
||||
Page* entries;
|
||||
PageBlock* next;
|
||||
};
|
||||
|
||||
struct View {
|
||||
Page* page;
|
||||
BYTE* address;
|
||||
View* next;
|
||||
};
|
||||
|
||||
SRWLOCK memory_lock = SRWLOCK_INIT;
|
||||
PageBlock* blocks = nullptr;
|
||||
View* views = nullptr;
|
||||
ULONG_PTR next_tag = 1;
|
||||
|
||||
struct Lock {
|
||||
Lock() { AcquireSRWLockExclusive(&memory_lock); }
|
||||
~Lock() { ReleaseSRWLockExclusive(&memory_lock); }
|
||||
};
|
||||
|
||||
using ReservePlaceholder = PVOID (WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG,
|
||||
MEM_EXTENDED_PARAMETER*, ULONG);
|
||||
using ReplacePlaceholder = PVOID (WINAPI*)(HANDLE, HANDLE, PVOID, ULONG64, SIZE_T, ULONG,
|
||||
ULONG, MEM_EXTENDED_PARAMETER*, ULONG);
|
||||
|
||||
struct PlaceholderApi {
|
||||
HMODULE kernel = GetModuleHandleW(L"kernelbase.dll");
|
||||
ReservePlaceholder reserve = resolve<ReservePlaceholder>("VirtualAlloc2");
|
||||
ReplacePlaceholder replace = resolve<ReplacePlaceholder>("MapViewOfFile3");
|
||||
|
||||
template<class Function>
|
||||
Function resolve(const char* name) const {
|
||||
return reinterpret_cast<Function>(reinterpret_cast<void*>(GetProcAddress(kernel, name)));
|
||||
}
|
||||
};
|
||||
|
||||
// The public backlog defines the supported sizes. The flags accepted here
|
||||
// belong to BetterXen's synthetic fixtures, pending a public console flags ABI.
|
||||
SIZE_T page_size(uint64_t flags) {
|
||||
switch (flags) {
|
||||
case 0:
|
||||
case small_page: return small_page;
|
||||
case large_page: return large_page;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
Page* find_page(ULONG_PTR tag) {
|
||||
for (PageBlock* block = blocks; block; block = block->next) {
|
||||
if (tag >= block->first_tag && tag - block->first_tag < block->count) {
|
||||
Page* page = &block->entries[tag - block->first_tag];
|
||||
return page->section ? page : nullptr;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
ULONG_PTR page_tag(const Page* page) {
|
||||
return page->block->first_tag + (page - page->block->entries);
|
||||
}
|
||||
|
||||
void delete_block(PageBlock* block) {
|
||||
for (SIZE_T i = 0; i < block->count; ++i) {
|
||||
if (block->entries[i].section) CloseHandle(block->entries[i].section);
|
||||
}
|
||||
delete[] block->entries;
|
||||
delete block;
|
||||
}
|
||||
|
||||
void destroy_views(View* first) {
|
||||
while (first) {
|
||||
View* next = first->next;
|
||||
delete first;
|
||||
first = next;
|
||||
}
|
||||
}
|
||||
|
||||
bool valid_span(PVOID base, SIZE_T count, SIZE_T size) {
|
||||
const auto address = reinterpret_cast<uintptr_t>(base);
|
||||
return size && count && address % size == 0
|
||||
&& count <= (std::numeric_limits<uintptr_t>::max() - address) / size;
|
||||
}
|
||||
|
||||
bool remove_view(View** link) {
|
||||
View* view = *link;
|
||||
if (!UnmapViewOfFile(view->address)) return false;
|
||||
*link = view->next;
|
||||
delete view;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Require every page slot in [base, base + count * size) to be actively mapped
|
||||
// with matching page size before unmapping; empty or partial spans fail without
|
||||
// modifying any existing views.
|
||||
PVOID unmap_span(BYTE* base, SIZE_T count, SIZE_T size) {
|
||||
if (!base) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
const auto begin = reinterpret_cast<uintptr_t>(base);
|
||||
const auto end = begin + count * size;
|
||||
|
||||
SIZE_T matched = 0;
|
||||
for (const View* view = views; view; view = view->next) {
|
||||
const auto address = reinterpret_cast<uintptr_t>(view->address);
|
||||
if (address >= begin && address < end && view->page->block->size == size) {
|
||||
++matched;
|
||||
}
|
||||
}
|
||||
if (matched != count) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
for (View** link = &views; *link;) {
|
||||
View* view = *link;
|
||||
const auto address = reinterpret_cast<uintptr_t>(view->address);
|
||||
if (address >= begin && address < end && view->page->block->size == size) {
|
||||
if (!remove_view(link)) return nullptr;
|
||||
} else {
|
||||
link = &view->next;
|
||||
}
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
// Duplicate tags in `tags` are intentionally permitted so a single virtual span
|
||||
// can alias one physical page at multiple offsets (e.g. ring buffers / tiles).
|
||||
PVOID map_pages(PVOID address, SIZE_T count, uint64_t flags, const ULONG_PTR* tags) {
|
||||
const SIZE_T size = page_size(flags);
|
||||
if (!valid_span(address, count, size)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Lock lock;
|
||||
if (!tags) return unmap_span(static_cast<BYTE*>(address), count, size);
|
||||
|
||||
static const PlaceholderApi api;
|
||||
if (!api.reserve || !api.replace) {
|
||||
BX_STUB_LOG("xmem.dll", "MapViewOfFile3");
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
View* pending = nullptr;
|
||||
for (SIZE_T i = count; i > 0; --i) {
|
||||
Page* page = find_page(tags[i - 1]);
|
||||
if (!page || page->block->size != size) {
|
||||
destroy_views(pending);
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
auto* view = new (std::nothrow) View{page, nullptr, pending};
|
||||
if (!view) {
|
||||
destroy_views(pending);
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
pending = view;
|
||||
}
|
||||
|
||||
MEM_ADDRESS_REQUIREMENTS requirements{};
|
||||
requirements.Alignment = size;
|
||||
MEM_EXTENDED_PARAMETER alignment{};
|
||||
alignment.Type = MemExtendedParameterAddressRequirements;
|
||||
alignment.Pointer = &requirements;
|
||||
auto* base = static_cast<BYTE*>(api.reserve(nullptr, address, count * size,
|
||||
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS,
|
||||
address ? nullptr : &alignment, address ? 0 : 1));
|
||||
if (!base) {
|
||||
const DWORD error = GetLastError();
|
||||
destroy_views(pending);
|
||||
SetLastError(error);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
BYTE* cursor = base;
|
||||
SIZE_T remaining = count;
|
||||
View* view = pending;
|
||||
for (; view; view = view->next, cursor += size, --remaining) {
|
||||
const bool split = remaining > 1;
|
||||
if (split && !VirtualFree(cursor, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) break;
|
||||
if (!api.replace(view->page->section, nullptr, cursor, 0, size,
|
||||
MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0)) {
|
||||
const DWORD error = GetLastError();
|
||||
if (split) VirtualFree(cursor + size, 0, MEM_RELEASE);
|
||||
SetLastError(error);
|
||||
break;
|
||||
}
|
||||
view->address = cursor;
|
||||
}
|
||||
|
||||
if (view) {
|
||||
const DWORD error = GetLastError();
|
||||
VirtualFree(cursor, 0, MEM_RELEASE);
|
||||
for (View* completed = pending; completed != view; completed = completed->next) {
|
||||
UnmapViewOfFile(completed->address);
|
||||
}
|
||||
destroy_views(pending);
|
||||
SetLastError(error);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
while (pending) {
|
||||
View* next = pending->next;
|
||||
pending->next = views;
|
||||
views = pending;
|
||||
pending = next;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// Clean-room synthetic signatures modeled after public Win32 AWE
|
||||
// AllocateUserPhysicalPages / FreeUserPhysicalPages (memoryapi.h, [in, out]
|
||||
// page count pointer), pending a public console flags/signature ABI.
|
||||
extern "C" BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_array,
|
||||
uint64_t flags) {
|
||||
const SIZE_T size = page_size(flags);
|
||||
if (!num_pages || !page_array || !valid_span(nullptr, *num_pages, size)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
Lock lock;
|
||||
const SIZE_T count = *num_pages;
|
||||
if (count > std::numeric_limits<ULONG_PTR>::max() - next_tag
|
||||
|| count > std::numeric_limits<SIZE_T>::max() / sizeof(Page)
|
||||
|| count > std::numeric_limits<uint64_t>::max() / size) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
const uint64_t total_bytes = static_cast<uint64_t>(count) * size;
|
||||
if (!bx_xmem::try_reserve_physical(total_bytes)) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
auto* entries = new (std::nothrow) Page[count]{};
|
||||
if (!entries) {
|
||||
bx_xmem::release_physical(total_bytes);
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
auto* block = new (std::nothrow) PageBlock{next_tag, count, size, count, entries, blocks};
|
||||
if (!block) {
|
||||
delete[] entries;
|
||||
bx_xmem::release_physical(total_bytes);
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
for (SIZE_T i = 0; i < count; ++i) {
|
||||
HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE,
|
||||
0, static_cast<DWORD>(size), nullptr);
|
||||
if (!section) {
|
||||
const DWORD error = GetLastError();
|
||||
delete_block(block);
|
||||
bx_xmem::release_physical(total_bytes);
|
||||
SetLastError(error);
|
||||
return FALSE;
|
||||
}
|
||||
entries[i] = {block, section, false};
|
||||
}
|
||||
|
||||
blocks = block;
|
||||
for (SIZE_T i = 0; i < count; ++i) page_array[i] = next_tag + i;
|
||||
next_tag += count;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// Rejects unknown, wrong-size, or duplicate tags in `page_array` with
|
||||
// ERROR_INVALID_PARAMETER without mutating `page_array` or live views.
|
||||
extern "C" BOOL WINAPI XMemFreePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_array,
|
||||
uint64_t flags) {
|
||||
const SIZE_T size = page_size(flags);
|
||||
if (!num_pages || !page_array || !valid_span(nullptr, *num_pages, size)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
Lock lock;
|
||||
const SIZE_T count = *num_pages;
|
||||
SIZE_T validated = 0;
|
||||
for (; validated < count; ++validated) {
|
||||
Page* page = find_page(page_array[validated]);
|
||||
if (!page || page->block->size != size || page->releasing) break;
|
||||
page->releasing = true;
|
||||
}
|
||||
if (validated != count) {
|
||||
for (SIZE_T i = 0; i < validated; ++i) find_page(page_array[i])->releasing = false;
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
for (View** link = &views; *link;) {
|
||||
if ((*link)->page->releasing) {
|
||||
if (!remove_view(link)) {
|
||||
const DWORD error = GetLastError();
|
||||
for (SIZE_T i = 0; i < count; ++i) find_page(page_array[i])->releasing = false;
|
||||
SetLastError(error);
|
||||
return FALSE;
|
||||
}
|
||||
} else {
|
||||
link = &(*link)->next;
|
||||
}
|
||||
}
|
||||
|
||||
for (SIZE_T i = 0; i < count; ++i) {
|
||||
Page* page = find_page(page_array[i]);
|
||||
CloseHandle(page->section);
|
||||
page->section = nullptr;
|
||||
--page->block->live;
|
||||
page_array[i] = 0;
|
||||
}
|
||||
for (PageBlock** link = &blocks; *link;) {
|
||||
PageBlock* block = *link;
|
||||
if (block->live) {
|
||||
link = &block->next;
|
||||
} else {
|
||||
*link = block->next;
|
||||
delete_block(block);
|
||||
}
|
||||
}
|
||||
bx_xmem::release_physical(static_cast<uint64_t>(count) * size);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
extern "C" PVOID WINAPI XMemMapPhysicalPages(PVOID base, SIZE_T count, uint64_t flags,
|
||||
PULONG_PTR page_array) {
|
||||
return map_pages(base, count, flags, page_array);
|
||||
}
|
||||
|
||||
extern "C" PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID base, SIZE_T count, uint64_t flags,
|
||||
PULONG_PTR page_array) {
|
||||
return map_pages(base, count, flags, page_array);
|
||||
}
|
||||
|
||||
extern "C" int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info) {
|
||||
if (!out_info) return 0;
|
||||
|
||||
Lock lock;
|
||||
for (const View* view = views; view; view = view->next) {
|
||||
const auto base = reinterpret_cast<uintptr_t>(view->address);
|
||||
const SIZE_T size = view->page->block->size;
|
||||
if (va >= base && va - base < size) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(view->address, ®ion, sizeof(region))
|
||||
|| region.AllocationBase != view->address || region.Type != MEM_MAPPED) {
|
||||
return 0;
|
||||
}
|
||||
*out_info = {base, size, size, region.Protect, region.Type, page_tag(view->page)};
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
+25
-31
@@ -10,6 +10,7 @@
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
#include "xmem_accounting.h"
|
||||
|
||||
namespace {
|
||||
constexpr SIZE_T heap_alignment = 64;
|
||||
@@ -61,6 +62,7 @@ std::mutex usage_lock;
|
||||
CommitTable virtual_commits;
|
||||
uint64_t heap_bytes = 0;
|
||||
uint64_t virtual_bytes = 0;
|
||||
uint64_t physical_bytes = 0;
|
||||
uint64_t peak_bytes = 0;
|
||||
|
||||
uint64_t title_limit() {
|
||||
@@ -70,12 +72,12 @@ uint64_t title_limit() {
|
||||
|
||||
bool can_commit(uint64_t bytes) {
|
||||
const uint64_t limit = title_limit();
|
||||
const uint64_t used = heap_bytes + virtual_bytes;
|
||||
const uint64_t used = heap_bytes + virtual_bytes + physical_bytes;
|
||||
return used <= limit && bytes <= limit - used;
|
||||
}
|
||||
|
||||
void update_peak() {
|
||||
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes);
|
||||
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes + physical_bytes);
|
||||
}
|
||||
|
||||
uintptr_t region_end(const MEMORY_BASIC_INFORMATION& region) {
|
||||
@@ -268,29 +270,6 @@ SIZE_T WINAPI XMemVirtualQuery(LPCVOID address, PMEMORY_BASIC_INFORMATION buf, S
|
||||
return VirtualQuery(address, buf, len);
|
||||
}
|
||||
|
||||
BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* /*num_pages*/, PULONG_PTR /*page_array*/, uint64_t /*flags*/) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemAllocatePhysicalPages");
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
BOOL WINAPI XMemFreePhysicalPages(SIZE_T /*num_pages*/, PULONG_PTR /*page_array*/, uint64_t /*flags*/) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemFreePhysicalPages");
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
PVOID WINAPI XMemMapPhysicalPages(PVOID /*base*/, SIZE_T /*num_pages*/, uint64_t /*flags*/, PULONG_PTR /*page_array*/) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemMapPhysicalPages");
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID /*base*/, SIZE_T /*num_pages*/, uint64_t /*flags*/, PULONG_PTR /*page_array*/) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemMapPhysicalPagesScatter");
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
BOOL WINAPI XMemTransferMemory(PVOID dst, LPCVOID src, SIZE_T bytes, uint64_t /*flags*/) {
|
||||
if (bytes == 0) return TRUE;
|
||||
if (!dst || !src) {
|
||||
@@ -311,7 +290,7 @@ BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes, 0, peak_bytes};
|
||||
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes, physical_bytes, peak_bytes};
|
||||
std::memset(out_stats, 0, stats_size);
|
||||
std::memcpy(out_stats, &stats, sizeof(stats));
|
||||
return TRUE;
|
||||
@@ -321,18 +300,33 @@ BOOL WINAPI XMemIsToolsMemAvailable(void) {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
int bx_xmem_query_region(uint64_t /*va*/, bx_xmem_region_info_t* /*out_info*/) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats) {
|
||||
if (!out_stats) return;
|
||||
if (!XMemGetWorkingSetStatistics(out_stats, sizeof(*out_stats))) {
|
||||
// The internal ABI has no error return. Preserve the most recent
|
||||
// accounting snapshot if refreshing it runs out of bookkeeping memory.
|
||||
std::lock_guard guard(usage_lock);
|
||||
*out_stats = {title_limit(), heap_bytes + virtual_bytes, 0, peak_bytes};
|
||||
*out_stats = {title_limit(), heap_bytes + virtual_bytes, physical_bytes, peak_bytes};
|
||||
}
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
namespace bx_xmem {
|
||||
|
||||
bool try_reserve_physical(uint64_t bytes) {
|
||||
std::lock_guard guard(usage_lock);
|
||||
if (!can_commit(bytes) && (!refresh_virtual_commits() || !can_commit(bytes))) {
|
||||
return false;
|
||||
}
|
||||
physical_bytes += bytes;
|
||||
update_peak();
|
||||
return true;
|
||||
}
|
||||
|
||||
void release_physical(uint64_t bytes) {
|
||||
std::lock_guard guard(usage_lock);
|
||||
physical_bytes = physical_bytes >= bytes ? physical_bytes - bytes : 0;
|
||||
}
|
||||
|
||||
} // namespace bx_xmem
|
||||
@@ -0,0 +1,15 @@
|
||||
#ifndef BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
|
||||
#define BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace bx_xmem {
|
||||
|
||||
// Reserve or release physical-page bytes against the shared xmem title memory
|
||||
// cap and working-set statistics (heap + virtual + physical <= title limit).
|
||||
bool try_reserve_physical(uint64_t bytes);
|
||||
void release_physical(uint64_t bytes);
|
||||
|
||||
} // namespace bx_xmem
|
||||
|
||||
#endif // BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
|
||||
@@ -6,7 +6,9 @@
|
||||
# CreateWindowExA & co. bind to the ext-ms-win-rtcore-ntuser-* shims instead of
|
||||
# the toolchain's default user32 import library.
|
||||
add_executable(test_integration_boot main.cpp)
|
||||
target_include_directories(test_integration_boot PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_include_directories(test_integration_boot PRIVATE
|
||||
"${BX_ABI_INCLUDE_DIR}"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../../../shims/xg_xs")
|
||||
target_link_libraries(test_integration_boot PRIVATE
|
||||
ntuser_win_ansi_1_0
|
||||
ntuser_win_1_0
|
||||
|
||||
@@ -24,7 +24,8 @@
|
||||
* or an error-severity exception.
|
||||
*
|
||||
* Function prototypes below mirror the in-tree shim sources and abi/defs; this
|
||||
* fixture deliberately invents no console structure layouts.
|
||||
* fixture deliberately invents no console structure layouts. The xg_xs
|
||||
* descriptor and vtable are BetterXen's own, from shims/xg_xs/xg_texture.h.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
@@ -40,6 +41,7 @@
|
||||
#include "bx_config.h"
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
#include "xg_texture.h"
|
||||
|
||||
#define BX_IMPORT __declspec(dllimport)
|
||||
|
||||
@@ -94,11 +96,7 @@ BX_IMPORT HRESULT WINAPI XDspDisconnect(void* handle);
|
||||
/* GameInput.dll (ordinal 1) */
|
||||
BX_IMPORT HRESULT WINAPI GameInputCreate(void** out_game_input);
|
||||
|
||||
/* xg_xs.dll */
|
||||
BX_IMPORT HRESULT WINAPI XGCreateTextureComputer(const void* desc, void** out_computer);
|
||||
BX_IMPORT uint32_t WINAPI XGSuggestSwizzleMode(uint32_t resource_type, uint32_t format, uint32_t width,
|
||||
uint32_t height, uint32_t depth, uint32_t mip_levels,
|
||||
uint32_t sample_count, uint32_t flags);
|
||||
/* xg_xs.dll is declared by "xg_texture.h". */
|
||||
|
||||
/* d3d12_xs.dll (D3D12SerializeVersionedRootSignature is declared by <d3d12.h>) */
|
||||
BX_IMPORT HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
|
||||
@@ -651,27 +649,71 @@ void stage_acphal_heap() {
|
||||
|
||||
/* ---- Stage 13: xg_xs ---------------------------------------------------------------------- */
|
||||
|
||||
/*
|
||||
* 100x50 R8G8B8A8 with two mips, so both public D3D12 alignments matter. By hand:
|
||||
* mip 0: 100 * 4 = 400 bytes per row, pitch 512 (256-byte pitch alignment);
|
||||
* ends at 49 * 512 + 400 = 25488.
|
||||
* mip 1: starts at the next 512 boundary, 25600; 50 * 4 = 200 bytes per row,
|
||||
* pitch 256; ends at 25600 + 24 * 256 + 200 = 31944.
|
||||
* total: 31944 rounded up to 512 = 32256.
|
||||
*/
|
||||
void* stage_xg_texture_computer() {
|
||||
begin_stage("xg_xs_texture_computer");
|
||||
bx_xg_resource_desc desc = {};
|
||||
desc.dimension = BX_XG_DIMENSION_TEXTURE2D;
|
||||
desc.width = 100;
|
||||
desc.height = 50;
|
||||
desc.depth_or_array_size = 1;
|
||||
desc.mip_levels = 2;
|
||||
desc.format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
desc.sample_desc.count = 1;
|
||||
desc.layout = BX_XG_LAYOUT_LINEAR;
|
||||
|
||||
void* object = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
|
||||
HRESULT hr = XGCreateTextureComputer(&desc, &object);
|
||||
if (hr != S_OK || !object || object == reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD))) {
|
||||
checkpoint("xg_xs_texture_computer", Status::Fail, "XGCreateTextureComputer hr=0x%08lx object=%p",
|
||||
static_cast<unsigned long>(hr), object);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto* computer = static_cast<bx_xg_texture_computer*>(object);
|
||||
bx_xg_placed_footprint mips[2] = {};
|
||||
uint32_t rows[2] = {};
|
||||
uint64_t row_bytes[2] = {};
|
||||
uint64_t total = 0;
|
||||
hr = computer->lpVtbl->GetResourceLayout(computer, 0, 2, 0, mips, rows, row_bytes, &total);
|
||||
auto shape_is = [](const bx_xg_subresource_footprint& f, uint32_t width, uint32_t height, uint32_t pitch) {
|
||||
return f.format == DXGI_FORMAT_R8G8B8A8_UNORM && f.width == width && f.height == height && f.depth == 1 &&
|
||||
f.row_pitch == pitch;
|
||||
};
|
||||
const bool mip0 = mips[0].offset == 0 && shape_is(mips[0].footprint, 100, 50, 512) && mips[0].copy_end == 25488 &&
|
||||
rows[0] == 50 && row_bytes[0] == 400;
|
||||
const bool mip1 = mips[1].offset == 25600 && shape_is(mips[1].footprint, 50, 25, 256) && mips[1].copy_end == 31944 &&
|
||||
rows[1] == 25 && row_bytes[1] == 200;
|
||||
if (hr == S_OK && mip0 && mip1 && total == 32256) {
|
||||
checkpoint("xg_xs_texture_computer", Status::Pass,
|
||||
"100x50 RGBA8 two-mip linear footprints and 32256 total bytes match hand-computed values");
|
||||
} else {
|
||||
checkpoint("xg_xs_texture_computer", Status::Fail,
|
||||
"GetResourceLayout hr=0x%08lx mip0_ok=%d mip1_ok=%d total=%llu",
|
||||
static_cast<unsigned long>(hr), mip0, mip1, static_cast<unsigned long long>(total));
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
void* stage_xg_xs() {
|
||||
begin_stage("xg_xs_swizzle_mode");
|
||||
/* D3D12_RESOURCE_DIMENSION_TEXTURE2D / DXGI_FORMAT_R8G8B8A8_UNORM, 256x256, 1 mip, 1 sample. */
|
||||
uint32_t mode_a = XGSuggestSwizzleMode(D3D12_RESOURCE_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM, 256, 256, 1, 1, 1, 0);
|
||||
uint32_t mode_b = XGSuggestSwizzleMode(D3D12_RESOURCE_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM, 256, 256, 1, 1, 1, 0);
|
||||
if (mode_a == mode_b) {
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Pass, "XGSuggestSwizzleMode is deterministic for identical inputs (mode=%u)", mode_a);
|
||||
if (mode_a == BX_XG_LAYOUT_LINEAR && mode_b == mode_a) {
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Pass, "XGSuggestSwizzleMode suggests linear and is deterministic (mode=%u)", mode_a);
|
||||
} else {
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Fail, "XGSuggestSwizzleMode returned %u then %u for identical inputs", mode_a, mode_b);
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Fail, "XGSuggestSwizzleMode returned %u then %u, expected linear", mode_a, mode_b);
|
||||
}
|
||||
|
||||
begin_stage("xg_xs_texture_computer");
|
||||
void* computer = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
|
||||
HRESULT hr = XGCreateTextureComputer(nullptr, &computer);
|
||||
if (computer == reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD))) {
|
||||
checkpoint("xg_xs_texture_computer", Status::Fail, "XGCreateTextureComputer left the out pointer unwritten (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
return nullptr;
|
||||
}
|
||||
report_create("xg_xs_texture_computer", "XGCreateTextureComputer", hr, computer, true);
|
||||
return hr == S_OK ? computer : nullptr;
|
||||
return stage_xg_texture_computer();
|
||||
}
|
||||
|
||||
/* ---- Stage 14: d3d12_xs ------------------------------------------------------------------- */
|
||||
@@ -825,7 +867,12 @@ int main(int argc, char** argv) {
|
||||
/* --- Shutdown (reverse order) ----------------------------------------- */
|
||||
begin_stage("shutdown");
|
||||
release_com(device);
|
||||
release_com(texture_computer);
|
||||
/* The fixture holds the only reference, so this Release must return 0. */
|
||||
ULONG texture_refs = 0;
|
||||
if (texture_computer) {
|
||||
auto* computer = static_cast<bx_xg_texture_computer*>(texture_computer);
|
||||
texture_refs = computer->lpVtbl->Release(computer);
|
||||
}
|
||||
release_com(game_input);
|
||||
bool dsp_closed = true;
|
||||
if (dsp) {
|
||||
@@ -841,10 +888,11 @@ int main(int argc, char** argv) {
|
||||
if (runtime_initialized) XGameRuntimeUninitialize();
|
||||
|
||||
LONG faults = InterlockedCompareExchange(&g_error_exceptions, 0, 0);
|
||||
if (dsp_closed && apu_closed && faults == 0) {
|
||||
if (dsp_closed && apu_closed && texture_refs == 0 && faults == 0) {
|
||||
checkpoint("shutdown", Status::Pass, "reverse-order teardown completed with 0 error-severity exceptions");
|
||||
} else {
|
||||
checkpoint("shutdown", Status::Fail, "dsp_closed=%d apu_closed=%d error_exceptions=%ld", dsp_closed, apu_closed, faults);
|
||||
checkpoint("shutdown", Status::Fail, "dsp_closed=%d apu_closed=%d texture_refs=%lu error_exceptions=%ld",
|
||||
dsp_closed, apu_closed, texture_refs, faults);
|
||||
}
|
||||
if (fault_handle) RemoveVectoredExceptionHandler(fault_handle);
|
||||
SetUnhandledExceptionFilter(g_prev_unhandled_filter);
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
add_executable(test_win32_bridge main.cpp)
|
||||
target_link_libraries(test_win32_bridge PRIVATE kernel32 user32)
|
||||
add_dependencies(test_win32_bridge
|
||||
psm_appnotify_1_0 psm_appnotify_1_1
|
||||
ntuser_msg_1_0 ntuser_msg_ansi_1_0 ntuser_win_1_0 ntuser_win_ansi_1_0
|
||||
)
|
||||
@@ -0,0 +1,372 @@
|
||||
#include <windows.h>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <bit>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr UINT kMessage = WM_APP + 1;
|
||||
constexpr WPARAM kPayload = 42;
|
||||
decltype(&DefWindowProcA) g_def_window_proc;
|
||||
bool g_received_message = false;
|
||||
std::atomic<bool> g_callback_called{false};
|
||||
|
||||
struct ScopedModule {
|
||||
HMODULE handle = nullptr;
|
||||
ScopedModule() = default;
|
||||
explicit ScopedModule(HMODULE h) : handle(h) {}
|
||||
~ScopedModule() {
|
||||
if (handle) {
|
||||
FreeLibrary(handle);
|
||||
}
|
||||
}
|
||||
ScopedModule(const ScopedModule&) = delete;
|
||||
ScopedModule& operator=(const ScopedModule&) = delete;
|
||||
explicit operator bool() const { return handle != nullptr; }
|
||||
HMODULE get() const { return handle; }
|
||||
};
|
||||
|
||||
LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
|
||||
if (message == kMessage) {
|
||||
g_received_message = wparam == kPayload;
|
||||
return 0;
|
||||
}
|
||||
return g_def_window_proc(window, message, wparam, lparam);
|
||||
}
|
||||
|
||||
void CALLBACK notification_callback(BOOLEAN, PVOID) {
|
||||
g_callback_called.store(true);
|
||||
}
|
||||
|
||||
HMODULE load_bridge(const wchar_t* dll) {
|
||||
wchar_t executable[MAX_PATH];
|
||||
const DWORD length = GetModuleFileNameW(nullptr, executable, MAX_PATH);
|
||||
if (!length || length == MAX_PATH) {
|
||||
return nullptr;
|
||||
}
|
||||
const std::wstring path(executable, length);
|
||||
const auto expected = path.substr(0, path.find_last_of(L"\\/") + 1) + dll;
|
||||
HMODULE module = LoadLibraryW(expected.c_str());
|
||||
if (!module) {
|
||||
std::fwprintf(stderr, L"FAIL: could not load built bridge %ls (error %lu)\n",
|
||||
expected.c_str(), GetLastError());
|
||||
return nullptr;
|
||||
}
|
||||
wchar_t actual[MAX_PATH];
|
||||
const DWORD actual_length = GetModuleFileNameW(module, actual, MAX_PATH);
|
||||
if (!actual_length || actual_length == MAX_PATH) {
|
||||
const DWORD err = GetLastError();
|
||||
FreeLibrary(module);
|
||||
std::fwprintf(stderr, L"FAIL: could not query path for bridge %ls (error %lu)\n",
|
||||
expected.c_str(), err);
|
||||
return nullptr;
|
||||
}
|
||||
if (CompareStringOrdinal(expected.c_str(), -1, actual, -1, TRUE) != CSTR_EQUAL) {
|
||||
FreeLibrary(module);
|
||||
std::fwprintf(stderr, L"FAIL: bridge %ls resolved to unexpected path %ls\n",
|
||||
expected.c_str(), actual);
|
||||
return nullptr;
|
||||
}
|
||||
return module;
|
||||
}
|
||||
|
||||
template<typename Function>
|
||||
Function lookup(HMODULE module, const char* name) {
|
||||
return std::bit_cast<Function>(GetProcAddress(module, name));
|
||||
}
|
||||
|
||||
bool test_window() {
|
||||
const ScopedModule window(load_bridge(L"ext-ms-win-rtcore-ntuser-window-l1-1-0.dll"));
|
||||
const ScopedModule window_ansi(load_bridge(L"ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll"));
|
||||
const ScopedModule message(load_bridge(L"ext-ms-win-rtcore-ntuser-message-l1-1-0.dll"));
|
||||
const ScopedModule message_ansi(load_bridge(L"ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0.dll"));
|
||||
if (!window || !window_ansi || !message || !message_ansi) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto show = lookup<decltype(&ShowWindow)>(window.get(), "ShowWindow");
|
||||
const auto create = lookup<decltype(&CreateWindowExA)>(window_ansi.get(), "CreateWindowExA");
|
||||
const auto register_class = lookup<decltype(&RegisterClassExA)>(window_ansi.get(), "RegisterClassExA");
|
||||
g_def_window_proc = lookup<decltype(&DefWindowProcA)>(window_ansi.get(), "DefWindowProcA");
|
||||
const auto translate = lookup<decltype(&TranslateMessage)>(message.get(), "TranslateMessage");
|
||||
const auto peek = lookup<decltype(&PeekMessageA)>(message_ansi.get(), "PeekMessageA");
|
||||
const auto dispatch = lookup<decltype(&DispatchMessageA)>(message_ansi.get(), "DispatchMessageA");
|
||||
if (!show || !create || !register_class || !g_def_window_proc || !translate || !peek || !dispatch) {
|
||||
return false;
|
||||
}
|
||||
|
||||
WNDCLASSEXA cls{};
|
||||
cls.cbSize = sizeof(cls);
|
||||
cls.lpfnWndProc = window_proc;
|
||||
cls.hInstance = GetModuleHandleW(nullptr);
|
||||
cls.lpszClassName = "BetterXenBridgeConformance";
|
||||
if (!register_class(&cls)) {
|
||||
return false;
|
||||
}
|
||||
const HWND hwnd = create(0, cls.lpszClassName, "BetterXen Win32 Bridge", WS_OVERLAPPEDWINDOW,
|
||||
0, 0, 100, 100, nullptr, nullptr, cls.hInstance, nullptr);
|
||||
if (hwnd) {
|
||||
show(hwnd, SW_HIDE);
|
||||
if (!IsWindowVisible(hwnd) && PostMessageA(hwnd, kMessage, kPayload, 0)) {
|
||||
MSG msg{};
|
||||
while (!g_received_message && peek(&msg, hwnd, 0, 0, PM_REMOVE)) {
|
||||
translate(&msg);
|
||||
dispatch(&msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
const bool destroyed = hwnd && DestroyWindow(hwnd);
|
||||
const bool unregistered = UnregisterClassA(cls.lpszClassName, cls.hInstance);
|
||||
return g_received_message && destroyed && unregistered;
|
||||
}
|
||||
|
||||
using RegisterNotification = ULONG (WINAPI*)(decltype(¬ification_callback), PVOID, PVOID*);
|
||||
using UnregisterNotification = VOID (WINAPI*)(PVOID);
|
||||
|
||||
struct PsmLogCounts {
|
||||
size_t state_registered = 0;
|
||||
size_t constrained_registered = 0;
|
||||
size_t state_unregistered = 0;
|
||||
size_t state_foreign = 0;
|
||||
size_t state_unknown = 0;
|
||||
size_t constrained_unregistered = 0;
|
||||
size_t constrained_foreign = 0;
|
||||
size_t constrained_unknown = 0;
|
||||
};
|
||||
|
||||
int64_t query_file_size(const char* path) {
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) {
|
||||
return 0;
|
||||
}
|
||||
LARGE_INTEGER size{};
|
||||
const bool ok = GetFileSizeEx(f, &size) != 0;
|
||||
CloseHandle(f);
|
||||
return ok && size.QuadPart > 0 ? size.QuadPart : 0;
|
||||
}
|
||||
|
||||
bool count_psm_log_events(const char* path, int64_t start_offset, PsmLogCounts& out) {
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) {
|
||||
std::fprintf(stderr, "FAIL: could not open PSM log %s (error %lu)\n", path, GetLastError());
|
||||
return false;
|
||||
}
|
||||
LARGE_INTEGER size{};
|
||||
if (!GetFileSizeEx(f, &size) || size.QuadPart < start_offset) {
|
||||
CloseHandle(f);
|
||||
std::fprintf(stderr, "FAIL: invalid PSM log size for %s\n", path);
|
||||
return false;
|
||||
}
|
||||
const int64_t delta = size.QuadPart - start_offset;
|
||||
if (delta <= 0 || delta > (64LL << 20)) {
|
||||
CloseHandle(f);
|
||||
std::fprintf(stderr, "FAIL: unexpected PSM log delta (%lld bytes)\n",
|
||||
static_cast<long long>(delta));
|
||||
return false;
|
||||
}
|
||||
LARGE_INTEGER seek{};
|
||||
seek.QuadPart = start_offset;
|
||||
if (!SetFilePointerEx(f, seek, nullptr, FILE_BEGIN)) {
|
||||
CloseHandle(f);
|
||||
return false;
|
||||
}
|
||||
std::string data(static_cast<size_t>(delta), '\0');
|
||||
size_t total_read = 0;
|
||||
while (total_read < data.size()) {
|
||||
DWORD chunk = 0;
|
||||
const DWORD want = static_cast<DWORD>(data.size() - total_read);
|
||||
if (!ReadFile(f, data.data() + total_read, want, &chunk, nullptr) || chunk == 0) {
|
||||
break;
|
||||
}
|
||||
total_read += chunk;
|
||||
}
|
||||
CloseHandle(f);
|
||||
data.resize(total_read);
|
||||
|
||||
size_t pos = 0;
|
||||
while (pos < data.size()) {
|
||||
size_t nl = data.find('\n', pos);
|
||||
if (nl == std::string::npos) {
|
||||
nl = data.size();
|
||||
}
|
||||
const std::string line = data.substr(pos, nl - pos);
|
||||
pos = nl + 1;
|
||||
|
||||
if (line.find("\"sub\":\"win32_bridge\"") == std::string::npos) {
|
||||
continue;
|
||||
}
|
||||
if (line.find("\"event\":\"RegisterAppStateChangeNotification\"") != std::string::npos &&
|
||||
line.find("\"detail\":\"registered_offline\"") != std::string::npos) {
|
||||
++out.state_registered;
|
||||
} else if (line.find("\"event\":\"RegisterAppConstrainedChangeNotification\"") != std::string::npos &&
|
||||
line.find("\"detail\":\"registered_offline\"") != std::string::npos) {
|
||||
++out.constrained_registered;
|
||||
} else if (line.find("\"event\":\"UnregisterAppStateChangeNotification\"") != std::string::npos) {
|
||||
if (line.find("\"detail\":\"unregistered\"") != std::string::npos) {
|
||||
++out.state_unregistered;
|
||||
} else if (line.find("\"detail\":\"foreign_token\"") != std::string::npos) {
|
||||
++out.state_foreign;
|
||||
} else if (line.find("\"detail\":\"unknown_token\"") != std::string::npos) {
|
||||
++out.state_unknown;
|
||||
}
|
||||
} else if (line.find("\"event\":\"UnregisterAppConstrainedChangeNotification\"") != std::string::npos) {
|
||||
if (line.find("\"detail\":\"unregistered\"") != std::string::npos) {
|
||||
++out.constrained_unregistered;
|
||||
} else if (line.find("\"detail\":\"foreign_token\"") != std::string::npos) {
|
||||
++out.constrained_foreign;
|
||||
} else if (line.find("\"detail\":\"unknown_token\"") != std::string::npos) {
|
||||
++out.constrained_unknown;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool test_psm() {
|
||||
char log_path[MAX_PATH]{};
|
||||
bool created_temp_log = false;
|
||||
const DWORD existing_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
|
||||
if (existing_len == 0 || existing_len >= sizeof(log_path)) {
|
||||
char temp_dir[MAX_PATH]{};
|
||||
const DWORD dir_len = GetTempPathA(sizeof(temp_dir), temp_dir);
|
||||
if (dir_len == 0 || dir_len >= sizeof(temp_dir) ||
|
||||
GetTempFileNameA(temp_dir, "bxp", 0, log_path) == 0) {
|
||||
std::fprintf(stderr, "FAIL: could not create temporary PSM log file\n");
|
||||
return false;
|
||||
}
|
||||
if (!SetEnvironmentVariableA("BX_LOG_FILE", log_path)) {
|
||||
DeleteFileA(log_path);
|
||||
return false;
|
||||
}
|
||||
created_temp_log = true;
|
||||
}
|
||||
const int64_t log_start_offset = query_file_size(log_path);
|
||||
|
||||
bool ok = false;
|
||||
{
|
||||
const ScopedModule state_dll(load_bridge(L"api-ms-win-core-psm-appnotify-l1-1-0.dll"));
|
||||
const ScopedModule constrained_dll(load_bridge(L"api-ms-win-core-psm-appnotify-l1-1-1.dll"));
|
||||
if (state_dll && constrained_dll) {
|
||||
const auto register_state = lookup<RegisterNotification>(
|
||||
state_dll.get(), "RegisterAppStateChangeNotification");
|
||||
const auto unregister_state = lookup<UnregisterNotification>(
|
||||
state_dll.get(), "UnregisterAppStateChangeNotification");
|
||||
const auto register_constrained = lookup<RegisterNotification>(
|
||||
constrained_dll.get(), "RegisterAppConstrainedChangeNotification");
|
||||
const auto unregister_constrained = lookup<UnregisterNotification>(
|
||||
constrained_dll.get(), "UnregisterAppConstrainedChangeNotification");
|
||||
if (register_state && unregister_state && register_constrained && unregister_constrained) {
|
||||
PVOID token = reinterpret_cast<PVOID>(1);
|
||||
PVOID token2 = reinterpret_cast<PVOID>(1);
|
||||
const bool args_ok =
|
||||
register_state(nullptr, nullptr, &token) == ERROR_INVALID_PARAMETER && !token &&
|
||||
register_state(notification_callback, nullptr, nullptr) == ERROR_INVALID_PARAMETER &&
|
||||
register_constrained(nullptr, nullptr, &token2) == ERROR_INVALID_PARAMETER && !token2 &&
|
||||
register_constrained(notification_callback, nullptr, nullptr) == ERROR_INVALID_PARAMETER;
|
||||
|
||||
constexpr size_t kThreads = 4;
|
||||
constexpr size_t kRegistrationsPerThread = 16;
|
||||
constexpr size_t kPerFamily = kThreads * kRegistrationsPerThread;
|
||||
struct Tokens {
|
||||
PVOID state{};
|
||||
PVOID constrained{};
|
||||
};
|
||||
std::array<std::array<Tokens, kRegistrationsPerThread>, kThreads> tokens{};
|
||||
std::array<std::thread, kThreads> workers;
|
||||
std::atomic<bool> success{args_ok};
|
||||
for (size_t i = 0; i < workers.size(); ++i) {
|
||||
workers[i] = std::thread([&, i] {
|
||||
for (auto& entry : tokens[i]) {
|
||||
const auto state_status =
|
||||
register_state(notification_callback, &entry, &entry.state);
|
||||
const auto constrained_status =
|
||||
register_constrained(notification_callback, &entry, &entry.constrained);
|
||||
if (state_status != ERROR_SUCCESS || constrained_status != ERROR_SUCCESS ||
|
||||
!entry.state || !entry.constrained) {
|
||||
success.store(false);
|
||||
}
|
||||
// Cross-family unregister calls must log foreign_token and leave live tokens intact.
|
||||
unregister_constrained(entry.state);
|
||||
unregister_state(entry.constrained);
|
||||
// Valid unregister followed by duplicate unregister on each family.
|
||||
unregister_state(entry.state);
|
||||
unregister_state(entry.state);
|
||||
unregister_constrained(entry.constrained);
|
||||
unregister_constrained(entry.constrained);
|
||||
}
|
||||
});
|
||||
}
|
||||
for (auto& worker : workers) {
|
||||
worker.join();
|
||||
}
|
||||
|
||||
// Null and arbitrary invalid tokens must classify as unknown_token, not foreign_token.
|
||||
unregister_state(nullptr);
|
||||
unregister_constrained(reinterpret_cast<PVOID>(0x1234));
|
||||
|
||||
std::unordered_set<PVOID> seen;
|
||||
bool unique_ok = true;
|
||||
for (const auto& entries : tokens) {
|
||||
for (const auto& entry : entries) {
|
||||
if (!seen.insert(entry.state).second ||
|
||||
!seen.insert(entry.constrained).second) {
|
||||
unique_ok = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
PsmLogCounts counts{};
|
||||
const bool log_read_ok = count_psm_log_events(log_path, log_start_offset, counts);
|
||||
const bool counts_ok = log_read_ok &&
|
||||
counts.state_registered == kPerFamily &&
|
||||
counts.constrained_registered == kPerFamily &&
|
||||
counts.state_unregistered == kPerFamily &&
|
||||
counts.state_foreign == kPerFamily &&
|
||||
counts.state_unknown == kPerFamily + 1 &&
|
||||
counts.constrained_unregistered == kPerFamily &&
|
||||
counts.constrained_foreign == kPerFamily &&
|
||||
counts.constrained_unknown == kPerFamily + 1;
|
||||
if (log_read_ok && !counts_ok) {
|
||||
std::fprintf(
|
||||
stderr,
|
||||
"FAIL: PSM log count mismatch: state(reg=%zu unreg=%zu foreign=%zu unknown=%zu) "
|
||||
"constrained(reg=%zu unreg=%zu foreign=%zu unknown=%zu)\n",
|
||||
counts.state_registered, counts.state_unregistered,
|
||||
counts.state_foreign, counts.state_unknown,
|
||||
counts.constrained_registered, counts.constrained_unregistered,
|
||||
counts.constrained_foreign, counts.constrained_unknown);
|
||||
}
|
||||
|
||||
ok = success.load() && unique_ok && !g_callback_called.load() && counts_ok;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (created_temp_log) {
|
||||
DeleteFileA(log_path);
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
if (!test_window()) {
|
||||
std::fprintf(stderr, "FAIL: Win32 bridge window or message pump (error %lu)\n", GetLastError());
|
||||
return 1;
|
||||
}
|
||||
if (!test_psm()) {
|
||||
std::fprintf(stderr, "FAIL: PSM bridge registration lifecycle\n");
|
||||
return 2;
|
||||
}
|
||||
std::puts("PASS: test_win32_bridge (hidden window, message pump, 128 PSM registrations, per-event log verified)");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_xmem_physical main.cpp)
|
||||
target_include_directories(test_xmem_physical PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_link_libraries(test_xmem_physical PRIVATE xmem kernel32)
|
||||
@@ -0,0 +1,148 @@
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
|
||||
#include "bx_xmem_internal.h"
|
||||
|
||||
extern "C" {
|
||||
PVOID WINAPI XMemAllocDefault(SIZE_T, uint64_t);
|
||||
VOID WINAPI XMemFreeDefault(PVOID, uint64_t);
|
||||
BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
|
||||
BOOL WINAPI XMemFreePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
|
||||
PVOID WINAPI XMemMapPhysicalPages(PVOID, SIZE_T, uint64_t, PULONG_PTR);
|
||||
PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID, SIZE_T, uint64_t, PULONG_PTR);
|
||||
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
|
||||
}
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
std::fprintf(stderr, "xmem physical:%d: %s (Win32 error %lu)\n", \
|
||||
__LINE__, #condition, static_cast<unsigned long>(GetLastError())); \
|
||||
return false; \
|
||||
} \
|
||||
} while (false)
|
||||
|
||||
bool check_aliases(SIZE_T page_size, uint64_t flags) {
|
||||
bx_xmem_stats_t stats{};
|
||||
CHECK(XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
|
||||
CHECK(stats.allocated_physical_bytes == 0);
|
||||
|
||||
SIZE_T count = 2;
|
||||
ULONG_PTR pages[2]{};
|
||||
// Invalid flags must be rejected cleanly before touching stats or tags.
|
||||
CHECK(!XMemAllocatePhysicalPages(&count, pages, 0x12345));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
CHECK(XMemAllocatePhysicalPages(&count, pages, flags));
|
||||
CHECK(count == 2 && pages[0] && pages[1] && pages[0] != pages[1]);
|
||||
|
||||
// Working-set statistics and internal stats must both reflect physical pages.
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.allocated_physical_bytes == count * page_size);
|
||||
CHECK(stats.peak_committed_bytes >= count * page_size);
|
||||
bx_xmem_stats_t ws_stats{};
|
||||
CHECK(XMemGetWorkingSetStatistics(&ws_stats, sizeof(ws_stats)));
|
||||
CHECK(ws_stats.allocated_physical_bytes == count * page_size);
|
||||
|
||||
// Shared title budget cap: existing physical pages must block both full-cap
|
||||
// physical and full-cap heap allocations without allocating gigabytes.
|
||||
SIZE_T cap_pages = static_cast<SIZE_T>(stats.title_limit_bytes / page_size);
|
||||
CHECK(!XMemAllocatePhysicalPages(&cap_pages, pages, flags));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
CHECK(!XMemAllocDefault(static_cast<SIZE_T>(stats.title_limit_bytes), 0));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.allocated_physical_bytes == count * page_size);
|
||||
|
||||
CHECK(!XMemMapPhysicalPages(nullptr, count, 0x12345, pages));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
auto* linear = static_cast<BYTE*>(XMemMapPhysicalPages(nullptr, count, flags, pages));
|
||||
CHECK(linear && reinterpret_cast<uintptr_t>(linear) % page_size == 0);
|
||||
ULONG_PTR reversed[] = {pages[1], pages[0]};
|
||||
auto* scatter = static_cast<BYTE*>(
|
||||
XMemMapPhysicalPagesScatter(nullptr, count, flags, reversed));
|
||||
CHECK(scatter && scatter != linear && reinterpret_cast<uintptr_t>(scatter) % page_size == 0);
|
||||
|
||||
linear[7] = 0x41;
|
||||
linear[page_size + 7] = 0x73;
|
||||
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
|
||||
scatter[page_size + 30] = 0xf2;
|
||||
CHECK(linear[30] == 0xf2);
|
||||
|
||||
// Duplicate tags are valid when mapping (intra-span ring-buffer/tile aliasing).
|
||||
ULONG_PTR dup_map[] = {pages[0], pages[0]};
|
||||
auto* dup_view = static_cast<BYTE*>(
|
||||
XMemMapPhysicalPagesScatter(nullptr, count, flags, dup_map));
|
||||
CHECK(dup_view && reinterpret_cast<uintptr_t>(dup_view) % page_size == 0);
|
||||
dup_view[13] = 0x9b;
|
||||
CHECK(dup_view[page_size + 13] == 0x9b && linear[13] == 0x9b);
|
||||
bx_xmem_region_info_t dup0{};
|
||||
bx_xmem_region_info_t dup1{};
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view), &dup0));
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view + page_size), &dup1));
|
||||
CHECK(dup0.physical_tag == pages[0] && dup1.physical_tag == pages[0]);
|
||||
CHECK(XMemMapPhysicalPagesScatter(dup_view, count, flags, nullptr) == dup_view);
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view), &dup0));
|
||||
|
||||
bx_xmem_region_info_t first{};
|
||||
bx_xmem_region_info_t alias{};
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(linear + 7), &first));
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter + page_size + 7), &alias));
|
||||
CHECK(first.base_va == reinterpret_cast<uintptr_t>(linear));
|
||||
CHECK(alias.base_va == reinterpret_cast<uintptr_t>(scatter + page_size));
|
||||
CHECK(alias.physical_tag == first.physical_tag && first.physical_tag == pages[0]);
|
||||
CHECK(first.size_bytes == page_size && alias.page_size_bytes == page_size);
|
||||
CHECK(first.protect_flags == PAGE_READWRITE && first.mem_type_flags == MEM_MAPPED);
|
||||
|
||||
// Rejected frees (stale or duplicate tags) must fail without modifying
|
||||
// page_array or disturbing live mappings.
|
||||
ULONG_PTR stale[] = {pages[0], 0};
|
||||
CHECK(!XMemFreePhysicalPages(&count, stale, flags));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER && stale[0] == pages[0] && stale[1] == 0);
|
||||
CHECK(linear[7] == 0x41);
|
||||
ULONG_PTR dup_free[] = {pages[0], pages[0]};
|
||||
CHECK(!XMemFreePhysicalPages(&count, dup_free, flags));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER
|
||||
&& dup_free[0] == pages[0] && dup_free[1] == pages[0]);
|
||||
CHECK(linear[7] == 0x41 && scatter[7] == 0x73);
|
||||
|
||||
CHECK(!XMemMapPhysicalPagesScatter(nullptr, count, flags, stale));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
CHECK(!XMemMapPhysicalPages(linear, count, flags, pages));
|
||||
CHECK(linear[7] == 0x41 && scatter[7] == 0x73);
|
||||
|
||||
// Partial/over-wide unmap must fail cleanly and leave mapped pages intact.
|
||||
CHECK(!XMemMapPhysicalPagesScatter(scatter, count + 1, flags, nullptr));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
|
||||
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
|
||||
|
||||
// Exact unmap succeeds; repeating unmap on the now-empty span must fail.
|
||||
CHECK(XMemMapPhysicalPagesScatter(scatter, count, flags, nullptr) == scatter);
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
|
||||
CHECK(!XMemMapPhysicalPagesScatter(scatter, count, flags, nullptr));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
CHECK(XMemMapPhysicalPagesScatter(scatter, count, flags, reversed) == scatter);
|
||||
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
|
||||
CHECK(XMemFreePhysicalPages(&count, pages, flags));
|
||||
CHECK(!pages[0] && !pages[1]);
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(linear), &first));
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
|
||||
CHECK(!XMemMapPhysicalPages(nullptr, count, flags, reversed));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.allocated_physical_bytes == 0);
|
||||
return true;
|
||||
}
|
||||
|
||||
int main() {
|
||||
if (!check_aliases(64 * 1024, 0) || !check_aliases(2 * 1024 * 1024, 2 * 1024 * 1024)) {
|
||||
return 1;
|
||||
}
|
||||
std::puts("test_xmem_physical: passed");
|
||||
}
|
||||
Reference in new issue
Block a user