mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 19:30:43 +00:00
Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7d7249ee8b | ||
|
|
d0395a61da | ||
|
|
eec56dd028 | ||
|
|
486f7b197f | ||
|
|
390e85fc8d | ||
|
|
bfa80dee8b | ||
|
|
829a94fa2f | ||
|
|
02b8924de7 | ||
|
|
925311e852 | ||
|
|
f7194d0255 | ||
|
|
7ea4f1f6ca | ||
|
|
bd8edd8f70 | ||
|
|
058bc981dc | ||
|
|
a8c4dbb77e | ||
|
|
d8b83818c1 | ||
|
|
0a2544cd51 | ||
|
|
0082d16b1e | ||
|
|
4c7f1c5aff | ||
|
|
d72350c854 | ||
|
|
cee636193a | ||
|
|
134eee3a28 | ||
|
|
43f32acb82 | ||
|
|
ab696f1f07 | ||
|
|
19c240edd5 |
No files matched your search
@@ -10,6 +10,12 @@ 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).
|
||||
- Added a BetterXen-only DirectStorage conformance interface for asynchronous uncompressed file and memory transfers, status arrays, and completion events in `XCRDAPI.dll` (#413).
|
||||
- Implemented offline `xgameruntime.dll` task queues and async completion, local user handles, synthetic game-license queries, console identity, and bottle-local storage (#418). Added a synthetic conformance executable for Lockhart and Anaconda launches. Only the marked conformance title receives an active synthetic SKU. The build also produces an unmarked control with the same executable name. Queue shutdown delivers accepted callbacks, and bottle-local storage is keyed by executable path.
|
||||
- `xg_xs.dll` computes linear 2D layouts for `R8G8B8A8` and BC1 through BC7 (`XGCreateTextureComputer`, `XGSuggestSwizzleMode`, and COM `IXGTextureAddressComputer`). Row pitch uses the public D3D12 256-byte alignment and each subresource is placed on the public 512-byte alignment. `GetResourceLayout` reports that aligned allocation span in `total_bytes` (512 for a 1x1 RGBA8 texture) and a separate D3D12-style `copy_end` on each footprint (4 for that same texture). Sizes are overflow-checked, null pointers return `E_POINTER`, and copies stay inside the caller buffers. `SW_64KB_S`, `SW_64KB_D`, and `SW_64KB_R` return `E_NOTIMPL` and write no address. Synthetic `test_xg_xs.exe` checks hand-computed mip offsets, alignment, refcounts, and a byte-identical copy round trip. This is not an Xbox hardware result (#415).
|
||||
@@ -66,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()),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
+108
-24
@@ -1,20 +1,53 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
/* Track E (M1-E2 / M5): AcpHal.dll SHAPE Audio Coprocessor HAL shim. */
|
||||
namespace {
|
||||
class AcpHal final : public IUnknown {
|
||||
LONG refs = 1;
|
||||
public:
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (iid != IID_IUnknown) return E_NOINTERFACE;
|
||||
AddRef();
|
||||
*out = this;
|
||||
return S_OK;
|
||||
}
|
||||
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
|
||||
ULONG WINAPI Release() override {
|
||||
ULONG left = InterlockedDecrement(&refs);
|
||||
if (!left) delete this;
|
||||
return left;
|
||||
}
|
||||
};
|
||||
|
||||
// Sorted synthetic address ranges. Zero is reserved for failed lookups.
|
||||
struct Allocation {
|
||||
uintptr_t va;
|
||||
uint32_t base, size;
|
||||
Allocation* next;
|
||||
};
|
||||
Allocation* allocations;
|
||||
std::mutex heap_lock;
|
||||
uint64_t capacity = 0;
|
||||
uint64_t used = 0;
|
||||
bool heap_created = false;
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT WINAPI AcpHalCreate(void** out_hal) {
|
||||
BX_STUB_LOG("AcpHal.dll", "AcpHalCreate");
|
||||
if (out_hal) *out_hal = nullptr;
|
||||
return E_NOTIMPL;
|
||||
HRESULT WINAPI AcpHalCreate(void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = new (std::nothrow) AcpHal;
|
||||
return *out ? S_OK : E_OUTOFMEMORY;
|
||||
}
|
||||
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void* /*desc*/) {
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void*) {
|
||||
BX_STUB_LOG("AcpHal.dll", "AcpHalAllocateShapeContexts");
|
||||
return S_OK;
|
||||
}
|
||||
@@ -24,35 +57,86 @@ HRESULT WINAPI AcpHalReleaseShapeContexts(void) {
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI ApuCreateHeap(uint32_t /*cached_size*/, uint32_t /*non_cached_size*/) {
|
||||
BX_STUB_LOG("AcpHal.dll", "ApuCreateHeap");
|
||||
HRESULT WINAPI ApuCreateHeap(uint32_t cached, uint32_t non_cached) {
|
||||
std::lock_guard guard(heap_lock);
|
||||
if (allocations) return HRESULT_FROM_WIN32(ERROR_BUSY);
|
||||
// Invariant: allocations == nullptr implies used == 0; reset explicitly.
|
||||
used = 0;
|
||||
capacity = uint64_t(cached) + non_cached;
|
||||
heap_created = true;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI ApuAlloc(void** out_va, uint32_t* out_apu_addr, uint32_t size, uint32_t alignment) {
|
||||
HRESULT WINAPI ApuAlloc(void** va, uint32_t* apu, uint32_t size, uint32_t alignment) {
|
||||
if (va) *va = nullptr;
|
||||
if (apu) *apu = 0;
|
||||
if (!va && !apu) return E_POINTER;
|
||||
if (alignment && (alignment & (alignment - 1))) return E_INVALIDARG;
|
||||
if (alignment < 64) alignment = 64;
|
||||
void* p = _aligned_malloc(size ? size : 64, alignment);
|
||||
if (out_va) *out_va = p;
|
||||
if (out_apu_addr) *out_apu_addr = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(p) & 0xFFFFFFFFu);
|
||||
return p ? S_OK : E_OUTOFMEMORY;
|
||||
if (!size) size = 64;
|
||||
std::lock_guard guard(heap_lock);
|
||||
if (!heap_created || size > capacity - used) return E_OUTOFMEMORY;
|
||||
uint64_t base = alignment;
|
||||
Allocation** link = &allocations;
|
||||
while (*link && base + size > (*link)->base) {
|
||||
const uint64_t end = uint64_t((*link)->base) + (*link)->size;
|
||||
base = (end + alignment - 1) & ~(uint64_t(alignment) - 1);
|
||||
link = &(*link)->next;
|
||||
}
|
||||
if (base + size > (uint64_t{1} << 32)) return E_OUTOFMEMORY;
|
||||
void* ptr = _aligned_malloc(size, alignment);
|
||||
if (!ptr) return E_OUTOFMEMORY;
|
||||
auto* entry = new (std::nothrow) Allocation{reinterpret_cast<uintptr_t>(ptr),
|
||||
static_cast<uint32_t>(base), size, *link};
|
||||
if (!entry) {
|
||||
_aligned_free(ptr);
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
*link = entry;
|
||||
used += size;
|
||||
if (va) *va = ptr;
|
||||
if (apu) *apu = entry->base;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI ApuFree(void* va) {
|
||||
if (va) _aligned_free(va);
|
||||
return S_OK;
|
||||
if (!va) return S_OK;
|
||||
std::lock_guard guard(heap_lock);
|
||||
for (auto** link = &allocations; *link; link = &(*link)->next) {
|
||||
auto* entry = *link;
|
||||
if (entry->va != reinterpret_cast<uintptr_t>(va)) continue;
|
||||
*link = entry->next;
|
||||
used -= entry->size;
|
||||
_aligned_free(va);
|
||||
delete entry;
|
||||
return S_OK;
|
||||
}
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
BOOL WINAPI ApuIsVirtualAddressValid(const void* va, uint32_t /*size*/) {
|
||||
return va != nullptr;
|
||||
static uint32_t lookup_va(const void* va, uint32_t size) {
|
||||
const auto address = reinterpret_cast<uintptr_t>(va);
|
||||
std::lock_guard guard(heap_lock);
|
||||
for (auto* entry = allocations; entry; entry = entry->next) {
|
||||
const auto offset = address - entry->va;
|
||||
if (offset < entry->size && size <= entry->size - offset)
|
||||
return entry->base + static_cast<uint32_t>(offset);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void* WINAPI ApuMapApuAddress(uint32_t /*apu_addr*/) {
|
||||
BX_STUB_LOG("AcpHal.dll", "ApuMapApuAddress");
|
||||
BOOL WINAPI ApuIsVirtualAddressValid(const void* va, uint32_t size) {
|
||||
return lookup_va(va, size) != 0;
|
||||
}
|
||||
|
||||
void* WINAPI ApuMapApuAddress(uint32_t address) {
|
||||
std::lock_guard guard(heap_lock);
|
||||
for (auto* entry = allocations; entry && entry->base <= address; entry = entry->next) {
|
||||
const auto offset = address - entry->base;
|
||||
if (offset < entry->size) return reinterpret_cast<void*>(entry->va + offset);
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
uint32_t WINAPI ApuMapVirtualAddress(const void* va) {
|
||||
return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(va) & 0xFFFFFFFFu);
|
||||
uint32_t WINAPI ApuMapVirtualAddress(const void* va) { return lookup_va(va, 1); }
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
+34
-14
@@ -1,21 +1,41 @@
|
||||
#include <windows.h>
|
||||
#include <cstdint>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
/* Track E (M1-E2 / M5): chad.dll Xbox DSP command shim. */
|
||||
#define BX_DSP_CONNECTIONS
|
||||
#include "command_ring.h"
|
||||
|
||||
extern "C" {
|
||||
// Validate and record the caller's stream limit; the synthetic command ring
|
||||
// holds a fixed 32-packet backlog independent of stream count.
|
||||
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(uint32_t max_streams, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (!max_streams) return E_INVALIDARG;
|
||||
return connect(out, max_streams);
|
||||
}
|
||||
HRESULT WINAPI XDspDisconnect(void* handle) { return disconnect(handle); }
|
||||
|
||||
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(uint32_t /*max_streams*/, void** out_handle) {
|
||||
BX_STUB_LOG("chad.dll", "XDspConnectWithMaximumStreamLimit");
|
||||
if (out_handle) *out_handle = reinterpret_cast<void*>(0x5001);
|
||||
HRESULT WINAPI XDspActivate(void* handle) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(handle);
|
||||
if (!c) return E_HANDLE;
|
||||
c->active = true;
|
||||
// chad has no result export. Active DSP commands complete synchronously.
|
||||
while (c->queue.count) c->queue.pop();
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XDspDisconnect(void* /*handle*/) { return S_OK; }
|
||||
HRESULT WINAPI XDspActivate(void* /*handle*/) { return S_OK; }
|
||||
HRESULT WINAPI XDspDeactivate(void* /*handle*/) { return S_OK; }
|
||||
HRESULT WINAPI XDspSubmitCommand(void* /*handle*/, const void* /*cmd*/, uint32_t /*size*/) { return S_OK; }
|
||||
HRESULT WINAPI XDspDeactivate(void* handle) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(handle);
|
||||
if (!c) return E_HANDLE;
|
||||
c->active = false;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
HRESULT WINAPI XDspSubmitCommand(void* handle, const void* cmd, uint32_t size) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(handle);
|
||||
if (!c) return E_HANDLE;
|
||||
const HRESULT hr = c->queue.push(cmd, size);
|
||||
if (SUCCEEDED(hr) && c->active) c->queue.pop();
|
||||
return hr;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
|
||||
namespace {
|
||||
// A synthetic command completes by returning its opaque bytes unchanged.
|
||||
struct CommandRing {
|
||||
struct Packet {
|
||||
uint32_t size;
|
||||
unsigned char bytes[1024];
|
||||
};
|
||||
std::array<Packet, 32> packets;
|
||||
unsigned head = 0, count = 0;
|
||||
|
||||
HRESULT push(const void* data, uint32_t size) {
|
||||
if (!data || !size || size > sizeof(Packet::bytes)) return E_INVALIDARG;
|
||||
if (count == packets.size()) return HRESULT_FROM_WIN32(ERROR_BUSY);
|
||||
auto& packet = packets[(head + count) % packets.size()];
|
||||
packet.size = size;
|
||||
std::memcpy(packet.bytes, data, size);
|
||||
++count;
|
||||
return S_OK;
|
||||
}
|
||||
void pop() {
|
||||
head = (head + 1) % packets.size();
|
||||
--count;
|
||||
}
|
||||
HRESULT read(void* data, uint32_t size) {
|
||||
if (!data) return E_POINTER;
|
||||
if (!count) return S_FALSE;
|
||||
const auto& packet = packets[head];
|
||||
if (size < packet.size) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
|
||||
std::memcpy(data, packet.bytes, packet.size);
|
||||
pop();
|
||||
return S_OK;
|
||||
}
|
||||
};
|
||||
|
||||
struct Connection {
|
||||
uintptr_t id;
|
||||
Connection* next;
|
||||
CommandRing queue;
|
||||
uint32_t max_streams = 0;
|
||||
bool active = false;
|
||||
};
|
||||
|
||||
// Each DLL owns its registry. An ID stays invalid after disconnect, including
|
||||
// when the allocator subsequently reuses the same Connection address.
|
||||
std::mutex connections_lock;
|
||||
Connection* connections;
|
||||
#ifdef BX_DSP_CONNECTIONS
|
||||
uintptr_t next_id = 2;
|
||||
#else
|
||||
uintptr_t next_id = 1;
|
||||
#endif
|
||||
|
||||
HRESULT connect(void** out, uint32_t max_streams = 0) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
std::lock_guard guard(connections_lock);
|
||||
if (next_id > UINTPTR_MAX - 2) return E_OUTOFMEMORY;
|
||||
auto* c = new (std::nothrow) Connection;
|
||||
if (!c) return E_OUTOFMEMORY;
|
||||
c->id = next_id;
|
||||
c->max_streams = max_streams;
|
||||
next_id += 2;
|
||||
c->next = connections;
|
||||
connections = c;
|
||||
*out = reinterpret_cast<void*>(c->id);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
// Caller holds connections_lock through the operation.
|
||||
Connection* lookup(void* handle) {
|
||||
for (auto* c = connections; c; c = c->next)
|
||||
if (c->id == reinterpret_cast<uintptr_t>(handle)) return c;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
HRESULT disconnect(void* handle) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
for (auto** link = &connections; *link; link = &(*link)->next) {
|
||||
auto* c = *link;
|
||||
if (c->id != reinterpret_cast<uintptr_t>(handle)) continue;
|
||||
*link = c->next;
|
||||
delete c;
|
||||
return S_OK;
|
||||
}
|
||||
return E_HANDLE;
|
||||
}
|
||||
}
|
||||
+15
-23
@@ -1,32 +1,24 @@
|
||||
#include <windows.h>
|
||||
#include <cstdint>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
/* Track E (M1-E2 / M5): xapu.dll APU command queue shim. */
|
||||
#include "command_ring.h"
|
||||
|
||||
extern "C" {
|
||||
HRESULT WINAPI XApuConnect(void** out) { return connect(out); }
|
||||
HRESULT WINAPI XApuDisconnect(void* conn) { return disconnect(conn); }
|
||||
|
||||
HRESULT WINAPI XApuConnect(void** out_conn) {
|
||||
BX_STUB_LOG("xapu.dll", "XApuConnect");
|
||||
if (out_conn) *out_conn = reinterpret_cast<void*>(0x4001);
|
||||
return S_OK;
|
||||
HRESULT WINAPI XApuEnqueueCommand(void* conn, const void* cmd, uint32_t size) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(conn);
|
||||
return c ? c->queue.push(cmd, size) : E_HANDLE;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XApuDisconnect(void* /*conn*/) {
|
||||
return S_OK;
|
||||
HRESULT WINAPI XApuDequeueResult(void* conn, void* result, uint32_t size) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(conn);
|
||||
return c ? c->queue.read(result, size) : E_HANDLE;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XApuEnqueueCommand(void* /*conn*/, const void* /*cmd*/, uint32_t /*size*/) {
|
||||
return S_OK;
|
||||
uint32_t WINAPI XApuGetResultCount(void* conn) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(conn);
|
||||
return c ? c->queue.count : 0;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XApuDequeueResult(void* /*conn*/, void* /*out_res*/, uint32_t /*size*/) {
|
||||
return S_FALSE;
|
||||
}
|
||||
|
||||
uint32_t WINAPI XApuGetResultCount(void* /*conn*/) {
|
||||
return 0u;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -1,13 +1,117 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <cstdint>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
/* Track E (M1-E2): GameInput.dll ordinal 1 (GameInputCreate) shim. */
|
||||
namespace {
|
||||
// GameInputCreate @1 exposes the legacy v0 COM layout.
|
||||
constexpr GUID game_input_v0 = {0x11be2a7e, 0x4254, 0x445a,
|
||||
{0x9c, 0x09, 0xff, 0xc4, 0x0f, 0x00, 0x69, 0x18}};
|
||||
using Callback = void (WINAPI*)();
|
||||
|
||||
extern "C" HRESULT WINAPI GameInputCreate(void** out_game_input) {
|
||||
BX_STUB_LOG("GameInput.dll", "GameInputCreate@1");
|
||||
if (out_game_input) {
|
||||
*out_game_input = nullptr;
|
||||
}
|
||||
template<class T>
|
||||
HRESULT unavailable(T* out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = {};
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
class GameInput final : public IUnknown {
|
||||
LONG refs = 0;
|
||||
public:
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (iid != IID_IUnknown && iid != game_input_v0) return E_NOINTERFACE;
|
||||
AddRef();
|
||||
*out = this;
|
||||
return S_OK;
|
||||
}
|
||||
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
|
||||
ULONG WINAPI Release() override { return InterlockedDecrement(&refs); }
|
||||
|
||||
virtual uint64_t WINAPI GetCurrentTimestamp() {
|
||||
return GetTickCount64() * 1000;
|
||||
}
|
||||
virtual HRESULT WINAPI GetCurrentReading(uint32_t, void*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 4, "GetCurrentReading");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI GetNextReading(void*, uint32_t, void*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 5, "GetNextReading");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI GetPreviousReading(void*, uint32_t, void*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 6, "GetPreviousReading");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI GetTemporalReading(uint64_t, void*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 7, "GetTemporalReading");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI RegisterReadingCallback(void*, uint32_t, float, void*, Callback, uint64_t* out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 8, "RegisterReadingCallback");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI RegisterDeviceCallback(void*, uint32_t, uint32_t, uint32_t, void*, Callback, uint64_t* out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 9, "RegisterDeviceCallback");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI RegisterSystemButtonCallback(void*, uint32_t, void*, Callback, uint64_t* out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 10, "RegisterSystemButtonCallback");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI RegisterKeyboardLayoutCallback(void*, void*, Callback, uint64_t* out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 11, "RegisterKeyboardLayoutCallback");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual void WINAPI StopCallback(uint64_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 12, "StopCallback");
|
||||
}
|
||||
virtual bool WINAPI UnregisterCallback(uint64_t, uint64_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 13, "UnregisterCallback");
|
||||
return false;
|
||||
}
|
||||
virtual HRESULT WINAPI CreateDispatcher(void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 14, "CreateDispatcher");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI CreateAggregateDevice(uint32_t, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 15, "CreateAggregateDevice");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI FindDeviceFromId(const void*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 16, "FindDeviceFromId");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI FindDeviceFromObject(IUnknown*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 17, "FindDeviceFromObject");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI FindDeviceFromPlatformHandle(HANDLE, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 18, "FindDeviceFromPlatformHandle");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI FindDeviceFromPlatformString(const wchar_t*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 19, "FindDeviceFromPlatformString");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI EnableOemDeviceSupport(uint16_t, uint16_t, uint8_t, uint8_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 20, "EnableOemDeviceSupport");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual void WINAPI SetFocusPolicy(uint32_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 21, "SetFocusPolicy");
|
||||
}
|
||||
};
|
||||
|
||||
GameInput singleton;
|
||||
}
|
||||
|
||||
extern "C" HRESULT WINAPI GameInputCreate(void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
singleton.AddRef();
|
||||
*out = &singleton;
|
||||
return S_OK;
|
||||
}
|
||||
@@ -13,6 +13,9 @@ CRITICAL_SECTION g_log_lock;
|
||||
bool g_log_lock_ready = false;
|
||||
HANDLE g_log_handle = INVALID_HANDLE_VALUE;
|
||||
PVOID g_veh_handle = nullptr;
|
||||
LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = nullptr;
|
||||
std::atomic_flag g_crash_logged{};
|
||||
std::atomic<bool> g_crash_in_flight{false};
|
||||
std::atomic<uint64_t> g_clwb_traps{0};
|
||||
bx_runtime_config_t g_config = {
|
||||
BX_ABI_VERSION,
|
||||
@@ -26,6 +29,11 @@ bx_runtime_config_t g_config = {
|
||||
};
|
||||
|
||||
void write_log_line(const char* line, size_t len) {
|
||||
// Pause regular logging while a terminal crash record is being emitted so
|
||||
// background threads cannot interleave with the unlocked crash WriteFile.
|
||||
if (g_crash_in_flight.load(std::memory_order_acquire)) {
|
||||
return;
|
||||
}
|
||||
if (g_log_lock_ready) {
|
||||
EnterCriticalSection(&g_log_lock);
|
||||
}
|
||||
@@ -45,90 +53,135 @@ void write_log_line(const char* line, size_t len) {
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Decode an x86-64 `clwb m8` instruction at `ip`.
|
||||
* Encoding: [legacy prefixes] 0x66 [REX 0x40..0x4F] 0x0F 0xAE /6 (mod != 3).
|
||||
* Returns total instruction length in bytes, or 0 if `ip` is not `clwb`.
|
||||
*/
|
||||
size_t decode_clwb_length(const uint8_t* ip) {
|
||||
constexpr size_t kMaxInstructionLength = 15;
|
||||
|
||||
size_t read_instruction(uint64_t rip, uint8_t (&bytes)[kMaxInstructionLength]) {
|
||||
HANDLE process = GetCurrentProcess();
|
||||
if (ReadProcessMemory(process, reinterpret_cast<LPCVOID>(rip),
|
||||
bytes, sizeof(bytes), nullptr)) {
|
||||
return sizeof(bytes);
|
||||
}
|
||||
|
||||
// A short instruction can end immediately before an inaccessible page.
|
||||
size_t size = 0;
|
||||
while (size < sizeof(bytes) &&
|
||||
ReadProcessMemory(process, reinterpret_cast<LPCVOID>(rip + size),
|
||||
&bytes[size], 1, nullptr)) {
|
||||
++size;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
// CLWB is 66 0F AE /6 with a memory operand. The address-size override
|
||||
// selects 32-bit addressing but leaves the ModRM/SIB displacement lengths intact.
|
||||
size_t decode_clwb_length(const uint8_t* ip, size_t size) {
|
||||
size_t idx = 0;
|
||||
bool has_66 = false;
|
||||
bool has_addr_override = false;
|
||||
|
||||
while (idx < 6) {
|
||||
uint8_t b = ip[idx];
|
||||
if (b == 0x66) {
|
||||
while (idx < size) {
|
||||
const uint8_t byte = ip[idx];
|
||||
if (byte == 0x66) {
|
||||
has_66 = true;
|
||||
idx++;
|
||||
} else if (b == 0x67) {
|
||||
has_addr_override = true;
|
||||
idx++;
|
||||
} else if (b == 0x26 || b == 0x2E || b == 0x36 || b == 0x3E || b == 0x64 || b == 0x65) {
|
||||
idx++;
|
||||
} else {
|
||||
} else if (byte != 0x67 && byte != 0x26 && byte != 0x2E &&
|
||||
byte != 0x36 && byte != 0x3E && byte != 0x64 && byte != 0x65) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
(void)has_addr_override;
|
||||
if (!has_66) {
|
||||
return 0;
|
||||
++idx;
|
||||
}
|
||||
|
||||
if ((ip[idx] & 0xF0) == 0x40) {
|
||||
idx++; /* Optional REX prefix */
|
||||
// x86-64 allows at most one REX prefix immediately before the opcode.
|
||||
if (idx < size && (ip[idx] & 0xF0) == 0x40) {
|
||||
++idx;
|
||||
}
|
||||
|
||||
if (ip[idx] != 0x0F || ip[idx + 1] != 0xAE) {
|
||||
if (!has_66 || size - idx < 3 || ip[idx] != 0x0F || ip[idx + 1] != 0xAE) {
|
||||
return 0;
|
||||
}
|
||||
idx += 2;
|
||||
|
||||
uint8_t modrm = ip[idx++];
|
||||
uint8_t mod = (modrm >> 6) & 0x3;
|
||||
uint8_t reg = (modrm >> 3) & 0x7;
|
||||
uint8_t rm = modrm & 0x7;
|
||||
|
||||
/* `clwb` requires memory operand (mod != 3) and opcode extension /6. */
|
||||
const uint8_t modrm = ip[idx++];
|
||||
const uint8_t mod = modrm >> 6;
|
||||
const uint8_t reg = (modrm >> 3) & 7;
|
||||
const uint8_t rm = modrm & 7;
|
||||
if (mod == 3 || reg != 6) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint8_t base = rm;
|
||||
if (rm == 4) {
|
||||
uint8_t sib = ip[idx++];
|
||||
if (mod == 0 && (sib & 0x7) == 5) {
|
||||
idx += 4; /* disp32 with no base */
|
||||
if (idx == size) {
|
||||
return 0;
|
||||
}
|
||||
} else if (mod == 0 && rm == 5) {
|
||||
idx += 4; /* RIP-relative disp32 */
|
||||
base = ip[idx++] & 7;
|
||||
}
|
||||
|
||||
if (mod == 1) {
|
||||
idx += 1; /* disp8 */
|
||||
} else if (mod == 2) {
|
||||
idx += 4; /* disp32 */
|
||||
idx += 1;
|
||||
} else if (mod == 2 || (mod == 0 && base == 5)) {
|
||||
idx += 4;
|
||||
}
|
||||
|
||||
return idx;
|
||||
return idx <= size ? idx : 0;
|
||||
}
|
||||
|
||||
bool is_adx_opcode(const uint8_t* ip) {
|
||||
bool is_adx_opcode(const uint8_t* ip, size_t size) {
|
||||
size_t idx = 0;
|
||||
bool has_66_or_f3 = false;
|
||||
while (idx < 4) {
|
||||
if (ip[idx] == 0x66 || ip[idx] == 0xF3) {
|
||||
has_66_or_f3 = true;
|
||||
idx++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
while (idx < size && (ip[idx] == 0x66 || ip[idx] == 0xF3)) {
|
||||
++idx;
|
||||
}
|
||||
if (!has_66_or_f3) {
|
||||
if (idx == 0) {
|
||||
return false;
|
||||
}
|
||||
if ((ip[idx] & 0xF0) == 0x40) {
|
||||
idx++;
|
||||
if (idx < size && (ip[idx] & 0xF0) == 0x40) {
|
||||
++idx;
|
||||
}
|
||||
return ip[idx] == 0x0F && ip[idx + 1] == 0x38 && ip[idx + 2] == 0xF6;
|
||||
// Require the 3-byte ADCX/ADOX opcode (0F 38 F6) plus at least 1 ModRM byte.
|
||||
return size - idx >= 4 && ip[idx] == 0x0F && ip[idx + 1] == 0x38 && ip[idx + 2] == 0xF6;
|
||||
}
|
||||
|
||||
LONG WINAPI log_unhandled_exception(PEXCEPTION_POINTERS ep) {
|
||||
// Wine can invoke the top-level filter again for the same terminal fault.
|
||||
if (ep && ep->ExceptionRecord && ep->ContextRecord &&
|
||||
!g_crash_logged.test_and_set(std::memory_order_relaxed)) {
|
||||
g_crash_in_flight.store(true, std::memory_order_release);
|
||||
const CONTEXT& ctx = *ep->ContextRecord;
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
unsigned long long module_base = 0;
|
||||
if (VirtualQuery(reinterpret_cast<LPCVOID>(ctx.Rip), ®ion, sizeof(region)) &&
|
||||
region.Type == MEM_IMAGE) {
|
||||
module_base = reinterpret_cast<uintptr_t>(region.AllocationBase);
|
||||
}
|
||||
|
||||
char line[1024];
|
||||
int length = std::snprintf(
|
||||
line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"ERROR\",\"sub\":\"runtime_veh\","
|
||||
"\"event\":\"unhandled_exception\",\"exception_code\":\"0x%08lx\","
|
||||
"\"module_base\":\"0x%016llx\",\"rva\":\"0x%016llx\","
|
||||
"\"rip\":\"0x%016llx\",\"rsp\":\"0x%016llx\","
|
||||
"\"registers\":{\"rax\":\"0x%016llx\",\"rbx\":\"0x%016llx\","
|
||||
"\"rcx\":\"0x%016llx\",\"rdx\":\"0x%016llx\",\"rsi\":\"0x%016llx\","
|
||||
"\"rdi\":\"0x%016llx\",\"rbp\":\"0x%016llx\",\"r8\":\"0x%016llx\","
|
||||
"\"r9\":\"0x%016llx\",\"r10\":\"0x%016llx\",\"r11\":\"0x%016llx\","
|
||||
"\"r12\":\"0x%016llx\",\"r13\":\"0x%016llx\",\"r14\":\"0x%016llx\","
|
||||
"\"r15\":\"0x%016llx\"}}\n",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
|
||||
ep->ExceptionRecord->ExceptionCode, module_base,
|
||||
module_base ? ctx.Rip - module_base : 0ULL, ctx.Rip, ctx.Rsp,
|
||||
ctx.Rax, ctx.Rbx, ctx.Rcx, ctx.Rdx, ctx.Rsi, ctx.Rdi, ctx.Rbp,
|
||||
ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15);
|
||||
// A crashed thread may already own the regular logger's lock.
|
||||
HANDLE output = g_log_handle != INVALID_HANDLE_VALUE
|
||||
? g_log_handle : GetStdHandle(STD_ERROR_HANDLE);
|
||||
if (length > 0 && length < static_cast<int>(sizeof(line)) &&
|
||||
output && output != INVALID_HANDLE_VALUE) {
|
||||
DWORD written = 0;
|
||||
WriteFile(output, line, static_cast<DWORD>(length), &written, nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
const LONG disposition = g_previous_filter ? g_previous_filter(ep) : EXCEPTION_CONTINUE_SEARCH;
|
||||
if (disposition == EXCEPTION_CONTINUE_EXECUTION) {
|
||||
g_crash_in_flight.store(false, std::memory_order_release);
|
||||
g_crash_logged.clear(std::memory_order_relaxed);
|
||||
}
|
||||
return disposition;
|
||||
}
|
||||
|
||||
LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
|
||||
@@ -139,9 +192,10 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
auto* ip = reinterpret_cast<const uint8_t*>(ep->ContextRecord->Rip);
|
||||
uint8_t ip[kMaxInstructionLength]{};
|
||||
const size_t size = read_instruction(ep->ContextRecord->Rip, ip);
|
||||
if (g_config.enable_clwb_veh) {
|
||||
size_t len = decode_clwb_length(ip);
|
||||
size_t len = decode_clwb_length(ip, size);
|
||||
if (len > 0) {
|
||||
uint64_t count = g_clwb_traps.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
if (count == 1 || (count & (count - 1)) == 0) {
|
||||
@@ -158,7 +212,7 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
|
||||
}
|
||||
}
|
||||
|
||||
if (g_config.enable_adx_tripwire && is_adx_opcode(ip)) {
|
||||
if (g_config.enable_adx_tripwire && is_adx_opcode(ip, size)) {
|
||||
char msg[160];
|
||||
std::snprintf(msg, sizeof(msg),
|
||||
"rip=0x%016llx bytes=%02x %02x %02x %02x %02x",
|
||||
@@ -262,9 +316,18 @@ BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) {
|
||||
if (reason == DLL_PROCESS_ATTACH) {
|
||||
init_config_and_logging();
|
||||
bx_veh_install();
|
||||
g_previous_filter = SetUnhandledExceptionFilter(log_unhandled_exception);
|
||||
bx_log_emit(BX_LOG_INFO, "runtime_veh", "attached",
|
||||
g_config.profile == BX_PROFILE_ANACONDA ? "profile=anaconda" : "profile=lockhart");
|
||||
} else if (reason == DLL_PROCESS_DETACH) {
|
||||
// Restore g_previous_filter only when our filter is still the active
|
||||
// top-level filter; if the guest installed its own filter after attach,
|
||||
// put the guest filter back unchanged. (The frozen .def has no separate
|
||||
// uninstall export, so detach performs this bounded pointer swap.)
|
||||
const auto current_filter = SetUnhandledExceptionFilter(g_previous_filter);
|
||||
if (current_filter != log_unhandled_exception) {
|
||||
SetUnhandledExceptionFilter(current_filter);
|
||||
}
|
||||
if (g_veh_handle) {
|
||||
RemoveVectoredExceptionHandler(g_veh_handle);
|
||||
g_veh_handle = nullptr;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
+273
-62
@@ -1,30 +1,132 @@
|
||||
#include <windows.h>
|
||||
#include <atomic>
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <utility>
|
||||
|
||||
#include "bx_config.h"
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
|
||||
/*
|
||||
* Track B (M1-B1 / M1-B2): Starter implementation of xmem.dll.
|
||||
* Provides working default heap & virtual allocations so dependent DLLs can link
|
||||
* and load immediately; Track B issues expand physical/scatter page mapping,
|
||||
* __XMemAllocationHooks__ dispatch, and Lockhart working-set enforcement.
|
||||
*/
|
||||
#include "xmem_accounting.h"
|
||||
|
||||
namespace {
|
||||
std::atomic<uint64_t> g_committed_virtual{0};
|
||||
std::atomic<uint64_t> g_allocated_physical{0};
|
||||
std::atomic<uint64_t> g_peak_committed{0};
|
||||
constexpr SIZE_T heap_alignment = 64;
|
||||
|
||||
void record_alloc(uint64_t bytes) {
|
||||
uint64_t cur = g_committed_virtual.fetch_add(bytes) + bytes;
|
||||
uint64_t peak = g_peak_committed.load();
|
||||
while (cur > peak && !g_peak_committed.compare_exchange_weak(peak, cur)) {}
|
||||
struct VirtualCommit {
|
||||
uintptr_t begin;
|
||||
uintptr_t end;
|
||||
PVOID allocation_base;
|
||||
};
|
||||
|
||||
// The shim build disables exceptions. Grow the table before committing pages
|
||||
// so a bookkeeping allocation failure leaves the Win32 allocation untouched.
|
||||
struct CommitTable {
|
||||
VirtualCommit* entries = nullptr;
|
||||
size_t count = 0;
|
||||
size_t capacity = 0;
|
||||
|
||||
CommitTable() = default;
|
||||
CommitTable(const CommitTable&) = delete;
|
||||
CommitTable& operator=(const CommitTable&) = delete;
|
||||
~CommitTable() { std::free(entries); }
|
||||
|
||||
VirtualCommit* begin() const { return entries; }
|
||||
VirtualCommit* end() const { return count ? entries + count : entries; }
|
||||
|
||||
bool append(VirtualCommit commit) {
|
||||
if (count == capacity) {
|
||||
const size_t max_entries = std::numeric_limits<size_t>::max() / sizeof(commit);
|
||||
if (capacity > max_entries / 2) return false;
|
||||
const size_t next_capacity = capacity ? capacity * 2 : 8;
|
||||
auto* next = static_cast<VirtualCommit*>(
|
||||
std::realloc(entries, next_capacity * sizeof(commit)));
|
||||
if (!next) return false;
|
||||
entries = next;
|
||||
capacity = next_capacity;
|
||||
}
|
||||
entries[count++] = commit;
|
||||
return true;
|
||||
}
|
||||
|
||||
void swap(CommitTable& other) {
|
||||
std::swap(entries, other.entries);
|
||||
std::swap(count, other.count);
|
||||
std::swap(capacity, other.capacity);
|
||||
}
|
||||
};
|
||||
|
||||
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() {
|
||||
const auto* config = bx_get_runtime_config();
|
||||
return config ? config->title_memory_limit_bytes : (8ULL << 30);
|
||||
}
|
||||
|
||||
bool can_commit(uint64_t bytes) {
|
||||
const uint64_t limit = title_limit();
|
||||
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 + physical_bytes);
|
||||
}
|
||||
|
||||
uintptr_t region_end(const MEMORY_BASIC_INFORMATION& region) {
|
||||
return reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
|
||||
// The export table has no XMemVirtualFree. Reconcile tracked ranges with
|
||||
// Win32 when the guest releases or decommits pages using VirtualFree.
|
||||
bool refresh_virtual_commits() {
|
||||
CommitTable live;
|
||||
uint64_t bytes = 0;
|
||||
for (const auto& commit : virtual_commits) {
|
||||
uintptr_t cursor = commit.begin;
|
||||
while (cursor < commit.end) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<PVOID>(cursor), ®ion, sizeof(region))) {
|
||||
break;
|
||||
}
|
||||
const uintptr_t end = std::min(commit.end, region_end(region));
|
||||
if (end <= cursor) break;
|
||||
if (region.State == MEM_COMMIT && region.AllocationBase == commit.allocation_base) {
|
||||
if (!live.append({cursor, end, commit.allocation_base})) return false;
|
||||
bytes += end - cursor;
|
||||
}
|
||||
cursor = end;
|
||||
}
|
||||
}
|
||||
virtual_commits.swap(live);
|
||||
virtual_bytes = bytes;
|
||||
return true;
|
||||
}
|
||||
|
||||
void report_unsupported_host_hooks() {
|
||||
static const bool reported = [] {
|
||||
if (GetProcAddress(GetModuleHandleW(nullptr), "__XMemAllocationHooks__")) {
|
||||
BX_STUB_LOG("xmem.dll", "__XMemAllocationHooks__");
|
||||
}
|
||||
return true;
|
||||
}();
|
||||
(void)reported;
|
||||
}
|
||||
|
||||
SIZE_T page_size() {
|
||||
static const SIZE_T size = [] {
|
||||
SYSTEM_INFO info{};
|
||||
GetSystemInfo(&info);
|
||||
return info.dwPageSize;
|
||||
}();
|
||||
return size;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
@@ -32,20 +134,46 @@ extern "C" {
|
||||
|
||||
PVOID WINAPI XMemAllocDefault(SIZE_T size, uint64_t /*attributes*/) {
|
||||
if (size == 0) size = 16;
|
||||
void* p = _aligned_malloc(size, 64);
|
||||
if (p) record_alloc(size);
|
||||
return p;
|
||||
if (size > std::numeric_limits<SIZE_T>::max() - heap_alignment) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::lock_guard guard(usage_lock);
|
||||
if (!can_commit(size) && (!refresh_virtual_commits() || !can_commit(size))) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto* allocation = static_cast<unsigned char*>(_aligned_malloc(size + heap_alignment, heap_alignment));
|
||||
if (!allocation) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
std::memcpy(allocation, &size, sizeof(size));
|
||||
heap_bytes += size;
|
||||
update_peak();
|
||||
return allocation + heap_alignment;
|
||||
}
|
||||
|
||||
VOID WINAPI XMemFreeDefault(PVOID address, uint64_t /*attributes*/) {
|
||||
if (address) _aligned_free(address);
|
||||
if (!address) return;
|
||||
auto* allocation = static_cast<unsigned char*>(address) - heap_alignment;
|
||||
SIZE_T size;
|
||||
std::memcpy(&size, allocation, sizeof(size));
|
||||
|
||||
std::lock_guard guard(usage_lock);
|
||||
_aligned_free(allocation);
|
||||
heap_bytes -= size;
|
||||
}
|
||||
|
||||
PVOID WINAPI XMemAlloc(SIZE_T size, uint64_t attributes) {
|
||||
report_unsupported_host_hooks();
|
||||
return XMemAllocDefault(size, attributes);
|
||||
}
|
||||
|
||||
VOID WINAPI XMemFree(PVOID address, uint64_t attributes) {
|
||||
report_unsupported_host_hooks();
|
||||
XMemFreeDefault(address, attributes);
|
||||
}
|
||||
|
||||
@@ -53,51 +181,118 @@ PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, DWOR
|
||||
/* Strip console-only high bits before forwarding to standard Win32 VirtualAlloc. */
|
||||
DWORD win_alloc = alloc_type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET | MEM_TOP_DOWN);
|
||||
if (win_alloc == 0) win_alloc = MEM_COMMIT | MEM_RESERVE;
|
||||
DWORD win_prot = protect & 0xFFu;
|
||||
if (win_prot == 0) win_prot = PAGE_READWRITE;
|
||||
void* p = VirtualAlloc(address, size, win_alloc, win_prot);
|
||||
if (p && (win_alloc & MEM_COMMIT)) record_alloc(size);
|
||||
return p;
|
||||
/* Console callers may pass multi-bit Xbox memory attributes (e.g. 0x21) in arg 4;
|
||||
* valid Win32 base page protections are a single power-of-two bit in 0x01..0x80. */
|
||||
DWORD low_prot = protect & 0xFFu;
|
||||
DWORD win_prot = (low_prot != 0 && (low_prot & (low_prot - 1)) == 0)
|
||||
? (protect & (0xFFu | PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE))
|
||||
: PAGE_READWRITE;
|
||||
/* MEM_RESET combined with MEM_COMMIT is rejected by Win32 VirtualAlloc, so returning
|
||||
* early here cannot commit pages outside the working-set budget. */
|
||||
if (!(win_alloc & MEM_COMMIT) || (win_alloc & MEM_RESET)) {
|
||||
return VirtualAlloc(address, size, win_alloc, win_prot);
|
||||
}
|
||||
|
||||
const uintptr_t requested = reinterpret_cast<uintptr_t>(address);
|
||||
const SIZE_T page = page_size();
|
||||
// Explicit reservations round down to allocation granularity.
|
||||
SIZE_T alignment = page;
|
||||
if (win_alloc & MEM_RESERVE) {
|
||||
SYSTEM_INFO info{};
|
||||
GetSystemInfo(&info);
|
||||
alignment = info.dwAllocationGranularity;
|
||||
}
|
||||
const uintptr_t begin = requested - requested % alignment;
|
||||
constexpr uintptr_t max_address = std::numeric_limits<uintptr_t>::max();
|
||||
if (!size || requested > max_address - (page - 1)
|
||||
|| size > max_address - requested - (page - 1)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
const uintptr_t end = (requested + size + page - 1) & ~(page - 1);
|
||||
|
||||
std::lock_guard guard(usage_lock);
|
||||
if (!refresh_virtual_commits()) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
CommitTable next;
|
||||
for (const auto& commit : virtual_commits) {
|
||||
if (!next.append(commit)) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
uint64_t charge = end - begin;
|
||||
uintptr_t cursor = begin;
|
||||
if (address && !(win_alloc & MEM_RESERVE)) {
|
||||
for (const auto& commit : virtual_commits) {
|
||||
if (commit.end <= cursor) continue;
|
||||
if (commit.begin >= end) break;
|
||||
if (cursor < commit.begin && !next.append({cursor, commit.begin, nullptr})) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
const uintptr_t overlap_end = std::min(end, commit.end);
|
||||
charge -= overlap_end - std::max(cursor, commit.begin);
|
||||
cursor = overlap_end;
|
||||
}
|
||||
}
|
||||
if ((cursor < end && !next.append({cursor, end, nullptr})) || !can_commit(charge)) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
PVOID allocation = VirtualAlloc(address, size, win_alloc, win_prot);
|
||||
if (!allocation || next.count == virtual_commits.count) return allocation;
|
||||
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
// A successful commit establishes a region containing the returned address.
|
||||
VirtualQuery(allocation, ®ion, sizeof(region));
|
||||
const uintptr_t relocation = address ? 0 : reinterpret_cast<uintptr_t>(allocation);
|
||||
for (size_t i = virtual_commits.count; i < next.count; ++i) {
|
||||
next.entries[i].begin += relocation;
|
||||
next.entries[i].end += relocation;
|
||||
next.entries[i].allocation_base = region.AllocationBase;
|
||||
}
|
||||
std::sort(next.begin(), next.end(), [](const auto& lhs, const auto& rhs) {
|
||||
return lhs.begin < rhs.begin;
|
||||
});
|
||||
virtual_commits.swap(next);
|
||||
virtual_bytes += charge;
|
||||
update_peak();
|
||||
return allocation;
|
||||
}
|
||||
|
||||
SIZE_T WINAPI XMemVirtualQuery(LPCVOID address, PMEMORY_BASIC_INFORMATION buf, SIZE_T len) {
|
||||
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 (!dst || !src) return FALSE;
|
||||
std::memcpy(dst, src, bytes);
|
||||
if (bytes == 0) return TRUE;
|
||||
if (!dst || !src) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
std::memmove(dst, src, bytes);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemGetWorkingSetStatistics");
|
||||
if (out_stats && stats_size > 0) {
|
||||
std::memset(out_stats, 0, stats_size);
|
||||
if (!out_stats || stats_size < sizeof(bx_xmem_stats_t)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
std::lock_guard guard(usage_lock);
|
||||
if (!refresh_virtual_commits()) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -105,17 +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;
|
||||
const bx_runtime_config_t* cfg = bx_get_runtime_config();
|
||||
out_stats->title_limit_bytes = cfg ? cfg->title_memory_limit_bytes : (8ULL << 30);
|
||||
out_stats->committed_virtual_bytes = g_committed_virtual.load();
|
||||
out_stats->allocated_physical_bytes = g_allocated_physical.load();
|
||||
out_stats->peak_committed_bytes = g_peak_committed.load();
|
||||
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, 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
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_audio_input main.cpp)
|
||||
target_link_libraries(test_audio_input PRIVATE acphal xapu chad kernel32)
|
||||
add_dependencies(test_audio_input gameinput)
|
||||
@@ -0,0 +1,155 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <thread>
|
||||
|
||||
extern "C" {
|
||||
HRESULT WINAPI AcpHalCreate(void**);
|
||||
HRESULT WINAPI ApuCreateHeap(uint32_t, uint32_t);
|
||||
HRESULT WINAPI ApuAlloc(void**, uint32_t*, uint32_t, uint32_t);
|
||||
HRESULT WINAPI ApuFree(void*);
|
||||
BOOL WINAPI ApuIsVirtualAddressValid(const void*, uint32_t);
|
||||
void* WINAPI ApuMapApuAddress(uint32_t);
|
||||
uint32_t WINAPI ApuMapVirtualAddress(const void*);
|
||||
HRESULT WINAPI XApuConnect(void**);
|
||||
HRESULT WINAPI XApuDisconnect(void*);
|
||||
HRESULT WINAPI XApuEnqueueCommand(void*, const void*, uint32_t);
|
||||
HRESULT WINAPI XApuDequeueResult(void*, void*, uint32_t);
|
||||
uint32_t WINAPI XApuGetResultCount(void*);
|
||||
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(uint32_t, void**);
|
||||
HRESULT WINAPI XDspActivate(void*);
|
||||
HRESULT WINAPI XDspDeactivate(void*);
|
||||
HRESULT WINAPI XDspSubmitCommand(void*, const void*, uint32_t);
|
||||
HRESULT WINAPI XDspDisconnect(void*);
|
||||
}
|
||||
|
||||
#define CHECK(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0)
|
||||
|
||||
int main() {
|
||||
void* object = nullptr;
|
||||
CHECK(AcpHalCreate(&object) == S_OK && object);
|
||||
auto* hal = static_cast<IUnknown*>(object);
|
||||
CHECK(hal->QueryInterface(IID_IUnknown, &object) == S_OK && object == hal);
|
||||
CHECK(hal->Release() == 1);
|
||||
void *va = nullptr, *second = nullptr;
|
||||
uint32_t base = 0, other = 0;
|
||||
CHECK(ApuAlloc(&va, &base, 64, 64) == E_OUTOFMEMORY && !va && !base);
|
||||
CHECK(ApuCreateHeap(64, 64) == S_OK);
|
||||
CHECK(ApuAlloc(&va, nullptr, 64, 64) == S_OK && va);
|
||||
CHECK(ApuFree(va) == S_OK);
|
||||
va = nullptr;
|
||||
CHECK(ApuAlloc(nullptr, &base, 64, 64) == S_OK && base);
|
||||
va = ApuMapApuAddress(base);
|
||||
CHECK(va && ApuFree(va) == S_OK);
|
||||
va = nullptr;
|
||||
base = 0;
|
||||
CHECK(ApuAlloc(&va, &base, 64, 256) == S_OK && va && base);
|
||||
CHECK(reinterpret_cast<uintptr_t>(va) % 256 == 0 && base % 256 == 0);
|
||||
CHECK(ApuAlloc(&second, &other, 64, 64) == S_OK && other != base);
|
||||
CHECK(ApuCreateHeap(0, 0) == HRESULT_FROM_WIN32(ERROR_BUSY));
|
||||
void* excess = nullptr;
|
||||
CHECK(ApuAlloc(&excess, nullptr, 1, 64) == E_OUTOFMEMORY);
|
||||
auto* tail = static_cast<unsigned char*>(va) + 63;
|
||||
CHECK(ApuMapApuAddress(base + 63) == tail && ApuMapVirtualAddress(tail) == base + 63);
|
||||
CHECK(ApuIsVirtualAddressValid(tail, 1) && !ApuIsVirtualAddressValid(tail, 2));
|
||||
CHECK(ApuFree(tail) == E_INVALIDARG);
|
||||
CHECK(ApuFree(va) == S_OK && !ApuMapApuAddress(base) && !ApuMapVirtualAddress(va));
|
||||
CHECK(ApuFree(va) == E_INVALIDARG && ApuMapApuAddress(other) == second);
|
||||
CHECK(ApuFree(second) == S_OK && hal->Release() == 0);
|
||||
|
||||
void *apu = nullptr, *peer = nullptr, *dsp = nullptr;
|
||||
CHECK(XApuConnect(&apu) == S_OK && XApuConnect(&peer) == S_OK && peer != apu);
|
||||
unsigned result = 0;
|
||||
CHECK(XApuDequeueResult(apu, &result, sizeof(result)) == S_FALSE);
|
||||
for (unsigned cycle = 0; cycle < 3; ++cycle) {
|
||||
HRESULT status = S_OK;
|
||||
unsigned accepted = 0;
|
||||
std::thread producer([&] {
|
||||
for (; accepted < 1024; ++accepted) {
|
||||
unsigned command = cycle * 1024 + accepted;
|
||||
status = XApuEnqueueCommand(apu, &command, sizeof(command));
|
||||
if (status != S_OK) break;
|
||||
}
|
||||
});
|
||||
producer.join();
|
||||
CHECK(accepted && status == HRESULT_FROM_WIN32(ERROR_BUSY));
|
||||
CHECK(XApuGetResultCount(apu) == accepted && XApuGetResultCount(peer) == 0);
|
||||
CHECK(XApuDequeueResult(apu, &result, 1) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER));
|
||||
for (unsigned i = 0; i < accepted; ++i) {
|
||||
CHECK(XApuDequeueResult(apu, &result, sizeof(result)) == S_OK);
|
||||
CHECK(result == cycle * 1024 + i);
|
||||
}
|
||||
CHECK(XApuGetResultCount(apu) == 0);
|
||||
}
|
||||
// A stalled peer must fail this test rather than wait forever.
|
||||
constexpr unsigned messages = 4096;
|
||||
const auto deadline = GetTickCount64() + 10000;
|
||||
std::atomic<bool> failed{false};
|
||||
std::thread worker([&] {
|
||||
for (unsigned i = 0; i < messages && !failed;) {
|
||||
const auto hr = XApuEnqueueCommand(apu, &i, sizeof(i));
|
||||
if (hr == S_OK) ++i;
|
||||
else if (hr != HRESULT_FROM_WIN32(ERROR_BUSY) || GetTickCount64() >= deadline)
|
||||
failed = true;
|
||||
else std::this_thread::yield();
|
||||
}
|
||||
});
|
||||
for (unsigned i = 0; i < messages && !failed;) {
|
||||
const auto hr = XApuDequeueResult(apu, &result, sizeof(result));
|
||||
if (hr == S_OK && result == i) ++i;
|
||||
else if (hr != S_FALSE || GetTickCount64() >= deadline) failed = true;
|
||||
else std::this_thread::yield();
|
||||
}
|
||||
worker.join();
|
||||
CHECK(!failed && XApuGetResultCount(apu) == 0);
|
||||
CHECK(XApuDisconnect(apu) == S_OK && XApuDisconnect(peer) == S_OK);
|
||||
CHECK(XApuEnqueueCommand(apu, &result, sizeof(result)) == E_HANDLE);
|
||||
|
||||
CHECK(XDspConnectWithMaximumStreamLimit(0, &dsp) == E_INVALIDARG && !dsp);
|
||||
CHECK(XDspConnectWithMaximumStreamLimit(2, &dsp) == S_OK && dsp);
|
||||
for (unsigned cycle = 0; cycle < 2; ++cycle) {
|
||||
unsigned queued = 0;
|
||||
HRESULT hr = S_OK;
|
||||
while (queued < 1024 && (hr = XDspSubmitCommand(dsp, &result, sizeof(result))) == S_OK)
|
||||
++queued;
|
||||
CHECK(queued && hr == HRESULT_FROM_WIN32(ERROR_BUSY));
|
||||
CHECK(XDspActivate(dsp) == S_OK);
|
||||
for (unsigned i = 0; i <= queued; ++i)
|
||||
CHECK(XDspSubmitCommand(dsp, &result, sizeof(result)) == S_OK);
|
||||
CHECK(XDspDeactivate(dsp) == S_OK);
|
||||
}
|
||||
CHECK(XDspDisconnect(dsp) == S_OK && XDspActivate(dsp) == E_HANDLE);
|
||||
|
||||
HMODULE dll = LoadLibraryW(L"GameInput.dll");
|
||||
CHECK(dll);
|
||||
auto proc = GetProcAddress(dll, MAKEINTRESOURCEA(1));
|
||||
CHECK(proc && proc == GetProcAddress(dll, "GameInputCreate"));
|
||||
using Factory = HRESULT (WINAPI*)(void**);
|
||||
auto create = reinterpret_cast<Factory>(reinterpret_cast<void*>(proc));
|
||||
CHECK(create(&object) == S_OK && object);
|
||||
auto* input = static_cast<IUnknown*>(object);
|
||||
CHECK(create(&object) == S_OK && object == input && input->Release() == 1);
|
||||
CHECK(input->QueryInterface(IID_IUnknown, &object) == S_OK && object == input);
|
||||
CHECK(input->Release() == 1);
|
||||
constexpr GUID kGameInputV0 = {0x11be2a7e, 0x4254, 0x445a,
|
||||
{0x9c, 0x09, 0xff, 0xc4, 0x0f, 0x00, 0x69, 0x18}};
|
||||
constexpr GUID kUnknownIid = {0x00000001, 0x0002, 0x0003,
|
||||
{0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b}};
|
||||
void* unknown = reinterpret_cast<void*>(uintptr_t{1});
|
||||
CHECK(input->QueryInterface(kUnknownIid, &unknown) == E_NOINTERFACE && !unknown);
|
||||
void* v0_obj = nullptr;
|
||||
CHECK(input->QueryInterface(kGameInputV0, &v0_obj) == S_OK && v0_obj == input);
|
||||
auto* v0 = static_cast<IUnknown*>(v0_obj);
|
||||
auto** table = *reinterpret_cast<void***>(v0);
|
||||
using Timestamp = uint64_t (WINAPI*)(IUnknown*);
|
||||
CHECK(reinterpret_cast<Timestamp>(table[3])(v0) > 0);
|
||||
using Reading = HRESULT (WINAPI*)(IUnknown*, uint32_t, void*, void**);
|
||||
void* reading = reinterpret_cast<void*>(uintptr_t{1});
|
||||
CHECK(reinterpret_cast<Reading>(table[4])(v0, 0, nullptr, &reading) == E_NOTIMPL && !reading);
|
||||
CHECK(v0->Release() == 1);
|
||||
CHECK(input->Release() == 0);
|
||||
FreeLibrary(dll);
|
||||
std::puts("PASS: audio mappings, APU and DSP queues, GameInput ordinal 1");
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -2,3 +2,6 @@ add_executable(test_veh_clwb main.cpp)
|
||||
target_include_directories(test_veh_clwb PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_compile_options(test_veh_clwb PRIVATE -mavx2 -mfma)
|
||||
target_link_libraries(test_veh_clwb PRIVATE bx_runtime_veh xmem kernel32)
|
||||
|
||||
add_executable(test_veh_unhandled main_unhandled.cpp)
|
||||
target_link_libraries(test_veh_unhandled PRIVATE bx_runtime_veh kernel32)
|
||||
@@ -29,15 +29,25 @@ int main() {
|
||||
}
|
||||
}
|
||||
|
||||
/* 2. Verify clwb trapping via bx_runtime_veh.dll (both legacy and REX forms) */
|
||||
alignas(64) uint8_t buf[128] = {0x42};
|
||||
uint64_t before = bx_veh_get_clwb_trap_count();
|
||||
__asm__ volatile("clwb (%0)" :: "r"(buf) : "memory");
|
||||
__asm__ volatile("clwb 64(%0)" :: "r"(buf) : "memory");
|
||||
uint64_t after = bx_veh_get_clwb_trap_count();
|
||||
std::printf("clwb traps observed: %llu -> %llu\n",
|
||||
static_cast<unsigned long long>(before),
|
||||
static_cast<unsigned long long>(after));
|
||||
// Fixed registers ensure the assembler emits the intended ModRM/REX forms.
|
||||
alignas(64) uint8_t buf[512] = {0x42};
|
||||
const uint64_t before = bx_veh_get_clwb_trap_count();
|
||||
__asm__ volatile(
|
||||
"clwb (%%rax)\n\t"
|
||||
"clwb 64(%%rax)\n\t"
|
||||
"clwb 256(%%rax)\n\t"
|
||||
"mov %%rax, %%r8\n\t"
|
||||
"clwb (%%r8)\n\t"
|
||||
"clwb 64(%%rax,%%rcx,4)\n\t"
|
||||
"clwb (%%rip)"
|
||||
:: "a"(buf), "c"(8) : "r8", "memory");
|
||||
const uint64_t delta = bx_veh_get_clwb_trap_count() - before;
|
||||
if (delta != 6) {
|
||||
std::fprintf(stderr, "FAIL: expected 6 CLWB traps, observed %llu\n",
|
||||
static_cast<unsigned long long>(delta));
|
||||
return 4;
|
||||
}
|
||||
std::printf("CLWB traps observed: %llu\n", static_cast<unsigned long long>(delta));
|
||||
|
||||
/* 3. Verify basic XMem allocation + transfer + stats contract */
|
||||
void* src = XMemAlloc(4096, 0);
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
#include <windows.h>
|
||||
#include <cstdint>
|
||||
|
||||
extern "C" uint64_t bx_veh_get_clwb_trap_count(void);
|
||||
|
||||
// Run in its own process. The launcher should report failure and the trace
|
||||
// should contain a single unhandled_exception with RAX set to the marker.
|
||||
int main() {
|
||||
SetErrorMode(SEM_NOGPFAULTERRORBOX);
|
||||
// Keep a static import on bx_runtime_veh.dll so its DLL_PROCESS_ATTACH filter is installed.
|
||||
volatile uint64_t attached_traps = bx_veh_get_clwb_trap_count();
|
||||
(void)attached_traps;
|
||||
constexpr uint64_t marker = 0x123456789abcdef0ULL;
|
||||
__asm__ volatile("ud2" :: "a"(marker) : "memory");
|
||||
return 1;
|
||||
}
|
||||
@@ -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 main.cpp)
|
||||
target_include_directories(test_xmem PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_link_libraries(test_xmem PRIVATE xmem bx_runtime_veh kernel32)
|
||||
@@ -0,0 +1,114 @@
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
|
||||
extern "C" {
|
||||
PVOID WINAPI XMemAlloc(SIZE_T, uint64_t);
|
||||
PVOID WINAPI XMemAllocDefault(SIZE_T, uint64_t);
|
||||
VOID WINAPI XMemFree(PVOID, uint64_t);
|
||||
VOID WINAPI XMemFreeDefault(PVOID, uint64_t);
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, DWORD);
|
||||
SIZE_T WINAPI XMemVirtualQuery(LPCVOID, PMEMORY_BASIC_INFORMATION, SIZE_T);
|
||||
BOOL WINAPI XMemTransferMemory(PVOID, LPCVOID, SIZE_T, uint64_t);
|
||||
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
|
||||
BOOL WINAPI XMemIsToolsMemAvailable();
|
||||
}
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
std::fprintf(stderr, "xmem:%d: %s (Win32 error %lu)\n", __LINE__, \
|
||||
#condition, static_cast<unsigned long>(GetLastError())); \
|
||||
return 1; \
|
||||
} \
|
||||
} while (false)
|
||||
|
||||
int main() {
|
||||
SYSTEM_INFO sys{};
|
||||
GetSystemInfo(&sys);
|
||||
const SIZE_T page = sys.dwPageSize;
|
||||
const auto* config = bx_get_runtime_config();
|
||||
|
||||
bx_xmem_stats_t stats{};
|
||||
CHECK(config && XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
|
||||
char profile[16]{};
|
||||
GetEnvironmentVariableA("BX_PROFILE", profile, sizeof(profile));
|
||||
const uint64_t expected_limit = std::strcmp(profile, "anaconda") == 0
|
||||
? 13500ULL * 1024 * 1024
|
||||
: 8ULL * 1024 * 1024 * 1024;
|
||||
CHECK(stats.title_limit_bytes == expected_limit);
|
||||
CHECK(stats.title_limit_bytes == config->title_memory_limit_bytes);
|
||||
CHECK(stats.committed_virtual_bytes == 0 && stats.allocated_physical_bytes == 0);
|
||||
CHECK(!XMemIsToolsMemAvailable());
|
||||
CHECK(!XMemGetWorkingSetStatistics(&stats, sizeof(stats) - 1));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
unsigned char large_stats[sizeof(bx_xmem_stats_t) + 16];
|
||||
std::memset(large_stats, 0xCC, sizeof(large_stats));
|
||||
CHECK(XMemGetWorkingSetStatistics(large_stats, sizeof(large_stats)));
|
||||
for (size_t i = sizeof(bx_xmem_stats_t); i < sizeof(large_stats); ++i) {
|
||||
CHECK(large_stats[i] == 0);
|
||||
}
|
||||
|
||||
auto* ordinary = XMemAlloc(73, 0);
|
||||
auto* empty = XMemAllocDefault(0, 0);
|
||||
CHECK(ordinary && empty);
|
||||
CHECK(reinterpret_cast<uintptr_t>(ordinary) % 64 == 0);
|
||||
CHECK(reinterpret_cast<uintptr_t>(empty) % 64 == 0);
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.committed_virtual_bytes == 89);
|
||||
|
||||
// The existing heap charge should reject requests at the full cap
|
||||
// without allocating gigabytes on the test host.
|
||||
CHECK(!XMemAllocDefault(stats.title_limit_bytes, 0));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
CHECK(!XMemVirtualAlloc(nullptr, stats.title_limit_bytes,
|
||||
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
|
||||
XMemFreeDefault(empty, 0);
|
||||
XMemFree(ordinary, 0);
|
||||
|
||||
auto* reserved = static_cast<unsigned char*>(
|
||||
XMemVirtualAlloc(nullptr, page * 3, MEM_RESERVE, PAGE_READWRITE));
|
||||
CHECK(reserved && reinterpret_cast<uintptr_t>(reserved) % page == 0);
|
||||
CHECK(XMemVirtualAlloc(reserved, page * 2, MEM_COMMIT, PAGE_READWRITE) == reserved);
|
||||
CHECK(XMemVirtualAlloc(reserved + page + 1, page * 2 - 1, MEM_COMMIT, PAGE_READWRITE)
|
||||
== reserved + page);
|
||||
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
CHECK(XMemVirtualQuery(reserved + page, ®ion, sizeof(region)) == sizeof(region));
|
||||
CHECK(region.AllocationBase == reserved && region.State == MEM_COMMIT);
|
||||
CHECK(region.Protect == PAGE_READWRITE && region.RegionSize == page * 2);
|
||||
|
||||
constexpr char sample[] = "betterxen";
|
||||
CHECK(XMemTransferMemory(reserved, sample, sizeof(sample), 0));
|
||||
CHECK(XMemTransferMemory(reserved + 1, reserved, sizeof(sample), 0));
|
||||
CHECK(std::memcmp(reserved + 1, sample, sizeof(sample)) == 0);
|
||||
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.committed_virtual_bytes == page * 3 && stats.peak_committed_bytes == page * 3);
|
||||
CHECK(VirtualFree(reserved + page, page, MEM_DECOMMIT));
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.committed_virtual_bytes == page * 2 && stats.peak_committed_bytes == page * 3);
|
||||
CHECK(VirtualFree(reserved, 0, MEM_RELEASE));
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.committed_virtual_bytes == 0 && stats.peak_committed_bytes == page * 3);
|
||||
|
||||
// Console callers pass multi-bit attributes (e.g. 0x21) in arg 4 and high bits in alloc_type.
|
||||
auto* console_res = static_cast<unsigned char*>(
|
||||
XMemVirtualAlloc(nullptr, page * 2, MEM_RESERVE | 0x20400000u, 0x21u));
|
||||
CHECK(console_res != nullptr);
|
||||
CHECK(XMemVirtualAlloc(console_res, page, MEM_COMMIT, 0x21u) == console_res);
|
||||
console_res[0] = 0x5Au;
|
||||
CHECK(console_res[0] == 0x5Au);
|
||||
CHECK(VirtualFree(console_res, 0, MEM_RELEASE));
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.committed_virtual_bytes == 0);
|
||||
std::puts("test_xmem: passed");
|
||||
}
|
||||
@@ -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