mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-29 22:21:12 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2f5652694 | ||
|
|
41b755014a | ||
|
|
9d5ecf39e4 | ||
|
|
d910e43df3 | ||
|
|
c0aaaa005b | ||
|
|
69242d1215 | ||
|
|
808c5d17c5 | ||
|
|
23d631e3c7 | ||
|
|
64f9b1dcb5 | ||
|
|
740df46b10 | ||
|
|
a648cdecc7 | ||
|
|
911c27f62b | ||
|
|
340cd1deec | ||
|
|
a4026459d9 | ||
|
|
77af218878 | ||
|
|
620019564b | ||
|
|
36a0f3f6c5 | ||
|
|
29c8a29051 | ||
|
|
6db66dc4a4 | ||
|
|
9239ba6551 | ||
|
|
65eef5b08e |
No files matched your search
@@ -10,7 +10,7 @@ Collaborators point their agent at this repository and say "work" (or "contribut
|
||||
|
||||
**"Work" authorizes, for the one item you pick:** opening a draft pull request, posting a review, committing with DCO sign-off, and pushing a branch. It does not authorize merging your own person's pull request, changing rules, or anything marked `needs-human`. A more specific instruction from your person always wins.
|
||||
|
||||
### Step 1 — Preflight: required, or stop
|
||||
### Step 1 — Preflight: make the machine ready yourself
|
||||
|
||||
```sh
|
||||
cargo build --locked -p bx-cli && target/debug/bx-cli preflight
|
||||
@@ -21,15 +21,29 @@ cargo build --locked -p bx-cli && target/debug/bx-cli preflight
|
||||
| Required | How it is found |
|
||||
| --- | --- |
|
||||
| An Apple Silicon Mac with CrossOver 26.3+, D3DMetal and `mingw-w64` | Checked on the host |
|
||||
| **The project-authorized target build** | Saved once with `bx-cli setup --target-exe <path>` |
|
||||
| **The GDK** (headers and compilers, under the project's authorization) | Saved once with `bx-cli setup --gdk-root <folder>` |
|
||||
| **The project-authorized target build** | Found and saved by `bx-cli setup --find` |
|
||||
| **The GDK** (headers and compilers, under the project's authorization) | Found and saved by `bx-cli setup --find` |
|
||||
| At least 10 GiB of free disk space | Measured |
|
||||
|
||||
**If preflight fails, do not work.** Do not write fixes, tests, reviews or documentation "for someone else to verify". Tell your person exactly which line says `MISSING`, and stop. Work here is found by running the target build and checked against the GDK; an agent without them is guessing.
|
||||
**If preflight fails, fix it yourself and run it again.** Your person said "work"; do not hand the setup back to them.
|
||||
|
||||
| `MISSING` line | What you do |
|
||||
| --- | --- |
|
||||
| Target build, GDK | `target/debug/bx-cli setup --find`. It searches the home folder, recognises the GDK by its header and the build by its structure (never by name), and saves both. |
|
||||
| `mingw-w64 g++` (also `cmake`, `gh`) | `brew install mingw-w64 cmake gh`. Being told to "work" authorizes installing these three. |
|
||||
| Free disk space | Remove your own scratch: build folders and scratch bottles of worktrees you created. Never another session's files. |
|
||||
|
||||
**Stop only for what an agent cannot supply**, and say exactly which:
|
||||
|
||||
- the host is not an Apple Silicon Mac;
|
||||
- CrossOver is not installed (it is licensed software; do not install it);
|
||||
- `setup --find` reports that the target build or the GDK is not on this machine, or found more than one distinct build (which build to use is your person's choice: they run `bx-cli setup --target-exe <path>` once).
|
||||
|
||||
In those cases do not work around it: no fixes, tests or reviews "for someone else to verify". Work here is found by running the target build and checked against the GDK; an agent without them is guessing.
|
||||
|
||||
Also check `git`, `gh` (`gh auth status`; if not logged in, ask the user to run `gh auth login`), `cargo`, `cmake` and `python3`; verify push access or fork (`gh repo fork MacosPorters/betterxen --remote`); sync with `origin/main`. Work in your own worktree and your own bottle; never use a bottle another session is using.
|
||||
|
||||
`bx-cli setup` checks each path and remembers it in `~/.config/betterxen/local.conf`, outside every checkout, so it is set once per machine and works in every worktree, shell and agent session. (`BX_TARGET_EXE` and `BX_GDK_ROOT` override it for one command.) If a collaborator has not run setup, ask them to; do not search their disk for the build. Never commit those paths, and never put a path, file name, hash or byte from the target build or the GDK into a commit, issue or pull request (Section 6).
|
||||
`bx-cli setup` remembers the two locations in `~/.config/betterxen/local.conf`, outside every checkout, so it happens once per machine and works in every worktree, shell and agent session. (`BX_TARGET_EXE` and `BX_GDK_ROOT` override it for one command.) Never commit those paths, and never put a path, file name, hash or byte from the target build or the GDK into a commit, issue or pull request (Section 6).
|
||||
|
||||
### Step 2 — Pick exactly one thing, in this order
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- **A collaborator only has to say "work"** (AGENTS.md §0, step 1). When `bx-cli preflight` fails, the agent makes the machine ready itself: the new `bx-cli setup --find` searches the home folder, recognises the GDK by its header and the target build by its structure (a large PE32+ file that imports `d3d12_xs.dll`; never by name), ignores the GDK's own tools, treats byte-identical copies as one build and keeps the copy with its imported DLLs beside it, and saves both settings. The agent may install `mingw-w64`, `cmake` and `gh` with Homebrew and free disk space by removing its own scratch. It stops only for what it cannot supply: no Apple Silicon Mac, no CrossOver, the build or the GDK not on the machine, or more than one distinct build.
|
||||
- **Working rules: the pull request is the unit of work, and the target build and the GDK are required** (AGENTS.md §0, [working method](docs/process/working-method.md)). An agent told to "work" first runs the new `bx-cli preflight`, which fails unless the host is an Apple Silicon Mac with CrossOver, D3DMetal and `mingw-w64`, the target build's executable and the GDK folder are known, and 10 GiB of disk is free. A collaborator records the two locations once with the new `bx-cli setup --target-exe <path> --gdk-root <folder>`, which checks them and keeps them in `~/.config/betterxen/local.conf`, outside the repository (`BX_TARGET_EXE` and `BX_GDK_ROOT` override it). If preflight fails the agent stops and does no work. A blocker the agent can fix no longer gets an issue: it is claimed by a draft pull request titled with its run-report signature. Issues are kept for handoffs (label `handoff`), decisions for a person, and the ladder status. Claims by comment and the 7-day stale window are gone; an idle draft may be taken over after 3 days.
|
||||
- **BetterXen is no longer a clean-room project** (repository owner's decision, #650). `CONTRIBUTING.md` now says that material the project is authorized to use, such as the GDK and its compilers, may be used and that facts derived from it may be committed, while the material and its outputs are never committed. Leaked or unauthorized material remains forbidden.
|
||||
- **Roadmap and working method (proposed).** `docs/roadmap.md` replaces the subsystem milestones M3–M6 with stages the project-authorized target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), each judged on ten recorded runs on a 16 GB Mac, with decision gates for the D3DMetal back end, reference images, memory and frame rate. [docs/process/working-method.md](docs/process/working-method.md) describes the blocker queue for a team that works by telling coding agents to "work": where state lives, the order of work (own pull requests, review, one blocker, discover), the run protocol, source ranks and pull-request shape. AGENTS.md §0 is rewritten to match.
|
||||
@@ -25,6 +26,9 @@ remains unsupported.
|
||||
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
|
||||
|
||||
### Added
|
||||
- `xgameruntime.dll` serves `XAsyncRun`, `XTaskQueueCreateComposite`, `XTaskQueueGetPort` and `XTaskQueueDuplicateHandle` through `IXGameRuntimeCore` slots 6, 13, 14 and 15 (#666). `XAsyncRun` runs the title's work callback on the block's work port and completes the block with its result. A duplicated queue handle shares the queue, and only the last close shuts its lanes down. A composite queue forwards each port to the port it was made from, and an async block's completion returns through the queue the block named. A project-authorized target build uses these for its save-game work and exited when `XAsyncRun` was unimplemented. `test_xgameruntime` checks all four through `QueryApiImpl`.
|
||||
- `bx-cli report <log.jsonl>...` (#664, part 1): a run report per log (one log is one run) and a summary across runs. Per run: how it ended, the frames presented (a lower bound), every unimplemented call with its count, faults whose innermost frame is in a BetterXen module, and pipelines by kind. The summary counts clean runs and lists each blocker signature with the number of runs that hit it; blocker issues are titled with those signatures. `bx-cli run` now appends a `run_end` record to its log (exited with a status, timeout, signal or launch failure), which the report reads. A log without it has an unknown outcome and is never counted as clean.
|
||||
- `xgameruntime.dll` serves `XUserDuplicateHandle` through `IXUser` slot 3 (#680). A duplicate is a new handle to the one offline user; each handle is closed on its own, and `XUserCompare` returns 0 for any two valid handles of that user. A project-authorized target build duplicates its user handle after sign-in and waited when the slot was unimplemented. `test_xgameruntime` checks the slot through `QueryApiImpl`.
|
||||
- Shader corpus, Phase 0 of the console shader translator (#649). `shader-transpiler/corpus/hlsl/` holds eight BetterXen-authored compute kernels covering integer and float ALU, divergent branches, loops, groupshared memory, wave operations, atomics and system values. `scripts/shader-corpus/build.sh` compiles each one locally with the console `xdxc` (a title-style container: `DXIL` plus `ACCC`/`FSPX`), the console PIX compiler (Microsoft's ISA listing) and the public PC DXC (DXIL for a D3DMetal reference run). `extract_code.py` then takes the code from the `FSPX` kind-6 section, skips the leading `v_nop_xbox_data` words and disassembles it with LLVM's public `gfx1030` decoder. All eight kernels build and decode cleanly. The extractor has nine unit tests on synthetic containers that need no GDK. Compiler outputs stay in the git-ignored `target/shader-corpus/`. One open question is recorded: a `v_cmp_class_f16` in the `wave` kernel's ballot sequence.
|
||||
- `docs/research/console-shader-abi.md` and `CLAIM-XBOX-CS-ENTRY-ABI` (class U, not yet independently reproduced): the compute shader entry ABI observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler, used under Microsoft's authorization, on eleven project-authored probes. Compute code is wave64. Root data starts at `s4` in root-parameter order: one SGPR per constant, two per root descriptor address, one per 32-bit table pointer. The thread-group IDs follow the root data, and `s0:s1` holds the root-data address when it overflows. Root buffer descriptors are built inline with no effective bounds check, table buffer descriptors are 32 bytes apart (samplers 16), and the compiler reports the HLSL binding of each descriptor load. No compiler output, binary or documentation text is in the repository. Register roles are inferences, and the ACCC container layout remains unknown.
|
||||
- Opt-in diagnostics in `bx_runtime_veh.dll`, all off by default:
|
||||
@@ -85,6 +89,8 @@ remains unsupported.
|
||||
- `d3d12_xs.dll!D3D12ConfigureVirtualMemoryX` now decodes the Xbox virtual-memory configuration (`D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION`) alongside the existing `BXVM` contract. Layout and behaviour follow the authorized GDK documentation of the function and structure: no flags, a GPU page-table size in 4 MB units clamped to 33, a frame-buffer preserve size (0, -1 for the legacy size, or bytes clamped to 64 MiB), and two output addresses, the minimum always 2 GiB and the maximum 159.375 GiB at the default 5 pages. The call fails with `E_FAIL` once a D3D12 device exists. Call-site observation of a project-authorized target build agrees with the documented layout. Inferred, and marked as such: the maximum for other page-table sizes scales linearly (`max_estimated=1` in the log), and a page-table size of 0, an unreadable configuration or unwritable outputs fail with `E_INVALIDARG`. The host sizes no GPU page tables and keeps no cross-process frame buffer, so the path records both (`vmem_config_recorded`, `applied=0 recorded_only=1`), leaves the `BXVM` record and cached backing heap untouched, and still emits `BX_STUB_LOG`. `tests/conformance/test_d3d12_vmem_xbox/` checks the documented outputs, clamps and post-device `E_FAIL`, the refused cases, and that a cached `BXVM` backing heap survives.
|
||||
|
||||
### Fixed
|
||||
- `bx_runtime_veh.dll` completes a `CLZERO` loop in one exception (#665). A title that zeroes memory with `clzero; add rax,0x40; cmp rax,<reg64>; jb` raised one illegal-instruction exception per 64 bytes under Rosetta 2, which stalled a project-authorized target build's frame loop for tens of seconds. When the trapped `CLZERO` is followed by exactly that form, the handler zeroes every remaining line below the limit and leaves `RAX` at the last one, so the title's own `add`/`cmp`/`jb` leaves the loop. The range is zeroed region by region and stops at memory that is not committed and writable, where the next `CLZERO` traps and faults as before. Other loop forms keep the per-instruction path. `test_veh_clzero_loop` checks the memory result and counts the exceptions; it fails on the old handler.
|
||||
- `d3d12_xs.dll` no longer turns `DeserializeGraphicsPipelineStateX`, `DeserializeComputePipelineStateX`, `CreateDerivedGraphicsPipelineStateX` or `CreateDerivedComputePipelineStateX` into null pipelines in null-render mode (`BX_NULL_RENDER=1`) (#669). All four calls now always return `E_NOTIMPL`, clear `*ppv` and log `pipeline_refused` without `; null pipeline returned`, so a title falls back to creating pipelines from shader containers instead of silently receiving null pipelines. `test_d3d12_serialized_pipelines` checks all four slots and their refusal log lines with `BX_NULL_RENDER=1` active alongside a control shader-container null pipeline.
|
||||
- `XCRDAPI.dll` Xbox DirectStorage fixes:
|
||||
- **Zlib requests read the file.** The file handle was not set for them, so every compressed file request failed. The request options are now decoded, and zlib streams are inflated in-tree.
|
||||
- **`AutoSubmitDisabled` is honoured.** Xbox `CreateQueueX` respects `DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled`: a queue with the flag runs nothing before `Submit`, and when it is full the enqueuer waits until `Submit` is called on another thread. A queue without the flag submits by itself once half full.
|
||||
|
||||
@@ -15,9 +15,9 @@ No agent works without all of these. `bx-cli preflight` checks them and fails if
|
||||
- **the GDK**, headers and compilers, under the project's authorization;
|
||||
- at least 10 GiB of free disk space.
|
||||
|
||||
Each collaborator tells BetterXen once where the last two are: `bx-cli setup --target-exe <path> --gdk-root <folder>`. The answer is kept in `~/.config/betterxen/local.conf`, outside the repository, and every worktree and agent session on that machine uses it.
|
||||
A collaborator only says "work". When preflight fails, the agent makes the machine ready itself: `bx-cli setup --find` searches the home folder, recognises the GDK by its header and the target build by its structure (never by name), and saves both in `~/.config/betterxen/local.conf`, outside the repository, where every worktree and agent session on that machine finds them. It installs missing build tools with Homebrew and frees disk space by removing its own scratch.
|
||||
|
||||
Work here is found by running the build and checked against the GDK. Without them an agent can only guess, and a guess that looks like a fix costs a reviewer more than it saves. An agent whose preflight fails tells its person what is missing and stops; it does not write fixes, tests or reviews "for someone else to verify".
|
||||
Work here is found by running the build and checked against the GDK. Without them an agent can only guess, and a guess that looks like a fix costs a reviewer more than it saves. An agent stops only for what it cannot supply: the host is not an Apple Silicon Mac, CrossOver is not installed, the build or the GDK is not on the machine, or more than one distinct build is (the choice is the collaborator's). Then it says exactly which, and does not write fixes, tests or reviews "for someone else to verify".
|
||||
|
||||
## Why this shape
|
||||
|
||||
@@ -140,6 +140,8 @@ Until the launcher does, the offline-run procedure and the diagnostic switches a
|
||||
|
||||
It ends with a ten-run summary and a list of **signatures**, the strings pull requests and handoff issues are titled with.
|
||||
|
||||
**What exists today** (#664): `bx-cli report <log.jsonl>...` produces the per-run report and the summary with signatures from run logs, and `bx-cli run` records how each run ended. Not yet in the launcher: the offline runner, per-session bottles, the machine-wide lock, thread stacks on a stall, and stall detection itself (frames are logged at powers of two, so a log cannot yet tell a stall from slow presentation).
|
||||
|
||||
## Sources of truth
|
||||
|
||||
When a fix needs to know what the console does, use the strongest source available and name its rank in the pull request.
|
||||
|
||||
@@ -63,9 +63,10 @@ fn usage_text() -> &'static str {
|
||||
bx-cli doctor Inspect Apple Silicon host, Rosetta 2, CrossOver & mingw-w64\n\
|
||||
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 setup [--target-exe <path>] [--gdk-root <dir>] Remember where the target build and the GDK are on this machine (saved outside the repository)\n\
|
||||
bx-cli setup [--find] [--target-exe <path>] [--gdk-root <dir>] Remember where the target build and the GDK are on this machine (saved outside the repository); --find searches the home folder for them\n\
|
||||
bx-cli preflight Check everything work needs: host, CrossOver, the target build, the GDK, disk space. Fails if anything is missing\n\
|
||||
bx-cli trace <log.jsonl> Summarize bx_runtime_veh JSONL diagnostics\n\
|
||||
bx-cli report <log.jsonl>... Run report per log (one log = one run), then a summary with blocker signatures\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"
|
||||
}
|
||||
@@ -233,8 +234,234 @@ fn local_setting(env_name: &str, key: &str, config: &BTreeMap<String, String>) -
|
||||
const TARGET_EXE_KEY: &str = "target_exe";
|
||||
const GDK_ROOT_KEY: &str = "gdk_root";
|
||||
|
||||
/// An Xbox Series title's executable is recognised by structure, never by name: a large PE32+
|
||||
/// file that imports the console's D3D12 library. BetterXen's own test executables import it
|
||||
/// too, but they are small and live in build folders the search skips.
|
||||
const TITLE_IMPORT: &str = "d3d12_xs.dll";
|
||||
const TITLE_MIN_BYTES: u64 = 16 << 20;
|
||||
|
||||
fn looks_like_title(path: &Path) -> bool {
|
||||
let large = fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() >= TITLE_MIN_BYTES);
|
||||
if !large {
|
||||
return false;
|
||||
}
|
||||
let Ok(bytes) = fs::read(path) else {
|
||||
return false;
|
||||
};
|
||||
probe_pe32_plus(&bytes).is_ok_and(|pe| {
|
||||
pe.imports
|
||||
.keys()
|
||||
.any(|dll| dll.eq_ignore_ascii_case(TITLE_IMPORT))
|
||||
})
|
||||
}
|
||||
|
||||
/// The folder to remember for a GDK header found at `header`: the first folder below a
|
||||
/// well-known top-level folder of `home` (Documents, Downloads, ...), or below `home` itself.
|
||||
fn gdk_root_for(home: &Path, header: &Path) -> Option<PathBuf> {
|
||||
const TOP_LEVEL: &[&str] = &["Documents", "Downloads", "Desktop", "Developer", "Projects"];
|
||||
let relative = header.strip_prefix(home).ok()?;
|
||||
let mut parts = relative.components();
|
||||
let first = parts.next()?.as_os_str().to_owned();
|
||||
let mut root = home.join(&first);
|
||||
if TOP_LEVEL.iter().any(|name| first == *name) {
|
||||
root = root.join(parts.next()?.as_os_str());
|
||||
}
|
||||
(root.is_dir() && root != header).then_some(root)
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
struct Found {
|
||||
gdk_roots: Vec<PathBuf>,
|
||||
target_exes: Vec<PathBuf>,
|
||||
/// The search gave up before visiting everything.
|
||||
truncated: bool,
|
||||
}
|
||||
|
||||
/// Searches `home` for the GDK (by its header) and for Xbox Series executables (by structure).
|
||||
/// Hidden folders, `Library`, application bundles and build folders are skipped, and the walk is
|
||||
/// bounded so it always ends.
|
||||
fn search_for_materials(home: &Path) -> Found {
|
||||
const MAX_DEPTH: usize = 14;
|
||||
const MAX_ENTRIES: usize = 3_000_000;
|
||||
const SKIP: &[&str] = &[
|
||||
"Library",
|
||||
"node_modules",
|
||||
"target",
|
||||
"build-shims",
|
||||
"Applications",
|
||||
];
|
||||
let mut found = Found::default();
|
||||
let mut seen = 0usize;
|
||||
let mut stack = vec![(home.to_path_buf(), 0usize)];
|
||||
while let Some((dir, depth)) = stack.pop() {
|
||||
let Ok(entries) = fs::read_dir(&dir) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
seen += 1;
|
||||
if seen > MAX_ENTRIES {
|
||||
found.truncated = true;
|
||||
return found;
|
||||
}
|
||||
let name = entry.file_name();
|
||||
let name_text = name.to_string_lossy();
|
||||
let Ok(kind) = entry.file_type() else {
|
||||
continue;
|
||||
};
|
||||
let path = entry.path();
|
||||
if kind.is_dir() {
|
||||
let skip = name_text.starts_with('.')
|
||||
|| name_text.ends_with(".app")
|
||||
|| name_text.ends_with(".photoslibrary")
|
||||
|| SKIP.iter().any(|s| name_text == *s);
|
||||
if !skip && depth < MAX_DEPTH {
|
||||
stack.push((path, depth + 1));
|
||||
}
|
||||
} else if kind.is_file() {
|
||||
if name_text == GDK_MARKER {
|
||||
if let Some(root) = gdk_root_for(home, &path)
|
||||
&& !found.gdk_roots.contains(&root)
|
||||
&& check_gdk_root(root.to_str()).is_ok()
|
||||
{
|
||||
found.gdk_roots.push(root);
|
||||
}
|
||||
} else if name_text.to_ascii_lowercase().ends_with(".exe")
|
||||
&& looks_like_title(&path)
|
||||
{
|
||||
found.target_exes.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
found.gdk_roots.sort();
|
||||
found.target_exes.sort();
|
||||
// The GDK ships tools that import the same library; they are not titles.
|
||||
let roots = found.gdk_roots.clone();
|
||||
found
|
||||
.target_exes
|
||||
.retain(|exe| !roots.iter().any(|root| exe.starts_with(root)));
|
||||
found.target_exes = distinct_builds(std::mem::take(&mut found.target_exes));
|
||||
found
|
||||
}
|
||||
|
||||
fn content_hash(path: &Path) -> Option<(u64, u64)> {
|
||||
let bytes = fs::read(path).ok()?;
|
||||
// FNV-1a: only to tell copies of one file from different files, never recorded anywhere.
|
||||
let hash = bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, b| {
|
||||
(h ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3)
|
||||
});
|
||||
Some((bytes.len() as u64, hash))
|
||||
}
|
||||
|
||||
/// How many of the DLLs an executable imports are present in its own folder. A title ships some
|
||||
/// of its DLLs beside it, so the real installation scores higher than a stray copy of the file.
|
||||
fn companion_dlls(path: &Path) -> usize {
|
||||
let Some(dir) = path.parent() else {
|
||||
return 0;
|
||||
};
|
||||
let Ok(bytes) = fs::read(path) else {
|
||||
return 0;
|
||||
};
|
||||
let Ok(pe) = probe_pe32_plus(&bytes) else {
|
||||
return 0;
|
||||
};
|
||||
let present: Vec<String> = fs::read_dir(dir)
|
||||
.map(|entries| {
|
||||
entries
|
||||
.flatten()
|
||||
.map(|e| e.file_name().to_string_lossy().to_ascii_lowercase())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
pe.imports
|
||||
.keys()
|
||||
.filter(|dll| present.contains(&dll.to_ascii_lowercase()))
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Byte-identical copies are one build. Of the copies, the one with the most of its imported
|
||||
/// DLLs beside it is kept: that is the installation, and the others are stray copies of the file.
|
||||
fn distinct_builds(candidates: Vec<PathBuf>) -> Vec<PathBuf> {
|
||||
distinct_builds_by(candidates, companion_dlls)
|
||||
}
|
||||
|
||||
fn distinct_builds_by(candidates: Vec<PathBuf>, siblings: impl Fn(&Path) -> usize) -> Vec<PathBuf> {
|
||||
let mut builds: Vec<((u64, u64), PathBuf)> = Vec::new();
|
||||
for path in candidates {
|
||||
let Some(identity) = content_hash(&path) else {
|
||||
continue;
|
||||
};
|
||||
match builds.iter_mut().find(|(known, _)| *known == identity) {
|
||||
Some((_, kept)) => {
|
||||
if siblings(&path) > siblings(kept) {
|
||||
*kept = path;
|
||||
}
|
||||
}
|
||||
None => builds.push((identity, path)),
|
||||
}
|
||||
}
|
||||
builds.into_iter().map(|(_, path)| path).collect()
|
||||
}
|
||||
|
||||
/// `bx-cli setup --find`: fills in whichever of the two settings is not already valid. A GDK is
|
||||
/// a GDK, so the first one found is used. A target build is saved only when exactly one is found:
|
||||
/// which build to use is the collaborator's choice, not the tool's.
|
||||
fn find_materials(config: &mut BTreeMap<String, String>) -> bool {
|
||||
let need_target = check_target_exe(config.get(TARGET_EXE_KEY).map(String::as_str)).is_err();
|
||||
let need_gdk = check_gdk_root(config.get(GDK_ROOT_KEY).map(String::as_str)).is_err();
|
||||
if !need_target && !need_gdk {
|
||||
return false;
|
||||
}
|
||||
let Some(home) = env::var_os("HOME").map(PathBuf::from) else {
|
||||
eprintln!("--find: no HOME to search");
|
||||
return false;
|
||||
};
|
||||
println!(
|
||||
"Searching the home folder for the GDK and the target build (this can take a minute)..."
|
||||
);
|
||||
let found = search_for_materials(&home);
|
||||
let mut changed = false;
|
||||
if need_gdk {
|
||||
match found.gdk_roots.first() {
|
||||
Some(root) => {
|
||||
config.insert(GDK_ROOT_KEY.to_owned(), root.to_string_lossy().into_owned());
|
||||
changed = true;
|
||||
println!(" GDK : found and saved");
|
||||
}
|
||||
None => println!(" GDK : not found in the home folder"),
|
||||
}
|
||||
}
|
||||
if need_target {
|
||||
match found.target_exes.as_slice() {
|
||||
[only] => {
|
||||
config.insert(
|
||||
TARGET_EXE_KEY.to_owned(),
|
||||
only.to_string_lossy().into_owned(),
|
||||
);
|
||||
changed = true;
|
||||
println!(" target build : found and saved");
|
||||
}
|
||||
[] => println!(" target build : no Xbox Series executable found in the home folder"),
|
||||
several => {
|
||||
println!(
|
||||
" target build : {} Xbox Series executables found; choose one with --target-exe:",
|
||||
several.len()
|
||||
);
|
||||
for path in several {
|
||||
println!(" {}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if found.truncated {
|
||||
println!(" (the search stopped early: the home folder has too many entries)");
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// `bx-cli setup`: checks the given paths with the same rules as preflight and remembers them.
|
||||
/// With no arguments it shows what is saved, as present or missing, without printing a path.
|
||||
/// `--find` searches the home folder for whatever is not set. With no arguments it shows what
|
||||
/// is saved, as present or missing, without printing a path.
|
||||
fn cmd_setup(args: &[String]) -> ExitCode {
|
||||
let Some(path) = local_config_path() else {
|
||||
eprintln!("error: no HOME or XDG_CONFIG_HOME to keep local settings in");
|
||||
@@ -243,7 +470,13 @@ fn cmd_setup(args: &[String]) -> ExitCode {
|
||||
let mut config = read_local_config(&path);
|
||||
let mut i = 0;
|
||||
let mut changed = false;
|
||||
let mut find = false;
|
||||
while i < args.len() {
|
||||
if args[i] == "--find" {
|
||||
find = true;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let (key, check): (&str, SettingCheck) = match args[i].as_str() {
|
||||
"--target-exe" => (TARGET_EXE_KEY, check_target_exe),
|
||||
"--gdk-root" => (GDK_ROOT_KEY, check_gdk_root),
|
||||
@@ -267,6 +500,9 @@ fn cmd_setup(args: &[String]) -> ExitCode {
|
||||
changed = true;
|
||||
i += 2;
|
||||
}
|
||||
if find {
|
||||
changed |= find_materials(&mut config);
|
||||
}
|
||||
if changed && let Err(e) = write_local_config(&path, &config) {
|
||||
eprintln!("error: could not save local settings: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
@@ -291,7 +527,7 @@ fn cmd_setup(args: &[String]) -> ExitCode {
|
||||
/// The target build: the setting must name a readable PE file.
|
||||
fn check_target_exe(value: Option<&str>) -> Result<String, String> {
|
||||
let path = value.filter(|v| !v.is_empty()).ok_or(
|
||||
"not set; run `bx-cli setup --target-exe <path to the target build's executable>`",
|
||||
"not set; run `bx-cli setup --find`, or `bx-cli setup --target-exe <path to the target build's executable>`",
|
||||
)?;
|
||||
let mut magic = [0u8; 2];
|
||||
let read = fs::File::open(path).and_then(|mut f| std::io::Read::read_exact(&mut f, &mut magic));
|
||||
@@ -306,7 +542,7 @@ fn check_target_exe(value: Option<&str>) -> Result<String, String> {
|
||||
fn check_gdk_root(value: Option<&str>) -> Result<String, String> {
|
||||
let root = value
|
||||
.filter(|v| !v.is_empty())
|
||||
.ok_or("not set; run `bx-cli setup --gdk-root <folder that holds the GDK>`")?;
|
||||
.ok_or("not set; run `bx-cli setup --find`, or `bx-cli setup --gdk-root <folder that holds the GDK>`")?;
|
||||
let root = Path::new(root);
|
||||
if !root.is_dir() {
|
||||
return Err("the saved path is not a folder".to_owned());
|
||||
@@ -351,7 +587,9 @@ fn render_preflight(requirements: &[Requirement]) -> (String, bool) {
|
||||
out.push_str(if ready {
|
||||
"Ready to work.\n"
|
||||
} else {
|
||||
"Not ready. Do not start work: tell the person you work for what is missing (AGENTS.md section 0).\n"
|
||||
"Not ready. Fix what you can yourself (AGENTS.md section 0, step 1): `bx-cli setup --find` for the \
|
||||
target build and the GDK, Homebrew for missing tools, your own scratch files for disk space. \
|
||||
Stop only for what is not on this machine.\n"
|
||||
});
|
||||
(out, ready)
|
||||
}
|
||||
@@ -656,6 +894,47 @@ fn cmd_trace(path: &str) -> ExitCode {
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
/// `bx-cli report <log>...`: each log is one run. Prints every run's report, then the summary
|
||||
/// whose signatures blocker issues are titled with (docs/process/working-method.md).
|
||||
fn cmd_report(paths: &[String]) -> ExitCode {
|
||||
let mut runs = Vec::new();
|
||||
for path in paths {
|
||||
let bytes = match fs::read(path) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) => {
|
||||
eprintln!("error reading {path}: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
// Guest text may not be valid UTF-8; the records that matter are ASCII.
|
||||
let report = bx_telemetry::report::report_run(&String::from_utf8_lossy(&bytes));
|
||||
let name = Path::new(path)
|
||||
.file_stem()
|
||||
.map_or_else(|| path.clone(), |stem| stem.to_string_lossy().into_owned());
|
||||
print!("{}", bx_telemetry::report::render_run(&name, &report));
|
||||
runs.push((name, report));
|
||||
}
|
||||
print!("\n{}", bx_telemetry::report::render_summary(&runs));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
/// The record `bx-cli run` appends to the log when the run is over, so a log says how its run
|
||||
/// ended (`bx-cli report` reads it). It carries no guest timestamp.
|
||||
fn run_end_record(outcome: &std::io::Result<Outcome>) -> String {
|
||||
let detail = match outcome {
|
||||
Ok(Outcome::Exited(status)) => match status.code() {
|
||||
Some(code) => format!("outcome=exited status={code}"),
|
||||
None => "outcome=signal signal=0".to_owned(),
|
||||
},
|
||||
Ok(Outcome::Stopped(Stop::TimedOut)) => "outcome=timeout".to_owned(),
|
||||
Ok(Outcome::Stopped(Stop::Signalled(signal))) => format!("outcome=signal signal={signal}"),
|
||||
Err(_) => "outcome=launch_failed".to_owned(),
|
||||
};
|
||||
format!(
|
||||
"{{\"ts_ms\":0,\"tid\":0,\"level\":\"INFO\",\"sub\":\"bx_cli\",\"event\":\"run_end\",\"detail\":\"{detail}\"}}\n"
|
||||
)
|
||||
}
|
||||
|
||||
fn render_trace(text: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let summary = summarize_jsonl(text);
|
||||
@@ -1368,6 +1647,14 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// The log says how its run ended. A log that cannot be appended to is not a reason to
|
||||
// fail the run.
|
||||
if let Some(log) = &abs_log
|
||||
&& let Ok(mut file) = fs::OpenOptions::new().append(true).create(true).open(log)
|
||||
{
|
||||
let _ = file.write_all(run_end_record(&outcome).as_bytes());
|
||||
}
|
||||
|
||||
// Printed for failed and stopped runs too, which is when it matters most. The log is
|
||||
// appended to across runs, so only what this run added is summarized.
|
||||
if let Some(log) = &abs_log
|
||||
@@ -1487,7 +1774,7 @@ impl<'a> Dispatch<'a> {
|
||||
};
|
||||
match sub.as_str() {
|
||||
"--help" | "-h" | "help" => Dispatch::Help,
|
||||
"doctor" | "setup" | "preflight" | "probe" | "shader" | "trace" | "run" => {
|
||||
"doctor" | "setup" | "preflight" | "probe" | "shader" | "trace" | "report" | "run" => {
|
||||
Dispatch::Sub(sub.as_str())
|
||||
}
|
||||
_ => Dispatch::Unknown(sub.as_str()),
|
||||
@@ -1523,6 +1810,7 @@ fn main() -> ExitCode {
|
||||
"probe" if args.len() >= 2 => cmd_probe(&args[1]),
|
||||
"shader" if args.len() >= 2 => cmd_shader(&args[1]),
|
||||
"trace" if args.len() >= 2 => cmd_trace(&args[1]),
|
||||
"report" if args.len() >= 2 => cmd_report(&args[1..]),
|
||||
"run" => cmd_run(&args[1..]),
|
||||
// Only reachable when a subcommand that needs an argument got none.
|
||||
_ => {
|
||||
@@ -2246,6 +2534,7 @@ sub setup_bottle_wineprefix {
|
||||
"probe",
|
||||
"shader",
|
||||
"trace",
|
||||
"report",
|
||||
"run",
|
||||
] {
|
||||
let argv = args(&[real]);
|
||||
@@ -2269,7 +2558,7 @@ sub setup_bottle_wineprefix {
|
||||
assert!(
|
||||
check_target_exe(None)
|
||||
.unwrap_err()
|
||||
.contains("bx-cli setup --target-exe")
|
||||
.contains("bx-cli setup --find")
|
||||
);
|
||||
let missing = dir.join("none.exe");
|
||||
assert!(
|
||||
@@ -2310,7 +2599,7 @@ sub setup_bottle_wineprefix {
|
||||
]);
|
||||
assert!(!ready);
|
||||
assert!(text.contains("MISSING GDK"), "{text}");
|
||||
assert!(text.contains("Do not start work"), "{text}");
|
||||
assert!(text.contains("Fix what you can yourself"), "{text}");
|
||||
let (text, ready) = render_preflight(&[("Target build", Ok("present".to_owned()))]);
|
||||
assert!(ready && text.contains("Ready to work."), "{text}");
|
||||
|
||||
@@ -2354,6 +2643,90 @@ sub setup_bottle_wineprefix {
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `setup --find`: the GDK is recognised by its header and remembered as the first folder
|
||||
/// below Documents; build folders and hidden folders are not searched; a small executable
|
||||
/// is not taken for a title.
|
||||
#[test]
|
||||
fn find_recognises_the_gdk_and_skips_what_is_not_a_title() {
|
||||
let home = env::temp_dir().join(format!("bx-find-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&home);
|
||||
let header_dir = home.join("Documents/sdk/pkg/xbox/include/gen9");
|
||||
fs::create_dir_all(&header_dir).unwrap();
|
||||
fs::write(header_dir.join(GDK_MARKER), b"// header").unwrap();
|
||||
// The same header in places the search must not look.
|
||||
for skipped in [
|
||||
".hidden/x",
|
||||
"Library/x",
|
||||
"Documents/proj/build-shims/x",
|
||||
"Documents/proj/target/x",
|
||||
] {
|
||||
fs::create_dir_all(home.join(skipped)).unwrap();
|
||||
fs::write(home.join(skipped).join(GDK_MARKER), b"// header").unwrap();
|
||||
}
|
||||
// A small PE-looking file and a non-PE .exe: neither is a title.
|
||||
fs::create_dir_all(home.join("Documents/game")).unwrap();
|
||||
fs::write(home.join("Documents/game/small.exe"), b"MZ\x90\x00").unwrap();
|
||||
|
||||
let found = search_for_materials(&home);
|
||||
assert_eq!(found.gdk_roots, vec![home.join("Documents/sdk")]);
|
||||
assert!(found.target_exes.is_empty());
|
||||
assert!(!found.truncated);
|
||||
|
||||
assert_eq!(
|
||||
gdk_root_for(&home, &home.join("sdk2/include/d3d12_xs.h")),
|
||||
None,
|
||||
"a folder that does not exist is not a root"
|
||||
);
|
||||
fs::create_dir_all(home.join("sdk2/include")).unwrap();
|
||||
assert_eq!(
|
||||
gdk_root_for(&home, &home.join("sdk2/include/d3d12_xs.h")),
|
||||
Some(home.join("sdk2")),
|
||||
"directly below home, the first folder is the root"
|
||||
);
|
||||
assert!(!looks_like_title(&home.join("Documents/game/small.exe")));
|
||||
assert!(!looks_like_title(&home.join("Documents/game/absent.exe")));
|
||||
|
||||
// Identical copies are one build, kept where the folder is fullest; a different file is
|
||||
// another build.
|
||||
let full = home.join("Documents/install");
|
||||
let stray = home.join("Downloads");
|
||||
fs::create_dir_all(&full).unwrap();
|
||||
fs::create_dir_all(&stray).unwrap();
|
||||
fs::write(full.join("title.exe"), b"same bytes").unwrap();
|
||||
fs::write(full.join("data1.pak"), b"x").unwrap();
|
||||
fs::write(full.join("data2.pak"), b"x").unwrap();
|
||||
fs::write(stray.join("title.exe"), b"same bytes").unwrap();
|
||||
fs::write(home.join("Documents/game/other.exe"), b"other bytes").unwrap();
|
||||
// Synthetic files are not PE images, so the folder is scored here by its entry count;
|
||||
// real candidates are scored by the imported DLLs found beside them.
|
||||
let entries = |path: &Path| {
|
||||
path.parent()
|
||||
.and_then(|dir| fs::read_dir(dir).ok())
|
||||
.map_or(0, Iterator::count)
|
||||
};
|
||||
let kept = distinct_builds_by(
|
||||
vec![
|
||||
stray.join("title.exe"),
|
||||
full.join("title.exe"),
|
||||
home.join("Documents/game/other.exe"),
|
||||
],
|
||||
entries,
|
||||
);
|
||||
assert_eq!(
|
||||
companion_dlls(&full.join("title.exe")),
|
||||
0,
|
||||
"not a PE image: no companions"
|
||||
);
|
||||
assert_eq!(
|
||||
kept,
|
||||
vec![
|
||||
full.join("title.exe"),
|
||||
home.join("Documents/game/other.exe")
|
||||
]
|
||||
);
|
||||
let _ = fs::remove_dir_all(&home);
|
||||
}
|
||||
|
||||
/// The usage text must name every subcommand, so the classifier above is
|
||||
/// not testing a table that nothing prints.
|
||||
#[test]
|
||||
@@ -2370,6 +2743,7 @@ sub setup_bottle_wineprefix {
|
||||
"probe",
|
||||
"shader",
|
||||
"trace",
|
||||
"report",
|
||||
"run",
|
||||
] {
|
||||
assert!(text.contains(sub), "usage documents {sub}");
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub mod report;
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct TraceSummary {
|
||||
pub total_lines: usize,
|
||||
|
||||
@@ -0,0 +1,582 @@
|
||||
//! Run reports for the blocker queue (docs/process/working-method.md, "Run protocol").
|
||||
//!
|
||||
//! One JSONL log is one run. [`report_run`] reduces it to what decides the next task: how the
|
||||
//! run ended, how far it got, and everything it stopped on. [`RunReport::signatures`] turns
|
||||
//! those into the fixed strings blocker issues are titled with, so two people who hit the
|
||||
//! same thing file the same issue. [`render_summary`] puts several runs side by side.
|
||||
//!
|
||||
//! What a log cannot show is said, not guessed: a run with no `run_end` record has an unknown
|
||||
//! outcome, and a stall cannot be told from slow presentation because frames are logged at
|
||||
//! powers of two.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
/// BetterXen's own guest modules. A fault whose innermost frame is in one of them is ours.
|
||||
const BETTERXEN_MODULES: &[&str] = &[
|
||||
"d3d12_xs.dll",
|
||||
"xmem.dll",
|
||||
"xcrdapi.dll",
|
||||
"xgameruntime.dll",
|
||||
"xg_xs.dll",
|
||||
"acphal.dll",
|
||||
"xapu.dll",
|
||||
"chad.dll",
|
||||
"gameinput.dll",
|
||||
"bx_runtime_veh.dll",
|
||||
"bx_shader_bridge.dll",
|
||||
"ffx_bvh_hooks.dll",
|
||||
];
|
||||
|
||||
/// How a run ended, from the launcher's `run_end` record.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub enum RunEnd {
|
||||
/// No `run_end` record: the launcher was killed, or the log predates the record.
|
||||
#[default]
|
||||
Unknown,
|
||||
/// The guest exited by itself with this status.
|
||||
Exited(i32),
|
||||
/// The launcher's `--timeout` stopped it: the run lasted as long as it was allowed to.
|
||||
TimedOut,
|
||||
/// A signal stopped the launcher.
|
||||
Signalled(i32),
|
||||
/// CrossOver could not be started.
|
||||
LaunchFailed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct RunReport {
|
||||
pub events: u64,
|
||||
/// Guest clock span of the log, in milliseconds.
|
||||
pub span_ms: u64,
|
||||
pub end: RunEnd,
|
||||
/// The last power-of-two frame count logged: at least this many frames were presented.
|
||||
pub frames_at_least: Option<u64>,
|
||||
/// Unimplemented calls reached, by signature, with how often.
|
||||
pub unimplemented: BTreeMap<String, u64>,
|
||||
/// Faults whose innermost frame is in a BetterXen module, by module.
|
||||
pub faults: BTreeMap<String, u64>,
|
||||
/// Exceptions nothing handled.
|
||||
pub unhandled_exceptions: u64,
|
||||
/// Pipeline stages that reached the shader gate, by "kind decision" (for example
|
||||
/// "stream reject_unclassified_dxil").
|
||||
pub shader_gate: BTreeMap<String, u64>,
|
||||
/// Refused pipeline creations by kind.
|
||||
pub pipelines_refused: BTreeMap<String, u64>,
|
||||
/// Draws and dispatches skipped with a null pipeline bound (a lower bound).
|
||||
pub skipped_work_at_least: Option<u64>,
|
||||
}
|
||||
|
||||
fn json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
|
||||
let needle = format!("\"{key}\":\"");
|
||||
let start = line.find(&needle)? + needle.len();
|
||||
let rest = &line[start..];
|
||||
// Details do not contain escaped quotes in practice; stop at the first unescaped one.
|
||||
let mut end = 0;
|
||||
let bytes = rest.as_bytes();
|
||||
while end < bytes.len() {
|
||||
if bytes[end] == b'"' && (end == 0 || bytes[end - 1] != b'\\') {
|
||||
return Some(&rest[..end]);
|
||||
}
|
||||
end += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn json_u64(line: &str, key: &str) -> Option<u64> {
|
||||
let needle = format!("\"{key}\":");
|
||||
let start = line.find(&needle)? + needle.len();
|
||||
let digits = &line[start..];
|
||||
let end = digits
|
||||
.find(|c: char| !c.is_ascii_digit())
|
||||
.unwrap_or(digits.len());
|
||||
digits[..end].parse().ok()
|
||||
}
|
||||
|
||||
fn number_after(detail: &str, key: &str) -> Option<u64> {
|
||||
let start = detail.find(key)? + key.len();
|
||||
let digits = &detail[start..];
|
||||
let end = digits
|
||||
.find(|c: char| !c.is_ascii_digit())
|
||||
.unwrap_or(digits.len());
|
||||
digits[..end].parse().ok()
|
||||
}
|
||||
|
||||
/// `IXUser[3]::slot_3` -> `unimplemented IXUser slot 3`;
|
||||
/// `XboxDevice[81]::GetFrameStatisticsX` -> `unimplemented XboxDevice slot 81 (GetFrameStatisticsX)`.
|
||||
fn vtable_signature(detail: &str) -> String {
|
||||
let parsed = (|| {
|
||||
let open = detail.find('[')?;
|
||||
let close = detail[open..].find(']')? + open;
|
||||
let slot: u32 = detail[open + 1..close].parse().ok()?;
|
||||
let method = detail[close + 1..].strip_prefix("::")?;
|
||||
Some((&detail[..open], slot, method))
|
||||
})();
|
||||
match parsed {
|
||||
Some((interface, slot, method)) if method.starts_with("slot_") || method.is_empty() => {
|
||||
format!("unimplemented {interface} slot {slot}")
|
||||
}
|
||||
Some((interface, slot, method)) => {
|
||||
format!("unimplemented {interface} slot {slot} ({method})")
|
||||
}
|
||||
None => format!("unimplemented {detail}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The module of the innermost stack frame in an `av_context` detail (`... | stack: A.dll+12 B.dll+34`).
|
||||
fn fault_module(detail: &str) -> Option<&str> {
|
||||
let stack = detail.split("stack: ").nth(1)?;
|
||||
let frame = stack.split_whitespace().next()?;
|
||||
Some(frame.split('+').next().unwrap_or(frame))
|
||||
}
|
||||
|
||||
fn is_betterxen_module(module: &str) -> bool {
|
||||
BETTERXEN_MODULES
|
||||
.iter()
|
||||
.any(|m| m.eq_ignore_ascii_case(module))
|
||||
}
|
||||
|
||||
/// Reduces one run's JSONL log to its report.
|
||||
pub fn report_run(input: &str) -> RunReport {
|
||||
let mut report = RunReport::default();
|
||||
let mut first_ts = None;
|
||||
let mut last_ts = 0;
|
||||
for line in input.lines() {
|
||||
let line = line.trim();
|
||||
if !line.starts_with('{') {
|
||||
continue;
|
||||
}
|
||||
report.events += 1;
|
||||
let event = json_str(line, "event").unwrap_or("");
|
||||
let detail = json_str(line, "detail").unwrap_or("");
|
||||
if event == "run_end" {
|
||||
report.end = match detail {
|
||||
d if d.starts_with("outcome=exited") => {
|
||||
let status = d
|
||||
.split("status=")
|
||||
.nth(1)
|
||||
.and_then(|s| s.trim().parse().ok());
|
||||
status.map_or(RunEnd::Unknown, RunEnd::Exited)
|
||||
}
|
||||
"outcome=timeout" => RunEnd::TimedOut,
|
||||
d if d.starts_with("outcome=signal") => {
|
||||
RunEnd::Signalled(number_after(d, "signal=").unwrap_or(0) as i32)
|
||||
}
|
||||
"outcome=launch_failed" => RunEnd::LaunchFailed,
|
||||
_ => RunEnd::Unknown,
|
||||
};
|
||||
continue; // the launcher's record carries no guest timestamp
|
||||
}
|
||||
if let Some(ts) = json_u64(line, "ts_ms") {
|
||||
first_ts.get_or_insert(ts);
|
||||
last_ts = last_ts.max(ts);
|
||||
}
|
||||
match event {
|
||||
"presentx_frames" => {
|
||||
if let Some(n) = number_after(detail, "presented=") {
|
||||
report.frames_at_least = Some(report.frames_at_least.unwrap_or(0).max(n));
|
||||
}
|
||||
}
|
||||
"unimpl_vtable" => {
|
||||
*report
|
||||
.unimplemented
|
||||
.entry(vtable_signature(detail))
|
||||
.or_default() += 1
|
||||
}
|
||||
"unimpl_api" => {
|
||||
*report
|
||||
.unimplemented
|
||||
.entry(format!("unimplemented {detail}"))
|
||||
.or_default() += 1
|
||||
}
|
||||
"av_context" => {
|
||||
if let Some(module) = fault_module(detail).filter(|m| is_betterxen_module(m)) {
|
||||
*report.faults.entry(module.to_owned()).or_default() += 1;
|
||||
}
|
||||
}
|
||||
"unhandled_exception" => report.unhandled_exceptions += 1,
|
||||
"shader_gate" => {
|
||||
let kind = detail
|
||||
.split("pso=")
|
||||
.nth(1)
|
||||
.and_then(|s| s.split_whitespace().next());
|
||||
let decision = detail
|
||||
.split("decision=")
|
||||
.nth(1)
|
||||
.and_then(|s| s.split_whitespace().next());
|
||||
if let (Some(kind), Some(decision)) = (kind, decision) {
|
||||
*report
|
||||
.shader_gate
|
||||
.entry(format!("{kind} {decision}"))
|
||||
.or_default() += 1;
|
||||
}
|
||||
}
|
||||
"pipeline_refused" => {
|
||||
let kind = detail.split(" pipeline refused").next().unwrap_or(detail);
|
||||
*report.pipelines_refused.entry(kind.to_owned()).or_default() += 1;
|
||||
}
|
||||
"null_render_skip" => {
|
||||
if let Some(n) = number_after(detail, "total skipped=") {
|
||||
report.skipped_work_at_least =
|
||||
Some(report.skipped_work_at_least.unwrap_or(0).max(n));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
report.span_ms = first_ts.map_or(0, |first| last_ts.saturating_sub(first));
|
||||
report
|
||||
}
|
||||
|
||||
impl RunReport {
|
||||
/// The strings blocker issues are titled with (`[blocker] <signature>`), most severe first.
|
||||
pub fn signatures(&self) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
match self.end {
|
||||
RunEnd::Exited(status) if status != 0 => out.push(format!("exit status {status}")),
|
||||
RunEnd::LaunchFailed => out.push("launch failed".to_owned()),
|
||||
_ => {}
|
||||
}
|
||||
if self.unhandled_exceptions > 0 {
|
||||
out.push("unhandled exception".to_owned());
|
||||
}
|
||||
out.extend(
|
||||
self.faults
|
||||
.keys()
|
||||
.map(|module| format!("fault in {module}")),
|
||||
);
|
||||
out.extend(self.unimplemented.keys().cloned());
|
||||
if self.skipped_work_at_least.is_some() {
|
||||
out.push("draws or dispatches skipped with a null pipeline".to_owned());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// True when the run reached the frame loop and stopped on nothing: the Boot gate's
|
||||
/// per-run condition, except for its length, which the caller sets with `--timeout`.
|
||||
pub fn clean_boot(&self) -> bool {
|
||||
self.end == RunEnd::TimedOut
|
||||
&& self.frames_at_least.is_some()
|
||||
&& self.unimplemented.is_empty()
|
||||
&& self.faults.is_empty()
|
||||
&& self.unhandled_exceptions == 0
|
||||
}
|
||||
}
|
||||
|
||||
fn end_text(end: &RunEnd) -> String {
|
||||
match end {
|
||||
RunEnd::Unknown => "unknown (no run_end record)".to_owned(),
|
||||
RunEnd::Exited(status) => format!("exited by itself, status {status}"),
|
||||
RunEnd::TimedOut => "ran until the timeout".to_owned(),
|
||||
RunEnd::Signalled(signal) => format!("stopped by signal {signal}"),
|
||||
RunEnd::LaunchFailed => "launch failed".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The report of one run, as text.
|
||||
pub fn render_run(name: &str, report: &RunReport) -> String {
|
||||
let mut out = String::new();
|
||||
let _ = writeln!(out, "Run {name}");
|
||||
let _ = writeln!(out, " outcome : {}", end_text(&report.end));
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" frames presented : {}",
|
||||
report
|
||||
.frames_at_least
|
||||
.map_or("none".to_owned(), |n| format!("at least {n}"))
|
||||
);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" log span : {:.1} s, {} events",
|
||||
report.span_ms as f64 / 1000.0,
|
||||
report.events
|
||||
);
|
||||
if !report.unimplemented.is_empty() {
|
||||
let _ = writeln!(out, " unimplemented calls:");
|
||||
for (signature, count) in &report.unimplemented {
|
||||
let _ = writeln!(out, " {count:>7}x {signature}");
|
||||
}
|
||||
}
|
||||
if !report.faults.is_empty() || report.unhandled_exceptions > 0 {
|
||||
let _ = writeln!(out, " faults:");
|
||||
for (module, count) in &report.faults {
|
||||
let _ = writeln!(out, " {count:>7}x fault in {module}");
|
||||
}
|
||||
if report.unhandled_exceptions > 0 {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" {:>7}x unhandled exception",
|
||||
report.unhandled_exceptions
|
||||
);
|
||||
}
|
||||
}
|
||||
if !report.shader_gate.is_empty() || !report.pipelines_refused.is_empty() {
|
||||
let _ = writeln!(out, " pipelines:");
|
||||
for (kind, count) in &report.shader_gate {
|
||||
let _ = writeln!(out, " {count:>7}x shader stage: {kind}");
|
||||
}
|
||||
for (kind, count) in &report.pipelines_refused {
|
||||
let _ = writeln!(out, " {count:>7}x refused: {kind}");
|
||||
}
|
||||
if let Some(skipped) = report.skipped_work_at_least {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" at least {skipped} draws or dispatches skipped (null pipeline)"
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Several runs side by side, then every signature with the number of runs that hit it.
|
||||
pub fn render_summary(runs: &[(String, RunReport)]) -> String {
|
||||
let mut out = String::new();
|
||||
let total = runs.len();
|
||||
let _ = writeln!(out, "Summary of {total} run(s)");
|
||||
for (name, report) in runs {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" {name}: {}; frames {}; {}",
|
||||
end_text(&report.end),
|
||||
report
|
||||
.frames_at_least
|
||||
.map_or("none".to_owned(), |n| format!(">= {n}")),
|
||||
if report.clean_boot() {
|
||||
"clean"
|
||||
} else {
|
||||
"not clean"
|
||||
}
|
||||
);
|
||||
}
|
||||
let clean = runs.iter().filter(|(_, r)| r.clean_boot()).count();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"Clean runs (frame loop reached, nothing stopped on, ran to the timeout): {clean} of {total}"
|
||||
);
|
||||
let mut hits: BTreeMap<String, usize> = BTreeMap::new();
|
||||
for (_, report) in runs {
|
||||
for signature in report.signatures() {
|
||||
*hits.entry(signature).or_default() += 1;
|
||||
}
|
||||
}
|
||||
if hits.is_empty() {
|
||||
let _ = writeln!(out, "Signatures: none");
|
||||
} else {
|
||||
let _ = writeln!(out, "Signatures (runs that hit each):");
|
||||
let mut ordered: Vec<_> = hits.into_iter().collect();
|
||||
ordered.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
||||
for (signature, count) in ordered {
|
||||
let _ = writeln!(out, " {count} of {total} {signature}");
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn line(ts: u64, sub: &str, event: &str, detail: &str) -> String {
|
||||
format!(
|
||||
"{{\"ts_ms\":{ts},\"tid\":1,\"level\":\"INFO\",\"sub\":\"{sub}\",\"event\":\"{event}\",\"detail\":\"{detail}\"}}\n"
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clean_run_reports_frames_span_and_no_signatures() {
|
||||
let log = line(
|
||||
1000,
|
||||
"d3d12_xs",
|
||||
"presentx_frames",
|
||||
"frames presented=1 last hr=0x00000000",
|
||||
) + &line(
|
||||
4000,
|
||||
"d3d12_xs",
|
||||
"presentx_frames",
|
||||
"frames presented=64 last hr=0x00000000",
|
||||
) + &line(0, "bx_cli", "run_end", "outcome=timeout");
|
||||
let report = report_run(&log);
|
||||
assert_eq!(report.frames_at_least, Some(64));
|
||||
assert_eq!(
|
||||
report.span_ms, 3000,
|
||||
"the launcher's record must not stretch the guest span"
|
||||
);
|
||||
assert_eq!(report.end, RunEnd::TimedOut);
|
||||
assert!(report.clean_boot());
|
||||
assert!(report.signatures().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unimplemented_calls_become_stable_signatures() {
|
||||
let log = line(1, "com_vtable", "unimpl_vtable", "IXUser[3]::slot_3")
|
||||
+ &line(
|
||||
2,
|
||||
"com_vtable",
|
||||
"unimpl_vtable",
|
||||
"XboxDevice[81]::GetFrameStatisticsX",
|
||||
)
|
||||
+ &line(
|
||||
3,
|
||||
"com_vtable",
|
||||
"unimpl_vtable",
|
||||
"XboxDevice[81]::GetFrameStatisticsX",
|
||||
)
|
||||
+ &line(
|
||||
4,
|
||||
"stub",
|
||||
"unimpl_api",
|
||||
"d3d12_xs.dll!CreatePlacedResourceX(texture contents)",
|
||||
);
|
||||
let report = report_run(&log);
|
||||
assert_eq!(
|
||||
report.unimplemented.get("unimplemented IXUser slot 3"),
|
||||
Some(&1)
|
||||
);
|
||||
assert_eq!(
|
||||
report
|
||||
.unimplemented
|
||||
.get("unimplemented XboxDevice slot 81 (GetFrameStatisticsX)"),
|
||||
Some(&2)
|
||||
);
|
||||
assert!(report.signatures().contains(
|
||||
&"unimplemented d3d12_xs.dll!CreatePlacedResourceX(texture contents)".to_owned()
|
||||
));
|
||||
assert!(
|
||||
!report.clean_boot(),
|
||||
"an unimplemented call is not a clean run"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fault_counts_only_when_its_innermost_frame_is_a_betterxen_module() {
|
||||
let ours = line(
|
||||
1,
|
||||
"runtime_veh",
|
||||
"av_context",
|
||||
"rip=1 fault=2 | stack: XCRDAPI.dll+9a51 ntdll.dll+10",
|
||||
);
|
||||
let theirs = line(
|
||||
2,
|
||||
"runtime_veh",
|
||||
"av_context",
|
||||
"rip=1 fault=2 | stack: title.exe+10 XCRDAPI.dll+9a51",
|
||||
);
|
||||
let report = report_run(&(ours + &theirs));
|
||||
assert_eq!(report.faults.get("XCRDAPI.dll"), Some(&1));
|
||||
assert_eq!(report.faults.len(), 1);
|
||||
assert_eq!(report.signatures(), vec!["fault in XCRDAPI.dll".to_owned()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_of_a_run_is_read_from_the_launcher_record() {
|
||||
let exited = report_run(&line(0, "bx_cli", "run_end", "outcome=exited status=5"));
|
||||
assert_eq!(exited.end, RunEnd::Exited(5));
|
||||
assert_eq!(exited.signatures(), vec!["exit status 5".to_owned()]);
|
||||
assert_eq!(
|
||||
report_run(&line(0, "bx_cli", "run_end", "outcome=exited status=0")).signatures(),
|
||||
Vec::<String>::new()
|
||||
);
|
||||
assert_eq!(
|
||||
report_run(&line(0, "bx_cli", "run_end", "outcome=signal signal=15")).end,
|
||||
RunEnd::Signalled(15)
|
||||
);
|
||||
assert_eq!(
|
||||
report_run(&line(0, "bx_cli", "run_end", "outcome=launch_failed")).end,
|
||||
RunEnd::LaunchFailed
|
||||
);
|
||||
// No record: unknown, and never "clean".
|
||||
let unknown = report_run(&line(
|
||||
1,
|
||||
"d3d12_xs",
|
||||
"presentx_frames",
|
||||
"frames presented=8 last hr=0x0",
|
||||
));
|
||||
assert_eq!(unknown.end, RunEnd::Unknown);
|
||||
assert!(!unknown.clean_boot());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipelines_are_counted_by_kind() {
|
||||
let log = line(
|
||||
1,
|
||||
"d3d12_xs",
|
||||
"shader_gate",
|
||||
"pso=stream stage=VS decision=reject_unclassified_dxil hr=0x80004001",
|
||||
) + &line(
|
||||
2,
|
||||
"d3d12_xs",
|
||||
"shader_gate",
|
||||
"pso=compute stage=CS decision=pass_dxil hr=0x00000000",
|
||||
) + &line(
|
||||
3,
|
||||
"d3d12_xs",
|
||||
"pipeline_refused",
|
||||
"deserialized graphics (console code) pipeline refused hr=0x80004001",
|
||||
) + &line(
|
||||
4,
|
||||
"d3d12_xs",
|
||||
"null_render_skip",
|
||||
"DrawInstanced with a null pipeline bound; total skipped=4",
|
||||
) + &line(
|
||||
5,
|
||||
"d3d12_xs",
|
||||
"null_render_skip",
|
||||
"DrawInstanced with a null pipeline bound; total skipped=8",
|
||||
);
|
||||
let report = report_run(&log);
|
||||
assert_eq!(
|
||||
report.shader_gate.get("stream reject_unclassified_dxil"),
|
||||
Some(&1)
|
||||
);
|
||||
assert_eq!(report.shader_gate.get("compute pass_dxil"), Some(&1));
|
||||
assert_eq!(
|
||||
report
|
||||
.pipelines_refused
|
||||
.get("deserialized graphics (console code)"),
|
||||
Some(&1)
|
||||
);
|
||||
assert_eq!(report.skipped_work_at_least, Some(8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_summary_counts_runs_per_signature_and_clean_runs() {
|
||||
let clean = report_run(
|
||||
&(line(
|
||||
1,
|
||||
"d3d12_xs",
|
||||
"presentx_frames",
|
||||
"frames presented=16 last hr=0x0",
|
||||
) + &line(0, "bx_cli", "run_end", "outcome=timeout")),
|
||||
);
|
||||
let stopped = report_run(
|
||||
&(line(1, "com_vtable", "unimpl_vtable", "IXUser[3]::slot_3")
|
||||
+ &line(0, "bx_cli", "run_end", "outcome=exited status=1")),
|
||||
);
|
||||
let text = render_summary(&[
|
||||
("a".to_owned(), clean),
|
||||
("b".to_owned(), stopped.clone()),
|
||||
("c".to_owned(), stopped),
|
||||
]);
|
||||
assert!(
|
||||
text.contains(
|
||||
"Clean runs (frame loop reached, nothing stopped on, ran to the timeout): 1 of 3"
|
||||
),
|
||||
"{text}"
|
||||
);
|
||||
assert!(text.contains(" 2 of 3 exit status 1\n"), "{text}");
|
||||
assert!(
|
||||
text.contains(" 2 of 3 unimplemented IXUser slot 3\n"),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_that_are_not_json_records_are_ignored() {
|
||||
let report = report_run("warning: not a record\n\n{\"broken\n");
|
||||
assert_eq!(
|
||||
report.events, 1,
|
||||
"a line starting with a brace is counted even when malformed"
|
||||
);
|
||||
assert!(report.signatures().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -173,6 +173,13 @@ HRESULT refused(ID3D12Device* device, HRESULT hr, const char* kind, REFIID riid,
|
||||
return bx_xbox_wrap_result(S_OK, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT refused_always_fail(HRESULT hr, const char* kind) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "%s pipeline refused hr=0x%08lx", kind, static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_refused", detail);
|
||||
return hr;
|
||||
}
|
||||
|
||||
void log_extended(const char* kind, UINT count) {
|
||||
if (!count) return;
|
||||
char detail[96];
|
||||
@@ -433,33 +440,35 @@ void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void*, void* callback, U
|
||||
|
||||
/*
|
||||
* DeserializeGraphics/ComputePipelineStateX create a pipeline from a serialized console pipeline
|
||||
* (console shader code), which has no host form. They fail with E_NOTIMPL (logged as a refused
|
||||
* pipeline); in null-render mode they return a null pipeline like any other refused pipeline.
|
||||
* (console shader code), which has no host form. They always fail with E_NOTIMPL and log
|
||||
* `pipeline_refused` — even in null-render mode — so a title falls back to creating its pipelines
|
||||
* from shader containers instead of receiving a null pipeline (#669).
|
||||
*/
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void* self, const void*, REFIID riid,
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void*, const void*, REFIID,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "DeserializeGraphicsPipelineStateX");
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized graphics (console code)", riid, ppv);
|
||||
return refused_always_fail(E_NOTIMPL, "deserialized graphics (console code)");
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void* self, const void*, REFIID riid,
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void*, const void*, REFIID,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "DeserializeComputePipelineStateX");
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized compute (console code)", riid, ppv);
|
||||
return refused_always_fail(E_NOTIMPL, "deserialized compute (console code)");
|
||||
}
|
||||
|
||||
/*
|
||||
* CreateDerived{Graphics,Compute}PipelineStateX: a pipeline equal to `source` with some state
|
||||
* groups replaced. Derived from a null pipeline, the result is a null pipeline too. Deriving
|
||||
* from a host pipeline needs its creation description, which this layer does not keep yet: that
|
||||
* case is refused (logged) and, in null-render mode, is a null pipeline as well.
|
||||
* groups replaced. Deriving from a host pipeline needs its creation description, which this layer
|
||||
* does not keep yet. Both calls always fail with E_NOTIMPL and log `pipeline_refused` — even in
|
||||
* null-render mode — so a title falls back to creating its pipelines from shader containers
|
||||
* instead of silently receiving null pipelines (#669).
|
||||
*/
|
||||
namespace {
|
||||
HRESULT derived(void* self, ID3D12PipelineState* source, REFIID riid, void** ppv, const char* kind) {
|
||||
HRESULT derived(ID3D12PipelineState* source, void** ppv, const char* kind) {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
const bool from_null = bx_xbox_pipeline_is_null(source);
|
||||
@@ -470,18 +479,18 @@ HRESULT derived(void* self, ID3D12PipelineState* source, REFIID riid, void** ppv
|
||||
"deriving from a host pipeline is not implemented (its creation description is not kept)");
|
||||
}
|
||||
}
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, kind, riid, ppv);
|
||||
return refused_always_fail(E_NOTIMPL, kind);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void* self, ID3D12PipelineState* source,
|
||||
UINT, const void*, REFIID riid, void** ppv) {
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void*, ID3D12PipelineState* source,
|
||||
UINT, const void*, REFIID, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDerivedGraphicsPipelineStateX");
|
||||
return derived(self, source, riid, ppv, "derived graphics");
|
||||
return derived(source, ppv, "derived graphics");
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void* self, ID3D12PipelineState* source,
|
||||
UINT, const void*, REFIID riid, void** ppv) {
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void*, ID3D12PipelineState* source,
|
||||
UINT, const void*, REFIID, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDerivedComputePipelineStateX");
|
||||
return derived(self, source, riid, ppv, "derived compute");
|
||||
return derived(source, ppv, "derived compute");
|
||||
}
|
||||
@@ -279,12 +279,72 @@ bool zero_guest_cache_line(uint64_t address, EXCEPTION_RECORD& exception) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// A title that zeroes memory with CLZERO does it in a loop, and each iteration would trap again
|
||||
// (an exception round trip per 64 bytes: seconds per 100 MB). When the trapped CLZERO is followed
|
||||
// by exactly
|
||||
// add rax, 0x40 ; cmp rax, <reg64> ; jb <the clzero>
|
||||
// the remaining iterations are done here: every further line below the limit is zeroed and RAX is
|
||||
// left at the last one, so the title's own add/cmp/jb then leaves the loop. The range is zeroed
|
||||
// region by region and stops early at memory that is not committed and writable, where the
|
||||
// title's next CLZERO traps as before. Returns the number of extra lines zeroed.
|
||||
uint64_t clzero_loop_fast_path(CONTEXT& context) {
|
||||
const auto* code = reinterpret_cast<const uint8_t*>(context.Rip);
|
||||
MEMORY_BASIC_INFORMATION text{};
|
||||
if (!VirtualQuery(code, &text, sizeof(text)) || text.State != MEM_COMMIT ||
|
||||
reinterpret_cast<uintptr_t>(code) + 12 > reinterpret_cast<uintptr_t>(text.BaseAddress) + text.RegionSize) {
|
||||
return 0;
|
||||
}
|
||||
if (code[0] != 0x0F || code[1] != 0x01 || code[2] != 0xFC) return 0; // clzero
|
||||
if (code[3] != 0x48 || code[4] != 0x83 || code[5] != 0xC0 || code[6] != 0x40) return 0; // add rax, 0x40
|
||||
if ((code[7] != 0x48 && code[7] != 0x4C) || code[8] != 0x39 || (code[9] & 0xC7) != 0xC0) return 0; // cmp rax, r64
|
||||
if (code[10] != 0x72 || code[11] != 0xF4) return 0; // jb -12
|
||||
const unsigned reg = ((code[9] >> 3) & 7) | (code[7] == 0x4C ? 8 : 0);
|
||||
const DWORD64* registers = &context.Rax; // Rax, Rcx, Rdx, Rbx, Rsp, Rbp, Rsi, Rdi, R8..R15
|
||||
const uint64_t limit = registers[reg];
|
||||
constexpr uint64_t line = 64;
|
||||
uint64_t next = context.Rax + line;
|
||||
if (reg == 0 || next >= limit || limit - next > (1ull << 32)) return 0;
|
||||
const uint64_t last = next + ((limit - 1 - next) / line) * line; // largest next + 64k below limit
|
||||
constexpr DWORD writable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
|
||||
uint64_t done = 0;
|
||||
while (next <= last) {
|
||||
const uint64_t start = next & ~(line - 1);
|
||||
MEMORY_BASIC_INFORMATION page{};
|
||||
if (!VirtualQuery(reinterpret_cast<const void*>(start), &page, sizeof(page)) || page.State != MEM_COMMIT ||
|
||||
!(page.Protect & writable) || (page.Protect & PAGE_GUARD)) {
|
||||
break;
|
||||
}
|
||||
const uint64_t region_end = reinterpret_cast<uintptr_t>(page.BaseAddress) + page.RegionSize;
|
||||
uint64_t lines = (last - next) / line + 1;
|
||||
const uint64_t fit = (region_end - start) / line;
|
||||
if (fit == 0) break;
|
||||
if (lines > fit) lines = fit;
|
||||
std::memset(reinterpret_cast<void*>(start), 0, static_cast<size_t>(lines * line));
|
||||
context.Rax = next + (lines - 1) * line;
|
||||
next += lines * line;
|
||||
done += lines;
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
bool apply_amd_instruction(const AmdInstruction& instruction, CONTEXT& context,
|
||||
EXCEPTION_RECORD& exception) {
|
||||
switch (instruction.kind) {
|
||||
case kClzero:
|
||||
return zero_guest_cache_line(instruction.address32 ? static_cast<uint32_t>(context.Rax)
|
||||
: context.Rax, exception);
|
||||
case kClzero: {
|
||||
if (!zero_guest_cache_line(instruction.address32 ? static_cast<uint32_t>(context.Rax) : context.Rax,
|
||||
exception)) {
|
||||
return false;
|
||||
}
|
||||
if (!instruction.address32) {
|
||||
static std::atomic<uint64_t> batched{0};
|
||||
const uint64_t lines = clzero_loop_fast_path(context);
|
||||
if (lines && batched.fetch_add(1) == 0) {
|
||||
bx_log_emit(BX_LOG_INFO, "runtime_veh", "clzero_loop",
|
||||
"CLZERO loop (add rax,0x40; cmp; jb) completed in one trap; later loops are not logged");
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
case kMonitorx:
|
||||
// There is no host monitor state. MWAITX may complete immediately.
|
||||
return true;
|
||||
|
||||
@@ -37,6 +37,9 @@ HRESULT WINAPI XTaskQueueSubmitCallback(void*, bx::gdk::Port, void*, void (CALLB
|
||||
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void*, bx::gdk::Port, uint32_t, void*,
|
||||
void (CALLBACK*)(void*, bool));
|
||||
bool WINAPI XTaskQueueGetCurrentProcessTaskQueue(void**);
|
||||
HRESULT WINAPI bx_xtq_duplicate_handle(void*, void**);
|
||||
HRESULT WINAPI bx_xtq_get_port(void*, bx::gdk::Port, void**);
|
||||
HRESULT WINAPI bx_xtq_create_composite(void*, void*, void**);
|
||||
|
||||
HRESULT WINAPI XAsyncGetStatus(void*, bool);
|
||||
HRESULT WINAPI XAsyncGetResultSize(void*, size_t*);
|
||||
@@ -45,6 +48,8 @@ void WINAPI XAsyncCancel(void*);
|
||||
HRESULT WINAPI XUserAddAsync(uint32_t, void*);
|
||||
HRESULT WINAPI XUserAddResult(void*, void**);
|
||||
void WINAPI XUserCloseHandle(void*);
|
||||
HRESULT WINAPI bx_xuser_duplicate_handle(void*, void**);
|
||||
bool WINAPI bx_xuser_is_handle(void*);
|
||||
HRESULT WINAPI XUserGetId(void*, uint64_t*);
|
||||
HRESULT WINAPI XUserGetGamertag(void*, uint32_t, size_t, char*, size_t*);
|
||||
HRESULT WINAPI XUserGetTokenAndSignatureAsync(void*, uint32_t, const char*, const char*, size_t, const void*, size_t,
|
||||
@@ -176,6 +181,32 @@ HRESULT WINAPI core_async_get_result_size(void*, void* async, size_t* size) {
|
||||
void WINAPI core_async_cancel(void*, void* async) {
|
||||
XAsyncCancel(async);
|
||||
}
|
||||
// XAsyncRun: the title's work callback runs on the block's work port and its return value
|
||||
// completes the block (no result payload).
|
||||
struct AsyncRunOp final : bx::gdk::AsyncOp {
|
||||
using Work = HRESULT (CALLBACK*)(void*);
|
||||
Work work;
|
||||
void* block;
|
||||
AsyncRunOp(Work work, void* block) : work(work), block(block) {}
|
||||
uint32_t kind() const override { return 0x4E5552u; } // "RUN"
|
||||
HRESULT execute() override { return work(block); }
|
||||
size_t result_size() const override { return 0; }
|
||||
};
|
||||
HRESULT WINAPI core_async_run(void*, void* async, AsyncRunOp::Work work) {
|
||||
if (!async || !work) return E_INVALIDARG;
|
||||
auto op = std::unique_ptr<bx::gdk::AsyncOp>(new (std::nothrow) AsyncRunOp(work, async));
|
||||
if (!op) return E_OUTOFMEMORY;
|
||||
return bx::gdk::begin_async_op(async, std::move(op));
|
||||
}
|
||||
HRESULT WINAPI core_tq_create_composite(void*, void* work_port, void* completion_port, void** out) {
|
||||
return bx_xtq_create_composite(work_port, completion_port, out);
|
||||
}
|
||||
HRESULT WINAPI core_tq_get_port(void*, void* queue, Port port, void** out) {
|
||||
return bx_xtq_get_port(queue, port, out);
|
||||
}
|
||||
HRESULT WINAPI core_tq_duplicate(void*, void* queue, void** out) {
|
||||
return bx_xtq_duplicate_handle(queue, out);
|
||||
}
|
||||
HRESULT WINAPI core_tq_create(void*, DispatchMode work, DispatchMode comp, void** out) {
|
||||
return XTaskQueueCreate(work, comp, out);
|
||||
}
|
||||
@@ -220,7 +251,11 @@ const std::array<const void*, 36> kCoreVtbl = [] {
|
||||
v[3] = reinterpret_cast<const void*>(&core_async_get_status);
|
||||
v[4] = reinterpret_cast<const void*>(&core_async_get_result_size);
|
||||
v[5] = reinterpret_cast<const void*>(&core_async_cancel);
|
||||
v[6] = reinterpret_cast<const void*>(&core_async_run);
|
||||
v[12] = reinterpret_cast<const void*>(&core_tq_create);
|
||||
v[13] = reinterpret_cast<const void*>(&core_tq_create_composite);
|
||||
v[14] = reinterpret_cast<const void*>(&core_tq_get_port);
|
||||
v[15] = reinterpret_cast<const void*>(&core_tq_duplicate);
|
||||
v[16] = reinterpret_cast<const void*>(&core_tq_dispatch);
|
||||
v[17] = reinterpret_cast<const void*>(&core_tq_close);
|
||||
v[18] = reinterpret_cast<const void*>(&core_tq_submit);
|
||||
@@ -433,8 +468,16 @@ std::unordered_set<uint64_t> user_event_tokens;
|
||||
void WINAPI user_close_handle(void*, void* h) {
|
||||
XUserCloseHandle(h);
|
||||
}
|
||||
HRESULT WINAPI user_duplicate_handle(void*, void* user, void** out) {
|
||||
const HRESULT hr = bx_xuser_duplicate_handle(user, out);
|
||||
bx_log_emit(SUCCEEDED(hr) ? BX_LOG_INFO : BX_LOG_WARN, "xgameruntime", "XUserDuplicateHandle",
|
||||
SUCCEEDED(hr) ? "duplicate handle for the offline user" : "invalid user handle");
|
||||
return hr;
|
||||
}
|
||||
int32_t WINAPI user_compare(void*, void* u1, void* u2) {
|
||||
if (u1 == u2) return 0;
|
||||
// One offline user: every valid handle (duplicates included) names the same user.
|
||||
if (bx_xuser_is_handle(u1) && bx_xuser_is_handle(u2)) return 0;
|
||||
return reinterpret_cast<uintptr_t>(u1) < reinterpret_cast<uintptr_t>(u2) ? -1 : 1;
|
||||
}
|
||||
HRESULT WINAPI user_get_max_users(void*, uint32_t* max_users) {
|
||||
@@ -517,6 +560,7 @@ HRESULT WINAPI user_get_gamertag(void*, void* user, uint32_t comp, size_t sz, ch
|
||||
|
||||
const std::array<const void*, 64> kUserVtbl = [] {
|
||||
auto v = make_default_vtbl<64>();
|
||||
v[3] = reinterpret_cast<const void*>(&user_duplicate_handle);
|
||||
v[4] = reinterpret_cast<const void*>(&user_close_handle);
|
||||
v[5] = reinterpret_cast<const void*>(&user_compare);
|
||||
v[6] = reinterpret_cast<const void*>(&user_get_max_users);
|
||||
|
||||
@@ -185,13 +185,31 @@ public:
|
||||
Queue(DispatchMode work, DispatchMode completion) : lanes{{this, work}, {this, completion}} {}
|
||||
|
||||
Lane lanes[2];
|
||||
// A composite queue (XTaskQueueCreateComposite) has no lanes of its own in use: each port
|
||||
// forwards to a port of another queue.
|
||||
QueueRef forward[2];
|
||||
Port forward_port[2] = {Port::work, Port::completion};
|
||||
};
|
||||
|
||||
// Follows composite forwarding to the queue and port that hold the lane.
|
||||
static void resolve_lane(QueueRef& queue, Port& port) {
|
||||
for (int depth = 0; depth < 8 && queue; ++depth) {
|
||||
const auto index = static_cast<uint32_t>(port);
|
||||
if (!queue->forward[index]) return;
|
||||
const Port next_port = queue->forward_port[index];
|
||||
queue = queue->forward[index];
|
||||
port = next_port;
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
std::mutex queues_mutex;
|
||||
std::unordered_map<uintptr_t, QueueRef> handles;
|
||||
uintptr_t next_handle = 1;
|
||||
// XTaskQueuePortHandle values (even numbers, so they never collide with queue handles).
|
||||
std::unordered_map<uintptr_t, std::pair<QueueRef, Port>> port_handles;
|
||||
uintptr_t next_port_handle = 2;
|
||||
QueueRef process_queue;
|
||||
|
||||
HRESULT make_queue(DispatchMode work, DispatchMode completion, QueueRef& queue) {
|
||||
@@ -238,7 +256,9 @@ QueueRef acquire_queue(void* handle) {
|
||||
}
|
||||
|
||||
bool submit(const QueueRef& queue, Port port, std::unique_ptr<Task> task, bool is_completion) {
|
||||
return queue->lanes[static_cast<uint32_t>(port)].push(std::move(task), is_completion);
|
||||
QueueRef target = queue;
|
||||
resolve_lane(target, port);
|
||||
return target->lanes[static_cast<uint32_t>(port)].push(std::move(task), is_completion);
|
||||
}
|
||||
|
||||
|
||||
@@ -275,6 +295,10 @@ void WINAPI XTaskQueueCloseHandle(void* handle) {
|
||||
queue = std::move(it->second);
|
||||
close_queue = queue != process_queue;
|
||||
handles.erase(it);
|
||||
// Duplicated handles share the queue: only the last close shuts its lanes down.
|
||||
for (const auto& other : handles) {
|
||||
if (other.second == queue) close_queue = false;
|
||||
}
|
||||
}
|
||||
// The frozen ABI exposes no termination or duplicate-handle API. Drain manual
|
||||
// completion callbacks on close and let accepted pool work finish normally.
|
||||
@@ -285,8 +309,64 @@ void WINAPI XTaskQueueCloseHandle(void* handle) {
|
||||
|
||||
bool WINAPI XTaskQueueDispatch(void* handle, Port port, uint32_t timeout) {
|
||||
if (!handle || port > Port::completion) return false;
|
||||
auto queue = acquire_queue(handle);
|
||||
if (!queue) return false;
|
||||
resolve_lane(queue, port);
|
||||
return queue->lanes[static_cast<uint32_t>(port)].dispatch(timeout);
|
||||
}
|
||||
|
||||
// Not exported: reached through IXGameRuntimeCore (com_dispatch.cpp).
|
||||
HRESULT WINAPI bx_xtq_duplicate_handle(void* handle, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
const auto queue = acquire_queue(handle);
|
||||
return queue && queue->lanes[static_cast<uint32_t>(port)].dispatch(timeout);
|
||||
if (!queue) return E_HANDLE;
|
||||
try {
|
||||
std::lock_guard lock(queues_mutex);
|
||||
*out = add_handle(queue);
|
||||
return S_OK;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT WINAPI bx_xtq_get_port(void* handle, Port port, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (port > Port::completion) return E_INVALIDARG;
|
||||
const auto queue = acquire_queue(handle);
|
||||
if (!queue) return E_HANDLE;
|
||||
try {
|
||||
std::lock_guard lock(queues_mutex);
|
||||
const auto id = next_port_handle;
|
||||
next_port_handle += 2;
|
||||
port_handles.emplace(id, std::make_pair(queue, port));
|
||||
*out = reinterpret_cast<void*>(id);
|
||||
return S_OK;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT WINAPI bx_xtq_create_composite(void* work_port, void* completion_port, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
try {
|
||||
std::lock_guard lock(queues_mutex);
|
||||
const auto work = port_handles.find(reinterpret_cast<uintptr_t>(work_port));
|
||||
const auto completion = port_handles.find(reinterpret_cast<uintptr_t>(completion_port));
|
||||
if (work == port_handles.end() || completion == port_handles.end()) return E_HANDLE;
|
||||
// Immediate lanes: never used, every submit and dispatch is forwarded.
|
||||
auto queue = std::make_shared<Queue>(DispatchMode::immediate, DispatchMode::immediate);
|
||||
queue->forward[0] = work->second.first;
|
||||
queue->forward_port[0] = work->second.second;
|
||||
queue->forward[1] = completion->second.first;
|
||||
queue->forward_port[1] = completion->second.second;
|
||||
*out = add_handle(queue);
|
||||
return S_OK;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void* handle, Port port, uint32_t delay_ms, void* context,
|
||||
|
||||
@@ -167,6 +167,10 @@ public:
|
||||
Operation operation;
|
||||
std::unique_ptr<AsyncOp> op;
|
||||
std::unique_ptr<CompletionTask> completion;
|
||||
// The queue the block named. A composite queue forwards its ports to other queues, and a
|
||||
// task runs with the queue that owns the lane, so the completion must go back through
|
||||
// this one to reach the composite's completion port.
|
||||
QueueRef origin;
|
||||
bool queued = false;
|
||||
|
||||
AsyncTask(AsyncBlock* block, Operation operation, std::unique_ptr<AsyncOp> op)
|
||||
@@ -225,7 +229,7 @@ private:
|
||||
queued = false;
|
||||
write_state(block, state);
|
||||
}
|
||||
if (completion) submit(queue, Port::completion, std::move(completion), true);
|
||||
if (completion) submit(origin ? origin : queue, Port::completion, std::move(completion), true);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -236,6 +240,7 @@ HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr, std
|
||||
|
||||
auto work = std::unique_ptr<AsyncTask>(new (std::nothrow) AsyncTask(block, operation, std::move(op)));
|
||||
if (!work) return E_OUTOFMEMORY;
|
||||
work->origin = queue;
|
||||
if (block->callback) {
|
||||
work->completion.reset(new (std::nothrow) CompletionTask(block));
|
||||
if (!work->completion) return E_OUTOFMEMORY;
|
||||
@@ -643,6 +648,21 @@ HRESULT WINAPI XUserAddResult(AsyncBlock* block, void** out) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Not exported: XUserDuplicateHandle is reached through IXUser (com_dispatch.cpp). A duplicate is
|
||||
// a new handle to the same (single, offline) user; each handle is closed separately.
|
||||
HRESULT WINAPI bx_xuser_duplicate_handle(void* user, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
std::lock_guard lock(state_mutex);
|
||||
if (!users.contains(user)) return runtime_invalid_handle;
|
||||
return create_handle(users, out);
|
||||
}
|
||||
|
||||
bool WINAPI bx_xuser_is_handle(void* user) {
|
||||
std::lock_guard lock(state_mutex);
|
||||
return users.contains(user);
|
||||
}
|
||||
|
||||
void WINAPI XUserCloseHandle(void* user) {
|
||||
std::lock_guard lock(state_mutex);
|
||||
users.erase(user);
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_d3d12_serialized_pipelines main.cpp)
|
||||
target_compile_definitions(test_d3d12_serialized_pipelines PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_link_libraries(test_d3d12_serialized_pipelines PRIVATE d3d12_xs kernel32 uuid)
|
||||
@@ -0,0 +1,198 @@
|
||||
/*
|
||||
* Conformance test for #669: serialized and derived Xbox pipeline-state calls must fail with
|
||||
* E_NOTIMPL and log `pipeline_refused` even when BX_NULL_RENDER=1 is active, so a title falls
|
||||
* back to creating pipelines from shader containers instead of silently receiving null pipelines.
|
||||
*
|
||||
* Slot numbers follow the Xbox Series ID3D12Device vtable layout (ADR 0009):
|
||||
* 2 = Release
|
||||
* 11 = CreateComputePipelineState
|
||||
* 55 = CreateDerivedGraphicsPipelineStateX
|
||||
* 57 = DeserializeGraphicsPipelineStateX
|
||||
* 63 = CreateDerivedComputePipelineStateX
|
||||
* 67 = DeserializeComputePipelineStateX
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
|
||||
void** ppv);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kRelease = 2;
|
||||
constexpr int kDevCreateComputePipelineState = 11;
|
||||
constexpr int kDevCreateDerivedGraphicsPipelineStateX = 55;
|
||||
constexpr int kDevDeserializeGraphicsPipelineStateX = 57;
|
||||
constexpr int kDevCreateDerivedComputePipelineStateX = 63;
|
||||
constexpr int kDevDeserializeComputePipelineStateX = 67;
|
||||
|
||||
int g_checks = 0;
|
||||
int g_failed = 0;
|
||||
|
||||
#define CHECK(cond, ...) \
|
||||
do { \
|
||||
++g_checks; \
|
||||
if (!(cond)) { \
|
||||
++g_failed; \
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_serialized_pipelines:%d: ", __LINE__); \
|
||||
std::fprintf(stderr, __VA_ARGS__); \
|
||||
std::fprintf(stderr, "\n"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
template <typename Fn>
|
||||
Fn slot(void* object, int index) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
|
||||
}
|
||||
|
||||
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateComputePsoFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, REFIID, void**);
|
||||
using DeserializePsoFn = HRESULT(STDMETHODCALLTYPE*)(void*, const void*, REFIID, void**);
|
||||
using CreateDerivedPsoFn = HRESULT(STDMETHODCALLTYPE*)(void*, ID3D12PipelineState*, UINT, const void*, REFIID, void**);
|
||||
|
||||
std::string read_log() {
|
||||
char path[MAX_PATH];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
if (n == 0 || n >= sizeof(path)) return {};
|
||||
std::string text;
|
||||
if (FILE* f = std::fopen(path, "rb")) {
|
||||
char buffer[4096];
|
||||
size_t got;
|
||||
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
|
||||
std::fclose(f);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
bool log_has_refusal_without_null(const std::string& log, const char* kind) {
|
||||
size_t pos = 0;
|
||||
while (pos < log.size()) {
|
||||
size_t end = log.find('\n', pos);
|
||||
if (end == std::string::npos) end = log.size();
|
||||
const std::string line = log.substr(pos, end - pos);
|
||||
if (line.find("\"event\":\"pipeline_refused\"") != std::string::npos && line.find(kind) != std::string::npos) {
|
||||
return line.find("null pipeline returned") == std::string::npos;
|
||||
}
|
||||
pos = end + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
// Enable null-render mode before any pipeline call so d3d12_xs caches BX_NULL_RENDER=1.
|
||||
SetEnvironmentVariableA("BX_NULL_RENDER", "1");
|
||||
|
||||
alignas(8) unsigned char title_params[80] = {};
|
||||
const UINT version = 0x20004;
|
||||
std::memcpy(title_params, &version, sizeof(version));
|
||||
|
||||
void* dev = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
|
||||
if (hr == E_NOINTERFACE) {
|
||||
std::printf("SKIP: test_d3d12_serialized_pipelines: host lacks Xbox-layout device interface (E_NOINTERFACE)\n");
|
||||
return 77;
|
||||
}
|
||||
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!dev) return 1;
|
||||
|
||||
// 1. Control check: a refused shader-container pipeline still becomes a null pipeline when
|
||||
// BX_NULL_RENDER=1, confirming null-render mode is active.
|
||||
static const uint8_t kBogusShader[16] = {0x44, 0x58, 0x42, 0x43};
|
||||
D3D12_COMPUTE_PIPELINE_STATE_DESC compute_desc{};
|
||||
compute_desc.CS.pShaderBytecode = kBogusShader;
|
||||
compute_desc.CS.BytecodeLength = sizeof(kBogusShader);
|
||||
void* null_pso = nullptr;
|
||||
hr = slot<CreateComputePsoFn>(dev, kDevCreateComputePipelineState)(
|
||||
dev, &compute_desc, __uuidof(ID3D12PipelineState), &null_pso);
|
||||
CHECK(hr == S_OK && null_pso != nullptr,
|
||||
"control: refused CreateComputePipelineState returns null pipeline in BX_NULL_RENDER=1 (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
|
||||
// 2. Serialized pipeline calls must fail with E_NOTIMPL and clear *ppv even with BX_NULL_RENDER=1.
|
||||
auto* sentinel = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
|
||||
void* out = sentinel;
|
||||
hr = slot<DeserializePsoFn>(dev, kDevDeserializeGraphicsPipelineStateX)(
|
||||
dev, nullptr, __uuidof(ID3D12PipelineState), &out);
|
||||
CHECK(hr == E_NOTIMPL && out == nullptr,
|
||||
"DeserializeGraphicsPipelineStateX must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
|
||||
static_cast<unsigned long>(hr), out);
|
||||
hr = slot<DeserializePsoFn>(dev, kDevDeserializeGraphicsPipelineStateX)(
|
||||
dev, nullptr, __uuidof(ID3D12PipelineState), nullptr);
|
||||
CHECK(hr == E_POINTER, "DeserializeGraphicsPipelineStateX(ppv=nullptr) must return E_POINTER (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
|
||||
out = sentinel;
|
||||
hr = slot<DeserializePsoFn>(dev, kDevDeserializeComputePipelineStateX)(
|
||||
dev, nullptr, __uuidof(ID3D12PipelineState), &out);
|
||||
CHECK(hr == E_NOTIMPL && out == nullptr,
|
||||
"DeserializeComputePipelineStateX must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
|
||||
static_cast<unsigned long>(hr), out);
|
||||
hr = slot<DeserializePsoFn>(dev, kDevDeserializeComputePipelineStateX)(
|
||||
dev, nullptr, __uuidof(ID3D12PipelineState), nullptr);
|
||||
CHECK(hr == E_POINTER, "DeserializeComputePipelineStateX(ppv=nullptr) must return E_POINTER (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
|
||||
// 3. Derived pipeline calls must also fail with E_NOTIMPL and clear *ppv (both from a null
|
||||
// pipeline source and from a nullptr source) even with BX_NULL_RENDER=1.
|
||||
auto* null_src = static_cast<ID3D12PipelineState*>(null_pso);
|
||||
out = sentinel;
|
||||
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedGraphicsPipelineStateX)(
|
||||
dev, null_src, 0, nullptr, __uuidof(ID3D12PipelineState), &out);
|
||||
CHECK(hr == E_NOTIMPL && out == nullptr,
|
||||
"CreateDerivedGraphicsPipelineStateX(null source) must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
|
||||
static_cast<unsigned long>(hr), out);
|
||||
out = sentinel;
|
||||
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedGraphicsPipelineStateX)(
|
||||
dev, nullptr, 0, nullptr, __uuidof(ID3D12PipelineState), &out);
|
||||
CHECK(hr == E_NOTIMPL && out == nullptr,
|
||||
"CreateDerivedGraphicsPipelineStateX(nullptr) must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
|
||||
static_cast<unsigned long>(hr), out);
|
||||
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedGraphicsPipelineStateX)(
|
||||
dev, null_src, 0, nullptr, __uuidof(ID3D12PipelineState), nullptr);
|
||||
CHECK(hr == E_POINTER, "CreateDerivedGraphicsPipelineStateX(ppv=nullptr) must return E_POINTER (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
|
||||
out = sentinel;
|
||||
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedComputePipelineStateX)(
|
||||
dev, null_src, 0, nullptr, __uuidof(ID3D12PipelineState), &out);
|
||||
CHECK(hr == E_NOTIMPL && out == nullptr,
|
||||
"CreateDerivedComputePipelineStateX(null source) must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
|
||||
static_cast<unsigned long>(hr), out);
|
||||
out = sentinel;
|
||||
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedComputePipelineStateX)(
|
||||
dev, nullptr, 0, nullptr, __uuidof(ID3D12PipelineState), &out);
|
||||
CHECK(hr == E_NOTIMPL && out == nullptr,
|
||||
"CreateDerivedComputePipelineStateX(nullptr) must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
|
||||
static_cast<unsigned long>(hr), out);
|
||||
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedComputePipelineStateX)(
|
||||
dev, null_src, 0, nullptr, __uuidof(ID3D12PipelineState), nullptr);
|
||||
CHECK(hr == E_POINTER, "CreateDerivedComputePipelineStateX(ppv=nullptr) must return E_POINTER (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
|
||||
// 4. When BX_LOG_FILE is active, verify each refusal was logged without "null pipeline returned".
|
||||
const std::string log = read_log();
|
||||
if (!log.empty()) {
|
||||
CHECK(log_has_refusal_without_null(log, "deserialized graphics (console code)"),
|
||||
"log must record deserialized graphics refusal without null pipeline");
|
||||
CHECK(log_has_refusal_without_null(log, "deserialized compute (console code)"),
|
||||
"log must record deserialized compute refusal without null pipeline");
|
||||
CHECK(log_has_refusal_without_null(log, "derived graphics"),
|
||||
"log must record derived graphics refusal without null pipeline");
|
||||
CHECK(log_has_refusal_without_null(log, "derived compute"),
|
||||
"log must record derived compute refusal without null pipeline");
|
||||
}
|
||||
|
||||
if (null_pso) slot<ReleaseFn>(null_pso, kRelease)(null_pso);
|
||||
slot<ReleaseFn>(dev, kRelease)(dev);
|
||||
|
||||
std::printf("%s: test_d3d12_serialized_pipelines (%d of %d checks passed)\n",
|
||||
g_failed ? "FAIL" : "PASS", g_checks - g_failed, g_checks);
|
||||
return g_failed ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_veh_clzero_loop main.cpp)
|
||||
target_include_directories(test_veh_clzero_loop PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_link_libraries(test_veh_clzero_loop PRIVATE bx_runtime_veh kernel32)
|
||||
@@ -0,0 +1,199 @@
|
||||
// Synthetic Windows x64 fixture for CLZERO loops under the Rosetta exception path (#665).
|
||||
//
|
||||
// CLZERO (AMD APM vol. 3, 24594) zeroes the 64-byte cache line that contains the address in RAX
|
||||
// and changes no register. Rosetta 2 does not run it, so bx_runtime_veh.dll emulates it from the
|
||||
// illegal-instruction exception. A loop of the form
|
||||
//
|
||||
// clzero ; add rax, 0x40 ; cmp rax, <reg64> ; jb <the clzero>
|
||||
//
|
||||
// would raise one exception per line. The handler completes such a loop in the first exception.
|
||||
//
|
||||
// This fixture runs its own machine-code loops (bytes written here, no title code) and checks:
|
||||
// * the memory result against the instruction's definition, line by line, with sentinels;
|
||||
// * the number of illegal-instruction exceptions, counted by a handler of its own that runs
|
||||
// before BetterXen's: one per loop that matches the form, one per line otherwise;
|
||||
// * a range that runs into a read-only page: the loop stops there with a write fault at that
|
||||
// page, and finishes once the page is writable.
|
||||
// On a host that runs CLZERO natively no exception is raised and the fixture skips (exit 77).
|
||||
#include <windows.h>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
extern "C" uint64_t bx_veh_get_clwb_trap_count(void); // imports bx_runtime_veh.dll, which installs the handler
|
||||
|
||||
namespace {
|
||||
|
||||
unsigned failures = 0;
|
||||
unsigned checks = 0;
|
||||
|
||||
void expect(bool passed, const char* name) {
|
||||
++checks;
|
||||
if (passed) {
|
||||
std::printf("ok: %s\n", name);
|
||||
} else {
|
||||
std::fprintf(stderr, "FAIL: %s\n", name);
|
||||
++failures;
|
||||
}
|
||||
}
|
||||
|
||||
volatile LONG g_illegal = 0; // illegal-instruction exceptions seen first-chance
|
||||
volatile LONG g_write_faults = 0; // write faults that reached the last handler
|
||||
volatile ULONG_PTR g_fault_address = 0;
|
||||
void* g_unprotect = nullptr; // page the last handler makes writable when it faults
|
||||
SIZE_T g_unprotect_size = 0;
|
||||
|
||||
// Registered first: sees every illegal instruction before BetterXen's handler emulates it.
|
||||
LONG CALLBACK count_first(PEXCEPTION_POINTERS ep) {
|
||||
if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) InterlockedIncrement(&g_illegal);
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
// Registered last: sees the write fault BetterXen passes on when a line is not writable.
|
||||
LONG CALLBACK fix_last(PEXCEPTION_POINTERS ep) {
|
||||
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
|
||||
if (r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION || r.NumberParameters < 2 || r.ExceptionInformation[0] != 1) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
InterlockedIncrement(&g_write_faults);
|
||||
g_fault_address = r.ExceptionInformation[1];
|
||||
DWORD old = 0;
|
||||
if (!g_unprotect || !VirtualProtect(g_unprotect, g_unprotect_size, PAGE_READWRITE, &old)) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
g_unprotect = nullptr;
|
||||
return EXCEPTION_CONTINUE_EXECUTION; // the CLZERO runs again
|
||||
}
|
||||
|
||||
using Loop = void (*)(uint8_t* start, uint8_t* limit); // rcx = start, rdx = limit
|
||||
|
||||
// mov rax, rcx ; L: clzero ; add rax, 0x40 ; cmp rax, rdx ; jb L ; ret
|
||||
const uint8_t kLoopRdx[] = {0x48, 0x89, 0xC8, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4, 0xC3};
|
||||
// mov rax, rcx ; mov r10, rdx ; L: clzero ; add rax, 0x40 ; cmp rax, r10 ; jb L ; ret
|
||||
const uint8_t kLoopR10[] = {0x48, 0x89, 0xC8, 0x49, 0x89, 0xD2, 0x0F, 0x01, 0xFC, 0x48, 0x83,
|
||||
0xC0, 0x40, 0x4C, 0x39, 0xD0, 0x72, 0xF4, 0xC3};
|
||||
// The same loop with a NOP before the add, which is not the recognised form:
|
||||
// mov rax, rcx ; L: clzero ; nop ; add rax, 0x40 ; cmp rax, rdx ; jb L ; ret
|
||||
const uint8_t kLoopOther[] = {0x48, 0x89, 0xC8, 0x0F, 0x01, 0xFC, 0x90, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF3, 0xC3};
|
||||
|
||||
Loop make(const uint8_t* code, size_t size) {
|
||||
void* page = VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
|
||||
if (!page) return nullptr;
|
||||
std::memcpy(page, code, size);
|
||||
FlushInstructionCache(GetCurrentProcess(), page, size);
|
||||
return reinterpret_cast<Loop>(page);
|
||||
}
|
||||
|
||||
constexpr size_t kLine = 64;
|
||||
|
||||
// Lines [first, first + count) of `base` are zero and every other line of the `lines`-line buffer
|
||||
// still holds the fill byte.
|
||||
bool only_zeroed(const uint8_t* base, size_t lines, size_t first, size_t count) {
|
||||
for (size_t line = 0; line < lines; ++line) {
|
||||
const uint8_t want = (line >= first && line < first + count) ? 0x00 : 0xAA;
|
||||
for (size_t i = 0; i < kLine; ++i) {
|
||||
if (base[line * kLine + i] != want) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
LONG run(Loop loop, uint8_t* start, uint8_t* limit) {
|
||||
InterlockedExchange(&g_illegal, 0);
|
||||
loop(start, limit);
|
||||
return g_illegal;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
(void)bx_veh_get_clwb_trap_count();
|
||||
void* first = AddVectoredExceptionHandler(1, count_first);
|
||||
void* last = AddVectoredExceptionHandler(0, fix_last);
|
||||
Loop loop_rdx = make(kLoopRdx, sizeof(kLoopRdx));
|
||||
Loop loop_r10 = make(kLoopR10, sizeof(kLoopR10));
|
||||
Loop loop_other = make(kLoopOther, sizeof(kLoopOther));
|
||||
if (!first || !last || !loop_rdx || !loop_r10 || !loop_other) {
|
||||
std::fprintf(stderr, "FAIL: setup\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// 1,026 lines: a sentinel line, 1,024 lines to work in, a sentinel line.
|
||||
constexpr size_t kLines = 1026;
|
||||
auto* buffer = static_cast<uint8_t*>(VirtualAlloc(nullptr, kLines * kLine, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
|
||||
if (!buffer) {
|
||||
std::fprintf(stderr, "FAIL: buffer\n");
|
||||
return 1;
|
||||
}
|
||||
uint8_t* work = buffer + kLine;
|
||||
|
||||
// One line: the loop body runs once.
|
||||
std::memset(buffer, 0xAA, kLines * kLine);
|
||||
LONG illegal = run(loop_rdx, work, work + kLine);
|
||||
if (illegal == 0) {
|
||||
std::printf("SKIP: test_veh_clzero_loop: CLZERO raised no exception on this host (it runs natively)\n");
|
||||
return 77;
|
||||
}
|
||||
expect(only_zeroed(buffer, kLines, 1, 1), "one line: exactly that line is zero");
|
||||
expect(illegal == 1, "one line: one exception");
|
||||
|
||||
// 1,000 lines through the recognised form.
|
||||
std::memset(buffer, 0xAA, kLines * kLine);
|
||||
illegal = run(loop_rdx, work, work + 1000 * kLine);
|
||||
expect(only_zeroed(buffer, kLines, 1, 1000), "1000 lines (cmp rax, rdx): exactly those lines are zero");
|
||||
expect(illegal == 1, "1000 lines (cmp rax, rdx): one exception for the whole loop");
|
||||
|
||||
// The limit register is r10.
|
||||
std::memset(buffer, 0xAA, kLines * kLine);
|
||||
illegal = run(loop_r10, work, work + 1000 * kLine);
|
||||
expect(only_zeroed(buffer, kLines, 1, 1000), "1000 lines (cmp rax, r10): exactly those lines are zero");
|
||||
expect(illegal == 1, "1000 lines (cmp rax, r10): one exception for the whole loop");
|
||||
|
||||
// A limit one byte into an eleventh line: the loop runs while rax < limit, so eleven lines.
|
||||
std::memset(buffer, 0xAA, kLines * kLine);
|
||||
illegal = run(loop_rdx, work, work + 10 * kLine + 1);
|
||||
expect(only_zeroed(buffer, kLines, 1, 11), "limit inside a line: that line is zeroed too");
|
||||
expect(illegal == 1, "limit inside a line: one exception");
|
||||
|
||||
// A start 8 bytes into a line: each CLZERO zeroes the whole line containing rax. With the limit
|
||||
// at the end of the tenth line, rax takes ten values below it.
|
||||
std::memset(buffer, 0xAA, kLines * kLine);
|
||||
illegal = run(loop_rdx, work + 8, work + 10 * kLine);
|
||||
expect(only_zeroed(buffer, kLines, 1, 10), "unaligned start: ten whole lines are zero");
|
||||
expect(illegal == 1, "unaligned start: one exception");
|
||||
|
||||
// A loop that is not the recognised form keeps the per-instruction path: same memory result,
|
||||
// one exception per line.
|
||||
std::memset(buffer, 0xAA, kLines * kLine);
|
||||
illegal = run(loop_other, work, work + 8 * kLine);
|
||||
expect(only_zeroed(buffer, kLines, 1, 8), "other loop form: exactly eight lines are zero");
|
||||
expect(illegal == 8, "other loop form: one exception per line");
|
||||
|
||||
// A range that runs from a writable page into a read-only one. The lines of the first page are
|
||||
// zeroed; the first line of the second page faults as a write to that page; once the last
|
||||
// handler makes it writable the loop finishes.
|
||||
auto* pages = static_cast<uint8_t*>(VirtualAlloc(nullptr, 2 * 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
|
||||
if (!pages) {
|
||||
std::fprintf(stderr, "FAIL: pages\n");
|
||||
return 1;
|
||||
}
|
||||
std::memset(pages, 0xAA, 2 * 4096);
|
||||
DWORD old = 0;
|
||||
VirtualProtect(pages + 4096, 4096, PAGE_READONLY, &old);
|
||||
g_unprotect = pages + 4096;
|
||||
g_unprotect_size = 4096;
|
||||
InterlockedExchange(&g_write_faults, 0);
|
||||
g_fault_address = 0;
|
||||
illegal = run(loop_rdx, pages + 4096 - 4 * kLine, pages + 4096 + 4 * kLine);
|
||||
expect(g_write_faults == 1, "read-only page: one write fault is passed on");
|
||||
expect(g_fault_address == reinterpret_cast<ULONG_PTR>(pages + 4096), "read-only page: the fault names the first line of that page");
|
||||
expect(only_zeroed(pages, 2 * 4096 / kLine, 4096 / kLine - 4, 8), "read-only page: all eight lines are zero after it is made writable");
|
||||
// First exception zeroes the four writable lines; the fifth line traps and faults; its retry
|
||||
// traps again and finishes the range.
|
||||
expect(illegal == 3, "read-only page: three exceptions (range start, the fault, the retry)");
|
||||
|
||||
RemoveVectoredExceptionHandler(last);
|
||||
RemoveVectoredExceptionHandler(first);
|
||||
std::printf("%s: test_veh_clzero_loop (%u of %u checks passed)\n", failures ? "FAIL" : "PASS", checks - failures, checks);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
@@ -199,6 +199,134 @@ void CALLBACK record_order(void* context, bool canceled) {
|
||||
else if (slot == 1) record.second = 2;
|
||||
}
|
||||
|
||||
// XAsyncRun and the task-queue handle calls through IXGameRuntimeCore slots 6, 13, 14 and 15
|
||||
// (#666). Slot numbers follow the declaration order of the public XAsync.h and XTaskQueue.h;
|
||||
// the expected behaviour is the documented one.
|
||||
struct RunRecord {
|
||||
std::atomic<unsigned> work_runs{0};
|
||||
std::atomic<unsigned> completions{0};
|
||||
std::atomic<DWORD> work_thread{0};
|
||||
HRESULT result = S_OK;
|
||||
};
|
||||
|
||||
HRESULT CALLBACK run_work(Async* async) {
|
||||
auto& record = *static_cast<RunRecord*>(async->context);
|
||||
record.work_thread = GetCurrentThreadId();
|
||||
++record.work_runs;
|
||||
return record.result;
|
||||
}
|
||||
|
||||
void CALLBACK run_completed(Async* async) {
|
||||
++static_cast<RunRecord*>(async->context)->completions;
|
||||
}
|
||||
|
||||
void check_async_run_and_queue_handles(HRESULT(WINAPI* query_api)(const GUID*, const GUID*, void**)) {
|
||||
constexpr GUID kCore = {0x073B7DCB, 0x1FCF, 0x4030, {0x94, 0xBE, 0xE3, 0xC9, 0xEB, 0x62, 0x34, 0x28}};
|
||||
void* core = nullptr;
|
||||
CHECK(SUCCEEDED(query_api(&kCore, &kCore, &core)) && core);
|
||||
auto** vtbl = *static_cast<void***>(core);
|
||||
auto async_run = reinterpret_cast<HRESULT(WINAPI*)(void*, Async*, HRESULT(CALLBACK*)(Async*))>(vtbl[6]);
|
||||
auto create_composite = reinterpret_cast<HRESULT(WINAPI*)(void*, void*, void*, void**)>(vtbl[13]);
|
||||
auto get_port = reinterpret_cast<HRESULT(WINAPI*)(void*, void*, uint32_t, void**)>(vtbl[14]);
|
||||
auto duplicate = reinterpret_cast<HRESULT(WINAPI*)(void*, void*, void**)>(vtbl[15]);
|
||||
const DWORD main_thread = GetCurrentThreadId();
|
||||
|
||||
// XAsyncRun: the work callback runs on the block's work port, its return value becomes the
|
||||
// block's status, and the completion callback runs on the completion port.
|
||||
{
|
||||
void* queue = nullptr;
|
||||
CHECK(XTaskQueueCreate(manual, manual, &queue) == S_OK && queue);
|
||||
RunRecord record{};
|
||||
Async async{queue, &record, run_completed, {}};
|
||||
CHECK(async_run(core, &async, run_work) == S_OK);
|
||||
CHECK(XAsyncGetStatus(&async, false) == E_PENDING && record.work_runs.load() == 0);
|
||||
CHECK(XTaskQueueDispatch(queue, work, 0));
|
||||
CHECK(record.work_runs.load() == 1 && record.work_thread.load() == main_thread);
|
||||
CHECK(record.completions.load() == 0);
|
||||
CHECK(XTaskQueueDispatch(queue, completion, 0));
|
||||
CHECK(record.completions.load() == 1 && XAsyncGetStatus(&async, false) == S_OK);
|
||||
|
||||
// A failing work callback's HRESULT is the block's status.
|
||||
RunRecord failing{};
|
||||
failing.result = E_ACCESSDENIED;
|
||||
Async failed{queue, &failing, nullptr, {}};
|
||||
CHECK(async_run(core, &failed, run_work) == S_OK);
|
||||
CHECK(XTaskQueueDispatch(queue, work, 0));
|
||||
CHECK(XAsyncGetStatus(&failed, false) == E_ACCESSDENIED);
|
||||
|
||||
CHECK(async_run(core, nullptr, run_work) == E_INVALIDARG);
|
||||
CHECK(async_run(core, &failed, nullptr) == E_INVALIDARG);
|
||||
XTaskQueueCloseHandle(queue);
|
||||
}
|
||||
|
||||
// XTaskQueueDuplicateHandle: both handles name one queue, and closing one leaves the other
|
||||
// usable. (Before the fix, closing any handle shut the queue's lanes down.)
|
||||
{
|
||||
void* queue = nullptr;
|
||||
CHECK(XTaskQueueCreate(manual, manual, &queue) == S_OK && queue);
|
||||
void* copy = nullptr;
|
||||
CHECK(duplicate(core, queue, ©) == S_OK && copy && copy != queue);
|
||||
DelayRecord through_copy{};
|
||||
CHECK(XTaskQueueSubmitCallback(copy, work, &through_copy, record_delay) == S_OK);
|
||||
CHECK(XTaskQueueDispatch(queue, work, 0) && through_copy.runs.load() == 1);
|
||||
XTaskQueueCloseHandle(queue);
|
||||
DelayRecord after_close{};
|
||||
CHECK(XTaskQueueSubmitCallback(copy, work, &after_close, record_delay) == S_OK);
|
||||
CHECK(XTaskQueueDispatch(copy, work, 0) && after_close.runs.load() == 1 && after_close.cancels.load() == 0);
|
||||
XTaskQueueCloseHandle(copy);
|
||||
void* refused = reinterpret_cast<void*>(uintptr_t{0x1234});
|
||||
CHECK(FAILED(duplicate(core, copy, &refused)) && refused == nullptr);
|
||||
CHECK(duplicate(core, nullptr, nullptr) == E_POINTER);
|
||||
}
|
||||
|
||||
// XTaskQueueGetPort and XTaskQueueCreateComposite: a composite's work port is one queue's
|
||||
// work port and its completion port is another queue's completion port. A callback sent to
|
||||
// the composite is dispatched from the queue that owns the port, and the other queue's own
|
||||
// ports are untouched.
|
||||
{
|
||||
void* a = nullptr;
|
||||
void* b = nullptr;
|
||||
CHECK(XTaskQueueCreate(manual, manual, &a) == S_OK && a);
|
||||
CHECK(XTaskQueueCreate(manual, manual, &b) == S_OK && b);
|
||||
void* a_work = nullptr;
|
||||
void* b_completion = nullptr;
|
||||
CHECK(get_port(core, a, static_cast<uint32_t>(work), &a_work) == S_OK && a_work);
|
||||
CHECK(get_port(core, b, static_cast<uint32_t>(completion), &b_completion) == S_OK && b_completion);
|
||||
void* no_port = reinterpret_cast<void*>(uintptr_t{0x1234});
|
||||
CHECK(get_port(core, a, 7, &no_port) == E_INVALIDARG && no_port == nullptr);
|
||||
void* composite = nullptr;
|
||||
CHECK(create_composite(core, a_work, b_completion, &composite) == S_OK && composite);
|
||||
|
||||
DelayRecord on_work{};
|
||||
DelayRecord on_completion{};
|
||||
CHECK(XTaskQueueSubmitCallback(composite, work, &on_work, record_delay) == S_OK);
|
||||
CHECK(XTaskQueueSubmitCallback(composite, completion, &on_completion, record_delay) == S_OK);
|
||||
// Not on the other queue's ports.
|
||||
CHECK(!XTaskQueueDispatch(b, work, 0) && !XTaskQueueDispatch(a, completion, 0));
|
||||
CHECK(on_work.runs.load() == 0 && on_completion.runs.load() == 0);
|
||||
// On the ports the composite was made from, through either handle.
|
||||
CHECK(XTaskQueueDispatch(a, work, 0) && on_work.runs.load() == 1);
|
||||
CHECK(XTaskQueueDispatch(composite, completion, 0) && on_completion.runs.load() == 1);
|
||||
|
||||
// XAsyncRun on the composite: work on a's work port, completion on b's completion port.
|
||||
RunRecord record{};
|
||||
Async async{composite, &record, run_completed, {}};
|
||||
CHECK(async_run(core, &async, run_work) == S_OK);
|
||||
CHECK(XTaskQueueDispatch(a, work, 0) && record.work_runs.load() == 1);
|
||||
CHECK(XTaskQueueDispatch(b, completion, 0) && record.completions.load() == 1);
|
||||
|
||||
void* bad = reinterpret_cast<void*>(uintptr_t{0x1234});
|
||||
CHECK(FAILED(create_composite(core, a, b_completion, &bad)) && bad == nullptr); // a queue handle is not a port
|
||||
XTaskQueueCloseHandle(composite);
|
||||
// Closing the composite does not close the queues it forwards to.
|
||||
DelayRecord still{};
|
||||
CHECK(XTaskQueueSubmitCallback(a, work, &still, record_delay) == S_OK);
|
||||
CHECK(XTaskQueueDispatch(a, work, 0) && still.runs.load() == 1);
|
||||
XTaskQueueCloseHandle(a);
|
||||
XTaskQueueCloseHandle(b);
|
||||
}
|
||||
}
|
||||
|
||||
void check_delayed_callback(HRESULT(WINAPI* query_api)(const GUID*, const GUID*, void**)) {
|
||||
constexpr GUID kCore = {0x073B7DCB, 0x1FCF, 0x4030, {0x94, 0xBE, 0xE3, 0xC9, 0xEB, 0x62, 0x34, 0x28}};
|
||||
void* core = nullptr;
|
||||
@@ -722,7 +850,8 @@ int main() {
|
||||
auto release = reinterpret_cast<ULONG(WINAPI*)(void*)>(core_vtbl[2]);
|
||||
auto tq_create = reinterpret_cast<HRESULT(WINAPI*)(void*, uint32_t, uint32_t, void**)>(core_vtbl[12]);
|
||||
auto tq_close = reinterpret_cast<void(WINAPI*)(void*, void*)>(core_vtbl[17]);
|
||||
auto unimpl_slot = reinterpret_cast<HRESULT(WINAPI*)(void*)>(core_vtbl[14]);
|
||||
// Slot 20 (XTaskQueueRegisterWaiter by the public order) is not implemented.
|
||||
auto unimpl_slot = reinterpret_cast<HRESULT(WINAPI*)(void*)>(core_vtbl[20]);
|
||||
void* qi_out = nullptr;
|
||||
CHECK(SUCCEEDED(qi(com_core, &iunknown, &qi_out)) && qi_out == com_core);
|
||||
void* q = nullptr;
|
||||
@@ -802,7 +931,48 @@ int main() {
|
||||
CHECK(unreg_ev(com_user, ev_tok, false));
|
||||
CHECK(!unreg_ev(com_user, ev_tok, false));
|
||||
|
||||
// XUserDuplicateHandle, XUserCloseHandle and XUserCompare through IXUser slots 3, 4 and 5
|
||||
// (#680). Slot numbers follow the public XUser.h declaration order; the expected behaviour
|
||||
// is the documented one: a duplicate is a separate handle to the same user, each handle
|
||||
// is closed on its own, and XUserCompare returns 0 for two handles of one user.
|
||||
{
|
||||
auto dup = reinterpret_cast<HRESULT(WINAPI*)(void*, void*, void**)>(user_vtbl[3]);
|
||||
auto close = reinterpret_cast<void(WINAPI*)(void*, void*)>(user_vtbl[4]);
|
||||
auto compare = reinterpret_cast<int32_t(WINAPI*)(void*, void*, void*)>(user_vtbl[5]);
|
||||
auto get_id = reinterpret_cast<HRESULT(WINAPI*)(void*, void*, uint64_t*)>(user_vtbl[11]);
|
||||
Async add{nullptr, nullptr, nullptr, {}};
|
||||
CHECK(XUserAddAsync(1, &add) == S_OK);
|
||||
CHECK(XAsyncGetStatus(&add, true) == S_OK);
|
||||
void* original = nullptr;
|
||||
CHECK(XUserAddResult(&add, &original) == S_OK && original);
|
||||
|
||||
void* copy = nullptr;
|
||||
CHECK(dup(com_user, original, ©) == S_OK && copy && copy != original);
|
||||
CHECK(compare(com_user, original, copy) == 0 && compare(com_user, copy, original) == 0);
|
||||
uint64_t copy_id = 0;
|
||||
CHECK(get_id(com_user, copy, ©_id) == S_OK && copy_id == 0x0009000000000001ULL);
|
||||
|
||||
// Closing the original leaves the duplicate valid, and the other way round.
|
||||
close(com_user, original);
|
||||
uint64_t gone = 0;
|
||||
CHECK(FAILED(XUserGetId(original, &gone)));
|
||||
CHECK(get_id(com_user, copy, ©_id) == S_OK);
|
||||
void* second = nullptr;
|
||||
CHECK(dup(com_user, copy, &second) == S_OK && second && second != copy);
|
||||
close(com_user, copy);
|
||||
CHECK(FAILED(XUserGetId(copy, &gone)));
|
||||
CHECK(XUserGetId(second, &gone) == S_OK);
|
||||
|
||||
// A closed or unknown handle is refused and the out pointer is cleared.
|
||||
void* refused = reinterpret_cast<void*>(uintptr_t{0x1234});
|
||||
CHECK(FAILED(dup(com_user, copy, &refused)) && refused == nullptr);
|
||||
CHECK(dup(com_user, second, nullptr) == E_POINTER);
|
||||
CHECK(compare(com_user, second, copy) != 0);
|
||||
close(com_user, second);
|
||||
}
|
||||
|
||||
check_delayed_callback(query_api);
|
||||
check_async_run_and_queue_handles(query_api);
|
||||
}
|
||||
|
||||
XGameRuntimeUninitialize();
|
||||
|
||||
Reference in new issue
Block a user