mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 09:30:42 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43f32acb82 |
No files matched your search
@@ -9,14 +9,6 @@ body:
|
||||
Use this template to hand off work to contributors across Tracks A-F.
|
||||
Keep file scopes disjoint so 5-8+ contributors can work concurrently without merge conflicts.
|
||||
Never include proprietary game files, names, hashes, or leaked material in issues or PRs.
|
||||
- type: textarea
|
||||
id: zen
|
||||
attributes:
|
||||
label: Zen
|
||||
description: 1–2 plain-English sentences explaining the core purpose of this issue and why it matters.
|
||||
placeholder: Enable guest allocations to stay within a 16 GiB Mac's unified memory budget so bring-up never OOMs.
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: track
|
||||
attributes:
|
||||
|
||||
@@ -100,6 +100,7 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
|
||||
## 6. Legal & Clean-Room Rules
|
||||
|
||||
- Use only publicly accessible documentation, publicly licensed software, and authorized synthetic workloads. Never obtain, paste, or commit leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or proprietary game builds and shader collections.
|
||||
- **Contributor clean-room rule:** Contributors who have seen leaked or confidential Xbox materials must not contribute (`CONTRIBUTING.md`, DCO `Signed-off-by` required on all commits).
|
||||
- **Legal boundary (`docs/legal.md`):** BetterXen does not circumvent console security or DRM and does not load encrypted or protected content. Validate technical compatibility and safety of user-provided files; do not ask for ownership receipts, accounts, or acquisition provenance as part of file loading.
|
||||
- Never place restricted material, personal paths, or secrets in the repository or its Git history.
|
||||
|
||||
|
||||
+1
-3
@@ -10,9 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
- `dxbc-accc` parses a synthetic FSPX section table inside DXBC `ACCC` chunks (section descriptors, section 1 stage configuration using the `bx_shader_stage_t` values, and section 6 RDNA 2 code bounds) and returns a parse error for truncated or out-of-range input instead of panicking. A table may declare at most 64 sections. A `DXIL` chunk is accepted only when it is a `DxilProgramHeader` from the public DirectXShaderCompiler layout. It exports `bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, and `bx_shader_free_buffer` with the layouts in `abi/include/bx_shader_bridge.h`. `bx_shader_inspect` fills that struct without logging. `bx_shader_prepare_for_d3dmetal` copies the `container_size` prefix when that DXIL header is present, including when the container also has a malformed FSPX table. An empty `DXIL` chunk is rejected. ACCC-only input returns `BX_SHADER_ERR_UNSUPPORTED` and writes one stderr inspection line. The first FSPX table that declares a stage supplies it. A failed stderr write does not panic. RDNA 2 bytes are not translated to DXIL. The section layout is synthetic and is not a console container specification or an Xbox hardware result (#416).
|
||||
- Added a visual `Progress Tracker` section to `README.md` with an M0–M6 Mermaid milestone pipeline, a Track A–F live status board (`🟩`/`🟨`/`⬜`), and direct GitHub label links for open M1 issues.
|
||||
- Added a required `Zen` field to `.github/ISSUE_TEMPLATE/track-handoff.yml` so every track handoff issue states its core purpose briefly in plain English up front.
|
||||
- Implemented synthetic APU heap mappings, per-connection APU and DSP queues, and the GameInput ordinal 1 COM stub. Added an audio/input conformance executable covering all four shim DLLs (#419).
|
||||
- Added Section 0 (`First-Time Contributor Onboarding`) to `AGENTS.md` (`CLAUDE.md` symlink) giving coding agents a turnkey step-by-step onboarding flow (preflight, `bx-cli doctor`, unclaimed `status: ready` issue discovery, claiming, scoped implementation, local verification including hosts without CrossOver, DCO commit, and PR CI watching).
|
||||
- Overhauled the repository into a clean 6-track parallel hybrid workspace (Milestone M0) designed for 5–8+ concurrent contributors and coding agents: added frozen cross-DLL ABI headers and canonical `.def` export tables (`abi/`), native ARM64 Rust workspace (`launcher/crates/{bx-cli,bx-probe,bx-telemetry}` with `env_clear()` child environment isolation, and `shader-transpiler/crates/dxbc-accc`), CMake + `mingw-w64` superbuild (`shims/`, `scripts/build-shims.sh`) producing 16 standalone x86-64 PE32+ shim DLLs (`bx_runtime_veh.dll` with working `clwb` VEH trap and JSONL logger, `xmem.dll`, `XCRDAPI.dll`, `d3d12_xs.dll`, `xg_xs.dll`, `xgameruntime.dll`, `GameInput.dll`, `AcpHal.dll`, `xapu.dll`, `chad.dll`, and PSM/ntuser forwarders) with strict PE Export Directory verification (exact names, ordinals, forwarders, zero extra exports, zero dynamic MinGW runtime dependencies), auto-discovered synthetic PE32+ conformance tests (`tests/conformance/`), `.github/workflows/hybrid-ci.yml`, `.github/ISSUE_TEMPLATE/track-handoff.yml`, `docs/adr/0006-retire-in-tree-native-workspace.md`, `docs/architecture/parallel-tracks.md`, and `docs/issues/wave-1-backlog.md`. Unified `docs/roadmap.md`, `CONTRIBUTING.md`, `AGENTS.md`, `README.md`, and `.github/CODEOWNERS` (retaining global `* @MacosPorters/maintainers` fallback and full provenance/independent-verification rules). Verified locally on Apple M5 (macOS 27.2.1, CrossOver 26.3, Rosetta 2) with all Rust checks, strict 16-DLL export verification, and live `test_veh_clwb.exe` + `test_shim_exports.exe` smoke tests passing.
|
||||
- Documented the original Windows workload set and Phase 1 hybrid measurement protocol (#353), including receipt-field sources, percentile definitions, negative controls and independent reproduction requirements. The protocol identifies the unmerged runner candidate and its missing raw traces and measurements; it adds no execution or compatibility claim.
|
||||
|
||||
@@ -27,58 +27,6 @@ BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Ro
|
||||
|
||||
---
|
||||
|
||||
## Progress Tracker
|
||||
|
||||
> *Tracks engineering milestones and synthetic conformance progress only — not commercial game compatibility percentages.*
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
M0["M0: Foundation & Shims\n(Merged #406)"]:::done
|
||||
M1["M1: Boot to D3D12\n(Active — Milestone #17)"]:::active
|
||||
M2["M2: First Frame &\nShader Gate"]:::planned
|
||||
M3["M3: Shaders &\nTexture Tiling"]:::planned
|
||||
M4["M4: 3D, DXR/BVH\n& Input"]:::planned
|
||||
M5["M5: Audio, Saves\n& Stability"]:::planned
|
||||
M6["M6: Cache & 16 GB\nOptimization"]:::planned
|
||||
|
||||
M0 --> M1 --> M2 --> M3 --> M4 --> M5 --> M6
|
||||
|
||||
classDef done fill:#dafbe1,stroke:#1a7f37,color:#0f5323,stroke-width:2px
|
||||
classDef active fill:#ddf4ff,stroke:#0969da,color:#0a3069,stroke-width:2px
|
||||
classDef planned fill:#f6f8fa,stroke:#8c959f,color:#57606a
|
||||
```
|
||||
|
||||
Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
|
||||
|
||||
### Active Milestone — [M1: Startup Shims to `D3D12XboxCreateDevice`](https://github.com/MacosPorters/betterxen/milestone/17)
|
||||
|
||||
| Track | Focus | Visual Status | Live Issues |
|
||||
| --- | --- | --- | --- |
|
||||
| **Track A** | `bx-cli` supervision, `clwb` VEH + crash dumper, Win32 bridge | `🟨🟨🟨` *(3/3 PRs open)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
|
||||
| **Track B** | `xmem.dll` core + physical/scatter pages, `XCRDAPI.dll` DirectStorage | `🟨🟨🟨` *(3/3 PRs open)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
|
||||
| **Track C** | `d3d12_xs.dll` COM proxy (D3DMetal 3.0), `xg_xs.dll` texture computer | `⬜⬜` *(needs contributors!)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
|
||||
| **Track D** | `dxbc-accc` FSPX C ABI bridge, `d3dmetal-native` harness | `🟨⬜` *(1 PR open, 1 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
|
||||
| **Track E** | `xgameruntime.dll` offline GDK, `AcpHal`/`xapu`/`chad`, `GameInput` | `🟨🟨` *(2/2 PRs open)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
|
||||
| **Track F** | End-to-end synthetic boot fixture (`test_integration_boot`) | `🟨` *(1/1 PR open)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
|
||||
|
||||
`🟩` Merged & verified · `🟨` PR open / in review · `⬜` Open & ready to claim
|
||||
|
||||
### Milestone Roadmap (M0 → M6)
|
||||
|
||||
| Milestone | Scope | Status |
|
||||
| --- | --- | --- |
|
||||
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 cross-compiled PE32+ shims, live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Merged (`#406`)** |
|
||||
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime`, audio queue stubs) | 🔵 **Active ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
|
||||
| **M2 — First Frame & Shader Gate** | `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0; inspect runtime shaders to select DXIL fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation | ⚪ Planned |
|
||||
| **M3 — Shaders, Streaming & Textures** | DirectStorage decompression, RDNA 2 `xg_xs` texture deswizzling, full shader pipeline | ⚪ Planned |
|
||||
| **M4 — 3D Rendering, DXR/BVH & Input** | BVH4 rehydration → live D3DMetal 3.0 DXR rebuild, PC FidelityFX/MetalFX upscaling shim, full `GameInput` | ⚪ Planned |
|
||||
| **M5 — Audio, Saves & Stability** | Software audio/DSP decoding (`AcpHal`/`xapu`/`chad`), `PersistentLocalStorage`, multi-hour soak stability | ⚪ Planned |
|
||||
| **M6 — Cache, 16 GB Tuning & Polish** | Persistent PSO/shader disk cache, Lockhart 16 GB unified memory optimization, Metal System Trace tuning | ⚪ Planned |
|
||||
|
||||
See [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md) and [docs/roadmap.md](docs/roadmap.md) for full details.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
Rosetta 2 executes x86-64 CPU code (including AVX/AVX2/FMA/F16C/BMI1/BMI2/128-bit VAES when launched with `ROSETTA_ADVERTISE_AVX=1`), CrossOver/Wine provides Win32/NT/CRT/XAudio2/WinHTTP, and D3DMetal 3.0 translates Direct3D 12 + DXR onto Metal. BetterXen supplies the modular Xbox Game OS shims, `clwb` exception handling, shader bridge, and ARM64 orchestration around that stack.
|
||||
@@ -141,6 +89,22 @@ The repository is organized into disjoint track directories around a single froz
|
||||
|
||||
---
|
||||
|
||||
## Milestones
|
||||
|
||||
| Milestone | Scope | Status |
|
||||
| --- | --- | --- |
|
||||
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 cross-compiled PE32+ shims, live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | **Verified locally on Apple M5** |
|
||||
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime`, audio queue stubs) | **Open (Wave 1 backlog ready)** |
|
||||
| **M2 — First Frame & Shader Gate** | `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0; inspect runtime shaders to select DXIL fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation | Planned |
|
||||
| **M3 — Shaders, Streaming & Textures** | DirectStorage decompression, RDNA 2 `xg_xs` texture deswizzling, full shader pipeline | Planned |
|
||||
| **M4 — 3D Rendering, DXR/BVH & Input** | BVH4 rehydration → live D3DMetal 3.0 DXR rebuild, PC FidelityFX/MetalFX upscaling shim, full `GameInput` | Planned |
|
||||
| **M5 — Audio, Saves & Stability** | Software audio/DSP decoding (`AcpHal`/`xapu`/`chad`), `PersistentLocalStorage`, multi-hour soak stability | Planned |
|
||||
| **M6 — Cache, 16 GB Tuning & Polish** | Persistent PSO/shader disk cache, Lockhart 16 GB unified memory optimization, Metal System Trace tuning | Planned |
|
||||
|
||||
See [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md) and [docs/roadmap.md](docs/roadmap.md) for full details.
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Requirements
|
||||
|
||||
@@ -5,8 +5,5 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lib]
|
||||
crate-type = ["rlib", "cdylib"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,422 +0,0 @@
|
||||
//! C ABI entry points from `abi/include/bx_shader_bridge.h`.
|
||||
//!
|
||||
//! `bx_shader_inspect` classifies a blob and fills `bx_shader_inspection_t`
|
||||
//! without logging or retaining chunk lists. `bx_shader_prepare_for_d3dmetal`
|
||||
//! copies `container_size` bytes when the container has a `DXIL` program
|
||||
//! header, even if an `FSPX` table in the same container is malformed. An
|
||||
//! empty `DXIL` chunk is `BX_SHADER_ERR_INVALID_BLOB`. It returns
|
||||
//! `BX_SHADER_ERR_UNSUPPORTED` for ACCC-only input and writes that inspection
|
||||
//! record to stderr. Other statuses are not logged. RDNA 2 to DXIL translation
|
||||
//! is not implemented. `bx_shader_free_buffer` releases a buffer returned by
|
||||
//! prepare.
|
||||
//!
|
||||
//! The shim logger `bx_log_emit` (declared in `abi/include/bx_log.h`) is
|
||||
//! provided by `bx_runtime_veh.dll`. This crate does not link that DLL. A
|
||||
//! failed stderr write is ignored so it cannot abort the host.
|
||||
|
||||
use std::alloc::{Layout, alloc, dealloc};
|
||||
#[cfg(test)]
|
||||
use std::cell::RefCell;
|
||||
use std::io::Write;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::ptr;
|
||||
|
||||
use super::{
|
||||
DxbcSummary, ShaderInspection, ShaderKind, ShaderStage, dxil_container_len, inspect_dxbc,
|
||||
summarize_dxbc,
|
||||
};
|
||||
|
||||
pub const BX_SHADER_OK: i32 = 0;
|
||||
pub const BX_SHADER_ERR_INVALID_BLOB: i32 = 1;
|
||||
pub const BX_SHADER_ERR_UNSUPPORTED: i32 = 2;
|
||||
pub const BX_SHADER_ERR_TRANSLATE: i32 = 3;
|
||||
pub const BX_SHADER_ERR_OOM: i32 = 4;
|
||||
|
||||
const _: () = {
|
||||
assert!(BX_SHADER_OK == 0);
|
||||
assert!(BX_SHADER_ERR_INVALID_BLOB == 1);
|
||||
assert!(BX_SHADER_ERR_UNSUPPORTED == 2);
|
||||
assert!(BX_SHADER_ERR_TRANSLATE == 3);
|
||||
assert!(BX_SHADER_ERR_OOM == 4);
|
||||
};
|
||||
|
||||
/// Rust layout of `bx_shader_inspection_t`.
|
||||
///
|
||||
/// The frozen header uses C enums, which are 4-byte `int` values on the
|
||||
/// mingw-w64 and Apple targets this ABI is written for, then six `uint32_t`
|
||||
/// fields and a 16-byte digest. The struct is 48 bytes with 4-byte alignment.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct BxShaderInspection {
|
||||
pub kind: i32,
|
||||
pub stage: i32,
|
||||
pub shader_model_major: u32,
|
||||
pub shader_model_minor: u32,
|
||||
pub container_size: u32,
|
||||
pub dxil_chunk_size: u32,
|
||||
pub accc_chunk_size: u32,
|
||||
pub has_root_signature: u32,
|
||||
pub digest_hash: [u8; 16],
|
||||
}
|
||||
|
||||
const _: () = {
|
||||
assert!(std::mem::size_of::<BxShaderInspection>() == 48);
|
||||
assert!(std::mem::align_of::<BxShaderInspection>() == 4);
|
||||
assert!(std::mem::offset_of!(BxShaderInspection, kind) == 0);
|
||||
assert!(std::mem::offset_of!(BxShaderInspection, stage) == 4);
|
||||
assert!(std::mem::offset_of!(BxShaderInspection, shader_model_major) == 8);
|
||||
assert!(std::mem::offset_of!(BxShaderInspection, shader_model_minor) == 12);
|
||||
assert!(std::mem::offset_of!(BxShaderInspection, container_size) == 16);
|
||||
assert!(std::mem::offset_of!(BxShaderInspection, dxil_chunk_size) == 20);
|
||||
assert!(std::mem::offset_of!(BxShaderInspection, accc_chunk_size) == 24);
|
||||
assert!(std::mem::offset_of!(BxShaderInspection, has_root_signature) == 28);
|
||||
assert!(std::mem::offset_of!(BxShaderInspection, digest_hash) == 32);
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static SHADER_LOG: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn clear_shader_log() {
|
||||
SHADER_LOG.with(|log| log.borrow_mut().clear());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn shader_log_lines() -> Vec<String> {
|
||||
SHADER_LOG.with(|log| log.borrow().clone())
|
||||
}
|
||||
|
||||
fn emit(line: String) {
|
||||
let _ = writeln!(std::io::stderr().lock(), "{line}");
|
||||
#[cfg(test)]
|
||||
SHADER_LOG.with(|log| log.borrow_mut().push(line));
|
||||
}
|
||||
|
||||
fn kind_name(kind: ShaderKind) -> &'static str {
|
||||
match kind {
|
||||
ShaderKind::Unknown => "unknown",
|
||||
ShaderKind::Dxil => "dxil",
|
||||
ShaderKind::LegacyDxbc => "legacy_dxbc",
|
||||
ShaderKind::AcccOnly => "accc_only",
|
||||
ShaderKind::DualDxilAndAccc => "dual",
|
||||
}
|
||||
}
|
||||
|
||||
fn stage_name(stage: ShaderStage) -> &'static str {
|
||||
match stage {
|
||||
ShaderStage::Unknown => "unknown",
|
||||
ShaderStage::Pixel => "pixel",
|
||||
ShaderStage::Vertex => "vertex",
|
||||
ShaderStage::Geometry => "geometry",
|
||||
ShaderStage::Hull => "hull",
|
||||
ShaderStage::Domain => "domain",
|
||||
ShaderStage::Compute => "compute",
|
||||
ShaderStage::Library => "library",
|
||||
ShaderStage::Mesh => "mesh",
|
||||
ShaderStage::Amplification => "amplification",
|
||||
}
|
||||
}
|
||||
|
||||
fn abi_kind(kind: ShaderKind) -> i32 {
|
||||
match kind {
|
||||
ShaderKind::Unknown => 0,
|
||||
ShaderKind::Dxil => 1,
|
||||
ShaderKind::LegacyDxbc => 2,
|
||||
ShaderKind::AcccOnly => 3,
|
||||
ShaderKind::DualDxilAndAccc => 4,
|
||||
}
|
||||
}
|
||||
|
||||
fn abi_stage(stage: ShaderStage) -> i32 {
|
||||
match stage {
|
||||
ShaderStage::Unknown => 0,
|
||||
ShaderStage::Pixel => 1,
|
||||
ShaderStage::Vertex => 2,
|
||||
ShaderStage::Geometry => 3,
|
||||
ShaderStage::Hull => 4,
|
||||
ShaderStage::Domain => 5,
|
||||
ShaderStage::Compute => 6,
|
||||
ShaderStage::Library => 7,
|
||||
ShaderStage::Mesh => 8,
|
||||
ShaderStage::Amplification => 9,
|
||||
}
|
||||
}
|
||||
|
||||
fn hex_digest(bytes: &[u8; 16]) -> String {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let mut out = String::with_capacity(32);
|
||||
for byte in bytes {
|
||||
out.push(HEX[usize::from(byte >> 4)] as char);
|
||||
out.push(HEX[usize::from(byte & 0x0f)] as char);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn format_inspection(event: &str, status: &str, detail: &str, info: &ShaderInspection) -> String {
|
||||
let (fspx, version, sections, rdna_off, rdna_size) = if let Some(fspx) = &info.fspx {
|
||||
let sections = if fspx.sections.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
fspx.sections
|
||||
.iter()
|
||||
.map(|section| format!("{}@{}+{}", section.id, section.offset, section.size))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
};
|
||||
let (rdna_off, rdna_size) = match fspx.rdna_code {
|
||||
Some(code) => (code.offset.to_string(), code.size.to_string()),
|
||||
None => ("none".to_string(), "none".to_string()),
|
||||
};
|
||||
("1", fspx.version.to_string(), sections, rdna_off, rdna_size)
|
||||
} else {
|
||||
(
|
||||
"0",
|
||||
"none".to_string(),
|
||||
"none".to_string(),
|
||||
"none".to_string(),
|
||||
"none".to_string(),
|
||||
)
|
||||
};
|
||||
format!(
|
||||
"bx-shader event={event} status={status} detail={detail} kind={}({}) stage={}({}) sm_major={} sm_minor={} container_size={} dxil_chunk_size={} accc_chunk_size={} has_root_signature={} digest={} fspx={fspx} fspx_version={version} sections={sections} rdna_off={rdna_off} rdna_size={rdna_size}",
|
||||
kind_name(info.kind),
|
||||
abi_kind(info.kind),
|
||||
stage_name(info.stage),
|
||||
abi_stage(info.stage),
|
||||
info.shader_model_major,
|
||||
info.shader_model_minor,
|
||||
info.container_size,
|
||||
info.dxil_size,
|
||||
info.accc_size,
|
||||
u32::from(info.has_root_signature),
|
||||
hex_digest(&info.digest),
|
||||
)
|
||||
}
|
||||
|
||||
fn log_accc_unsupported(info: &ShaderInspection) {
|
||||
emit(format_inspection(
|
||||
"prepare",
|
||||
"unsupported",
|
||||
"no_dxil_passthrough",
|
||||
info,
|
||||
));
|
||||
}
|
||||
|
||||
fn to_c_inspection(info: &DxbcSummary) -> BxShaderInspection {
|
||||
BxShaderInspection {
|
||||
kind: abi_kind(info.kind),
|
||||
stage: abi_stage(info.stage),
|
||||
shader_model_major: u32::from(info.shader_model_major),
|
||||
shader_model_minor: u32::from(info.shader_model_minor),
|
||||
container_size: info.container_size,
|
||||
dxil_chunk_size: info.dxil_size,
|
||||
accc_chunk_size: info.accc_size,
|
||||
has_root_signature: u32::from(info.has_root_signature),
|
||||
digest_hash: info.digest,
|
||||
}
|
||||
}
|
||||
|
||||
fn input_bytes<'a>(bytes: *const u8, len: usize) -> Option<&'a [u8]> {
|
||||
if len == 0 {
|
||||
return Some(&[]);
|
||||
}
|
||||
if bytes.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: The caller of the unsafe entry point guarantees `bytes` is
|
||||
// readable for `len` bytes when it is non-null. `len` is non-zero here.
|
||||
Some(unsafe { std::slice::from_raw_parts(bytes, len) })
|
||||
}
|
||||
|
||||
fn alloc_copy(src: &[u8]) -> Result<*mut u8, ()> {
|
||||
if src.is_empty() {
|
||||
return Err(());
|
||||
}
|
||||
let layout = Layout::from_size_align(src.len(), 1).map_err(|_| ())?;
|
||||
// SAFETY: `layout` has a non-zero size and alignment 1.
|
||||
let ptr = unsafe { alloc(layout) };
|
||||
if ptr.is_null() {
|
||||
return Err(());
|
||||
}
|
||||
// SAFETY: `alloc` returned a writable block of `src.len()` bytes, and
|
||||
// `src` is a valid readable region of that length. The regions do not
|
||||
// overlap.
|
||||
unsafe {
|
||||
ptr::copy_nonoverlapping(src.as_ptr(), ptr, src.len());
|
||||
}
|
||||
Ok(ptr)
|
||||
}
|
||||
|
||||
fn guard(body: impl FnOnce() -> i32 + std::panic::UnwindSafe) -> i32 {
|
||||
match catch_unwind(body) {
|
||||
Ok(status) => status,
|
||||
Err(_) => BX_SHADER_ERR_INVALID_BLOB,
|
||||
}
|
||||
}
|
||||
|
||||
fn inspect_status(bytes: *const u8, len: usize, out_info: *mut BxShaderInspection) -> i32 {
|
||||
if out_info.is_null() {
|
||||
return BX_SHADER_ERR_INVALID_BLOB;
|
||||
}
|
||||
let Some(bytes) = input_bytes(bytes, len) else {
|
||||
// SAFETY: `out_info` was checked non-null and the caller guarantees it
|
||||
// is writable for one `BxShaderInspection`.
|
||||
unsafe { out_info.write(BxShaderInspection::default()) };
|
||||
return BX_SHADER_ERR_INVALID_BLOB;
|
||||
};
|
||||
match summarize_dxbc(bytes) {
|
||||
Ok(info) => {
|
||||
let c_info = to_c_inspection(&info);
|
||||
// SAFETY: `out_info` is non-null and writable for one inspection.
|
||||
unsafe { out_info.write(c_info) };
|
||||
BX_SHADER_OK
|
||||
}
|
||||
Err(_) => {
|
||||
// SAFETY: `out_info` is non-null and writable for one inspection.
|
||||
unsafe { out_info.write(BxShaderInspection::default()) };
|
||||
BX_SHADER_ERR_INVALID_BLOB
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_status(
|
||||
in_bytes: *const u8,
|
||||
in_len: usize,
|
||||
out_bytes: *mut *mut u8,
|
||||
out_len: *mut usize,
|
||||
) -> i32 {
|
||||
if out_bytes.is_null() || out_len.is_null() {
|
||||
return BX_SHADER_ERR_INVALID_BLOB;
|
||||
}
|
||||
// SAFETY: both pointers were checked non-null and the caller guarantees
|
||||
// they are writable.
|
||||
unsafe {
|
||||
*out_bytes = ptr::null_mut();
|
||||
*out_len = 0;
|
||||
}
|
||||
let Some(bytes) = input_bytes(in_bytes, in_len) else {
|
||||
return BX_SHADER_ERR_INVALID_BLOB;
|
||||
};
|
||||
let container_size = match dxil_container_len(bytes) {
|
||||
Ok(Some(size)) => size,
|
||||
Ok(None) => {
|
||||
return match inspect_dxbc(bytes) {
|
||||
Ok(info) if info.kind == ShaderKind::AcccOnly => {
|
||||
log_accc_unsupported(&info);
|
||||
BX_SHADER_ERR_UNSUPPORTED
|
||||
}
|
||||
Ok(_) => BX_SHADER_ERR_UNSUPPORTED,
|
||||
Err(_) => BX_SHADER_ERR_INVALID_BLOB,
|
||||
};
|
||||
}
|
||||
Err(_) => return BX_SHADER_ERR_INVALID_BLOB,
|
||||
};
|
||||
let Some(len) = usize::try_from(container_size).ok() else {
|
||||
return BX_SHADER_ERR_INVALID_BLOB;
|
||||
};
|
||||
if len == 0 || len > bytes.len() {
|
||||
return BX_SHADER_ERR_INVALID_BLOB;
|
||||
}
|
||||
let ptr = match alloc_copy(&bytes[..len]) {
|
||||
Ok(ptr) => ptr,
|
||||
Err(()) => return BX_SHADER_ERR_OOM,
|
||||
};
|
||||
// SAFETY: `out_bytes` and `out_len` are non-null and writable. `len` is
|
||||
// the container size, which is not larger than `bytes`.
|
||||
unsafe {
|
||||
*out_bytes = ptr;
|
||||
*out_len = len;
|
||||
}
|
||||
BX_SHADER_OK
|
||||
}
|
||||
|
||||
/// Inspect `bytes` without allocating.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// When `bytes` is non-null it must be readable for `len` bytes. A null
|
||||
/// `bytes` pointer is not dereferenced. `out_info` must be non-null and
|
||||
/// writable; a null `out_info` returns [`BX_SHADER_ERR_INVALID_BLOB`].
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn bx_shader_inspect(
|
||||
bytes: *const u8,
|
||||
len: usize,
|
||||
out_info: *mut BxShaderInspection,
|
||||
) -> i32 {
|
||||
let status = guard(AssertUnwindSafe(|| inspect_status(bytes, len, out_info)));
|
||||
if status == BX_SHADER_ERR_INVALID_BLOB && !out_info.is_null() {
|
||||
// SAFETY: a non-null `out_info` is writable for one inspection. This
|
||||
// also covers a panic after a partial write.
|
||||
unsafe { out_info.write(BxShaderInspection::default()) };
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
/// Copy a DXIL container, or report that an ACCC-only container cannot be
|
||||
/// prepared for D3DMetal.
|
||||
///
|
||||
/// On [`BX_SHADER_OK`], `*out_bytes` is a copy of the first `container_size`
|
||||
/// bytes and `*out_len` is that size. Bytes past `container_size` are not
|
||||
/// copied. A `DXIL` chunk is copied even when an `FSPX` table in the same
|
||||
/// container is malformed. The caller frees the pointer with
|
||||
/// [`bx_shader_free_buffer`]. On every other status, `*out_bytes` is null and
|
||||
/// `*out_len` is 0 when the output pointers are non-null.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// When `in_bytes` is non-null it must be readable for `in_len` bytes.
|
||||
/// `out_bytes` and `out_len` must both be non-null and writable.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn bx_shader_prepare_for_d3dmetal(
|
||||
in_bytes: *const u8,
|
||||
in_len: usize,
|
||||
out_bytes: *mut *mut u8,
|
||||
out_len: *mut usize,
|
||||
) -> i32 {
|
||||
let status = guard(AssertUnwindSafe(|| {
|
||||
prepare_status(in_bytes, in_len, out_bytes, out_len)
|
||||
}));
|
||||
if status != BX_SHADER_OK && !out_bytes.is_null() && !out_len.is_null() {
|
||||
// SAFETY: the caller guarantees both pointers are writable. A panic
|
||||
// after publication drops the copy instead of returning it.
|
||||
unsafe {
|
||||
let ptr = *out_bytes;
|
||||
let len = *out_len;
|
||||
*out_bytes = ptr::null_mut();
|
||||
*out_len = 0;
|
||||
if !ptr.is_null() && len > 0 {
|
||||
free_buffer(ptr, len);
|
||||
}
|
||||
}
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
fn free_buffer(ptr: *mut u8, len: usize) {
|
||||
if ptr.is_null() || len == 0 {
|
||||
return;
|
||||
}
|
||||
let Ok(layout) = Layout::from_size_align(len, 1) else {
|
||||
return;
|
||||
};
|
||||
// SAFETY: The caller guarantees `ptr` was allocated by `alloc_copy` with
|
||||
// this layout (size `len`, alignment 1) and has not been freed.
|
||||
unsafe { dealloc(ptr, layout) };
|
||||
}
|
||||
|
||||
/// Free a buffer allocated by [`bx_shader_prepare_for_d3dmetal`].
|
||||
///
|
||||
/// A null `ptr` or a `len` of 0 is a no-op. `len` must be the length returned
|
||||
/// in `out_len` for that pointer. The allocation uses alignment 1.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// When `ptr` is non-null and `len` is non-zero, `ptr` must have been returned
|
||||
/// by [`bx_shader_prepare_for_d3dmetal`] and `len` must be the matching length.
|
||||
/// The pointer must not be freed twice.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn bx_shader_free_buffer(ptr: *mut u8, len: usize) {
|
||||
let _ = catch_unwind(AssertUnwindSafe(|| free_buffer(ptr, len)));
|
||||
}
|
||||
@@ -1,312 +0,0 @@
|
||||
//! Synthetic `FSPX` section table carried inside an `ACCC` chunk payload.
|
||||
//!
|
||||
//! This is BetterXen's clean-room layout for synthetic blobs and for inputs
|
||||
//! that adopt the same layout. It is not a description of a console compiler's
|
||||
//! on-disk format. A successful parse does not mean the bytes are RDNA 2
|
||||
//! machine code from any particular GPU, and it is not Xbox hardware
|
||||
//! verification. Section 6 is a byte range only; this module does not
|
||||
//! disassemble it.
|
||||
//!
|
||||
//! A version-1 table holds at most [`FSPX_MAX_SECTIONS`] descriptors. A larger
|
||||
//! count is rejected before any descriptor is compared with another, so
|
||||
//! inspection stays allocation-free and the pairwise check stays bounded.
|
||||
|
||||
use super::{ShaderStage, read_u32_le};
|
||||
|
||||
/// Most sections one synthetic FSPX table may declare.
|
||||
///
|
||||
/// Validation re-reads earlier descriptors from the payload and does not
|
||||
/// allocate. At this cap the pairwise check is at most 2,016 comparisons.
|
||||
/// `65` or more is an error before that loop starts.
|
||||
pub const FSPX_MAX_SECTIONS: usize = 64;
|
||||
|
||||
/// One bounds-checked section descriptor.
|
||||
///
|
||||
/// `offset` is relative to the first byte of the `FSPX` payload (the `FSPX`
|
||||
/// magic), not relative to the enclosing DXBC container.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct FspxSection {
|
||||
pub id: u32,
|
||||
pub offset: u32,
|
||||
pub size: u32,
|
||||
}
|
||||
|
||||
/// Section 1, the shader stage configuration.
|
||||
///
|
||||
/// `stage` uses the `bx_shader_stage_t` numbering from
|
||||
/// `abi/include/bx_shader_bridge.h`: 0 unknown, 1 pixel, 2 vertex, 3 geometry,
|
||||
/// 4 hull, 5 domain, 6 compute, 7 library, 8 mesh, 9 amplification.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct FspxStageConfig {
|
||||
pub offset: u32,
|
||||
pub size: u32,
|
||||
pub stage: ShaderStage,
|
||||
pub shader_model_major: u8,
|
||||
pub shader_model_minor: u8,
|
||||
}
|
||||
|
||||
/// Section 6, the RDNA 2 code byte range inside the `FSPX` payload.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct FspxCodeBounds {
|
||||
pub offset: u32,
|
||||
pub size: u32,
|
||||
}
|
||||
|
||||
/// A parsed synthetic `FSPX` table.
|
||||
///
|
||||
/// Version 0 is the magic-only stub: `section_count` must be 0 and no section
|
||||
/// bytes are read. Version 1 is the section table.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FspxInfo {
|
||||
pub version: u32,
|
||||
pub flags: u32,
|
||||
pub sections: Vec<FspxSection>,
|
||||
pub section0: Option<FspxSection>,
|
||||
pub stage_config: Option<FspxStageConfig>,
|
||||
pub rdna_code: Option<FspxCodeBounds>,
|
||||
pub section7: Option<FspxSection>,
|
||||
}
|
||||
|
||||
impl FspxInfo {
|
||||
/// Return the section 6 bytes, or `None` when the recorded bounds do not
|
||||
/// fit in `fspx_payload`.
|
||||
pub fn rdna_code_bytes<'a>(&self, fspx_payload: &'a [u8]) -> Option<&'a [u8]> {
|
||||
let code = self.rdna_code.as_ref()?;
|
||||
let start = code.offset as usize;
|
||||
let end = start.checked_add(code.size as usize)?;
|
||||
fspx_payload.get(start..end)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum FspxError {
|
||||
Truncated,
|
||||
BadVersion(u32),
|
||||
SectionOutOfBounds { section_id: u32 },
|
||||
DuplicateSection { section_id: u32 },
|
||||
Overlap { section_id: u32 },
|
||||
BadStageConfig,
|
||||
TooManySections(u32),
|
||||
}
|
||||
|
||||
const HEADER_LEN: usize = 16;
|
||||
const DESCRIPTOR_LEN: usize = 12;
|
||||
const STAGE_CONFIG_LEN: usize = 12;
|
||||
|
||||
fn stage_from_abi(raw: u32) -> Option<ShaderStage> {
|
||||
Some(match raw {
|
||||
0 => ShaderStage::Unknown,
|
||||
1 => ShaderStage::Pixel,
|
||||
2 => ShaderStage::Vertex,
|
||||
3 => ShaderStage::Geometry,
|
||||
4 => ShaderStage::Hull,
|
||||
5 => ShaderStage::Domain,
|
||||
6 => ShaderStage::Compute,
|
||||
7 => ShaderStage::Library,
|
||||
8 => ShaderStage::Mesh,
|
||||
9 => ShaderStage::Amplification,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn section_end(offset: u32, size: u32, table_end: usize, payload_len: usize) -> Option<usize> {
|
||||
let start = usize::try_from(offset).ok()?;
|
||||
let len = usize::try_from(size).ok()?;
|
||||
let end = start.checked_add(len)?;
|
||||
if start < table_end || end > payload_len {
|
||||
return None;
|
||||
}
|
||||
Some(end)
|
||||
}
|
||||
|
||||
fn ranges_overlap(a_off: u32, a_size: u32, b_off: u32, b_size: u32) -> bool {
|
||||
let a0 = u64::from(a_off);
|
||||
let a1 = a0 + u64::from(a_size);
|
||||
let b0 = u64::from(b_off);
|
||||
let b1 = b0 + u64::from(b_size);
|
||||
a0 < b1 && b0 < a1
|
||||
}
|
||||
|
||||
fn stage_from_body(body: &[u8]) -> Result<(ShaderStage, u8, u8), FspxError> {
|
||||
if body.len() != STAGE_CONFIG_LEN {
|
||||
return Err(FspxError::BadStageConfig);
|
||||
}
|
||||
let stage_raw = read_u32_le(body, 0).ok_or(FspxError::BadStageConfig)?;
|
||||
let major = read_u32_le(body, 4).ok_or(FspxError::BadStageConfig)?;
|
||||
let minor = read_u32_le(body, 8).ok_or(FspxError::BadStageConfig)?;
|
||||
let stage = stage_from_abi(stage_raw).ok_or(FspxError::BadStageConfig)?;
|
||||
let shader_model_major = u8::try_from(major).map_err(|_| FspxError::BadStageConfig)?;
|
||||
let shader_model_minor = u8::try_from(minor).map_err(|_| FspxError::BadStageConfig)?;
|
||||
Ok((stage, shader_model_major, shader_model_minor))
|
||||
}
|
||||
|
||||
fn descriptor_at(payload: &[u8], index: usize) -> Result<(u32, u32, u32), FspxError> {
|
||||
let at = HEADER_LEN
|
||||
.checked_add(
|
||||
index
|
||||
.checked_mul(DESCRIPTOR_LEN)
|
||||
.ok_or(FspxError::Truncated)?,
|
||||
)
|
||||
.ok_or(FspxError::Truncated)?;
|
||||
let id = read_u32_le(payload, at).ok_or(FspxError::Truncated)?;
|
||||
let offset = read_u32_le(payload, at + 4).ok_or(FspxError::Truncated)?;
|
||||
let size = read_u32_le(payload, at + 8).ok_or(FspxError::Truncated)?;
|
||||
Ok((id, offset, size))
|
||||
}
|
||||
|
||||
struct FspxHeader {
|
||||
version: u32,
|
||||
flags: u32,
|
||||
count: usize,
|
||||
table_end: usize,
|
||||
}
|
||||
|
||||
/// `Ok(None)` when the payload does not start with `FSPX`.
|
||||
fn read_fspx_header(payload: &[u8]) -> Result<Option<FspxHeader>, FspxError> {
|
||||
if payload.get(..4) != Some(b"FSPX".as_slice()) {
|
||||
return Ok(None);
|
||||
}
|
||||
if payload.len() < HEADER_LEN {
|
||||
return Err(FspxError::Truncated);
|
||||
}
|
||||
let version = read_u32_le(payload, 4).ok_or(FspxError::Truncated)?;
|
||||
let section_count = read_u32_le(payload, 8).ok_or(FspxError::Truncated)?;
|
||||
let flags = read_u32_le(payload, 12).ok_or(FspxError::Truncated)?;
|
||||
if version == 0 {
|
||||
if section_count != 0 {
|
||||
return Err(FspxError::BadVersion(0));
|
||||
}
|
||||
return Ok(Some(FspxHeader {
|
||||
version,
|
||||
flags,
|
||||
count: 0,
|
||||
table_end: HEADER_LEN,
|
||||
}));
|
||||
}
|
||||
if version != 1 {
|
||||
return Err(FspxError::BadVersion(version));
|
||||
}
|
||||
let count = usize::try_from(section_count).map_err(|_| FspxError::Truncated)?;
|
||||
if count > FSPX_MAX_SECTIONS {
|
||||
return Err(FspxError::TooManySections(section_count));
|
||||
}
|
||||
let table_bytes = count
|
||||
.checked_mul(DESCRIPTOR_LEN)
|
||||
.ok_or(FspxError::Truncated)?;
|
||||
let table_end = HEADER_LEN
|
||||
.checked_add(table_bytes)
|
||||
.ok_or(FspxError::Truncated)?;
|
||||
if table_end > payload.len() {
|
||||
return Err(FspxError::Truncated);
|
||||
}
|
||||
Ok(Some(FspxHeader {
|
||||
version,
|
||||
flags,
|
||||
count,
|
||||
table_end,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Validate every descriptor by re-reading earlier ones from `payload`.
|
||||
///
|
||||
/// The check does not allocate. `on_section` receives the section bytes.
|
||||
fn walk_sections(
|
||||
payload: &[u8],
|
||||
header: &FspxHeader,
|
||||
mut on_section: impl FnMut(FspxSection, &[u8]) -> Result<(), FspxError>,
|
||||
) -> Result<(), FspxError> {
|
||||
for index in 0..header.count {
|
||||
let (id, offset, size) = descriptor_at(payload, index)?;
|
||||
let end = section_end(offset, size, header.table_end, payload.len())
|
||||
.ok_or(FspxError::SectionOutOfBounds { section_id: id })?;
|
||||
for prev in 0..index {
|
||||
let (prev_id, prev_off, prev_size) = descriptor_at(payload, prev)?;
|
||||
if prev_id == id {
|
||||
return Err(FspxError::DuplicateSection { section_id: id });
|
||||
}
|
||||
if ranges_overlap(prev_off, prev_size, offset, size) {
|
||||
return Err(FspxError::Overlap { section_id: id });
|
||||
}
|
||||
}
|
||||
let start = usize::try_from(offset)
|
||||
.map_err(|_| FspxError::SectionOutOfBounds { section_id: id })?;
|
||||
let body = payload
|
||||
.get(start..end)
|
||||
.ok_or(FspxError::SectionOutOfBounds { section_id: id })?;
|
||||
on_section(FspxSection { id, offset, size }, body)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stage word from a version-1 table, without retaining the section list.
|
||||
///
|
||||
/// `Ok(None)` means the payload is not `FSPX`. `Ok(Some(scan))` is a
|
||||
/// magic-only stub or a valid table. `scan.stage` is set only when section 1
|
||||
/// is present.
|
||||
pub(crate) struct FspxStageScan {
|
||||
pub stage: Option<(ShaderStage, u8, u8)>,
|
||||
}
|
||||
|
||||
pub(crate) fn scan_fspx(payload: &[u8]) -> Result<Option<FspxStageScan>, FspxError> {
|
||||
let Some(header) = read_fspx_header(payload)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut stage = None;
|
||||
walk_sections(payload, &header, |section, body| {
|
||||
if section.id == 1 {
|
||||
stage = Some(stage_from_body(body)?);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Some(FspxStageScan { stage }))
|
||||
}
|
||||
|
||||
/// Parse an `ACCC` payload.
|
||||
///
|
||||
/// `Ok(None)` means the payload does not start with `FSPX`. `Ok(Some(_))` is a
|
||||
/// magic-only stub or a complete section table. Malformed `FSPX` bytes are
|
||||
/// `Err` and never panic.
|
||||
pub(crate) fn parse_fspx(payload: &[u8]) -> Result<Option<FspxInfo>, FspxError> {
|
||||
let Some(header) = read_fspx_header(payload)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut sections = Vec::new();
|
||||
let mut section0 = None;
|
||||
let mut stage_config = None;
|
||||
let mut rdna_code = None;
|
||||
let mut section7 = None;
|
||||
walk_sections(payload, &header, |section, body| {
|
||||
match section.id {
|
||||
0 => section0 = Some(section),
|
||||
1 => {
|
||||
let (stage, shader_model_major, shader_model_minor) = stage_from_body(body)?;
|
||||
stage_config = Some(FspxStageConfig {
|
||||
offset: section.offset,
|
||||
size: section.size,
|
||||
stage,
|
||||
shader_model_major,
|
||||
shader_model_minor,
|
||||
});
|
||||
}
|
||||
6 => {
|
||||
rdna_code = Some(FspxCodeBounds {
|
||||
offset: section.offset,
|
||||
size: section.size,
|
||||
});
|
||||
}
|
||||
7 => section7 = Some(section),
|
||||
_ => {}
|
||||
}
|
||||
sections.push(section);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Some(FspxInfo {
|
||||
version: header.version,
|
||||
flags: header.flags,
|
||||
sections,
|
||||
section0,
|
||||
stage_config,
|
||||
rdna_code,
|
||||
section7,
|
||||
}))
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+104
-24
@@ -1,20 +1,52 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
/* Track E (M1-E2 / M5): AcpHal.dll SHAPE Audio Coprocessor HAL shim. */
|
||||
namespace {
|
||||
class AcpHal final : public IUnknown {
|
||||
LONG refs = 1;
|
||||
public:
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (iid != IID_IUnknown) return E_NOINTERFACE;
|
||||
AddRef();
|
||||
*out = this;
|
||||
return S_OK;
|
||||
}
|
||||
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
|
||||
ULONG WINAPI Release() override {
|
||||
ULONG left = InterlockedDecrement(&refs);
|
||||
if (!left) delete this;
|
||||
return left;
|
||||
}
|
||||
};
|
||||
|
||||
// Sorted synthetic address ranges. Zero is reserved for failed lookups.
|
||||
struct Allocation {
|
||||
uintptr_t va;
|
||||
uint32_t base, size;
|
||||
Allocation* next;
|
||||
};
|
||||
Allocation* allocations;
|
||||
std::mutex heap_lock;
|
||||
uint64_t capacity = UINT32_MAX;
|
||||
uint64_t used;
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT WINAPI AcpHalCreate(void** out_hal) {
|
||||
BX_STUB_LOG("AcpHal.dll", "AcpHalCreate");
|
||||
if (out_hal) *out_hal = nullptr;
|
||||
return E_NOTIMPL;
|
||||
HRESULT WINAPI AcpHalCreate(void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = new (std::nothrow) AcpHal;
|
||||
return *out ? S_OK : E_OUTOFMEMORY;
|
||||
}
|
||||
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void* /*desc*/) {
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void*) {
|
||||
BX_STUB_LOG("AcpHal.dll", "AcpHalAllocateShapeContexts");
|
||||
return S_OK;
|
||||
}
|
||||
@@ -24,35 +56,83 @@ HRESULT WINAPI AcpHalReleaseShapeContexts(void) {
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI ApuCreateHeap(uint32_t /*cached_size*/, uint32_t /*non_cached_size*/) {
|
||||
BX_STUB_LOG("AcpHal.dll", "ApuCreateHeap");
|
||||
HRESULT WINAPI ApuCreateHeap(uint32_t cached, uint32_t non_cached) {
|
||||
std::lock_guard guard(heap_lock);
|
||||
if (allocations) return HRESULT_FROM_WIN32(ERROR_BUSY);
|
||||
capacity = uint64_t(cached) + non_cached;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI ApuAlloc(void** out_va, uint32_t* out_apu_addr, uint32_t size, uint32_t alignment) {
|
||||
HRESULT WINAPI ApuAlloc(void** va, uint32_t* apu, uint32_t size, uint32_t alignment) {
|
||||
if (va) *va = nullptr;
|
||||
if (apu) *apu = 0;
|
||||
if (!va && !apu) return E_POINTER;
|
||||
if (alignment && (alignment & (alignment - 1))) return E_INVALIDARG;
|
||||
if (alignment < 64) alignment = 64;
|
||||
void* p = _aligned_malloc(size ? size : 64, alignment);
|
||||
if (out_va) *out_va = p;
|
||||
if (out_apu_addr) *out_apu_addr = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(p) & 0xFFFFFFFFu);
|
||||
return p ? S_OK : E_OUTOFMEMORY;
|
||||
if (!size) size = 64;
|
||||
std::lock_guard guard(heap_lock);
|
||||
if (size > capacity - used) return E_OUTOFMEMORY;
|
||||
uint64_t base = alignment;
|
||||
Allocation** link = &allocations;
|
||||
while (*link && base + size > (*link)->base) {
|
||||
const uint64_t end = uint64_t((*link)->base) + (*link)->size;
|
||||
base = (end + alignment - 1) & ~(uint64_t(alignment) - 1);
|
||||
link = &(*link)->next;
|
||||
}
|
||||
if (base + size > (uint64_t{1} << 32)) return E_OUTOFMEMORY;
|
||||
void* ptr = _aligned_malloc(size, alignment);
|
||||
if (!ptr) return E_OUTOFMEMORY;
|
||||
auto* entry = new (std::nothrow) Allocation{reinterpret_cast<uintptr_t>(ptr),
|
||||
static_cast<uint32_t>(base), size, *link};
|
||||
if (!entry) {
|
||||
_aligned_free(ptr);
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
*link = entry;
|
||||
used += size;
|
||||
if (va) *va = ptr;
|
||||
if (apu) *apu = entry->base;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI ApuFree(void* va) {
|
||||
if (va) _aligned_free(va);
|
||||
return S_OK;
|
||||
if (!va) return S_OK;
|
||||
std::lock_guard guard(heap_lock);
|
||||
for (auto** link = &allocations; *link; link = &(*link)->next) {
|
||||
auto* entry = *link;
|
||||
if (entry->va != reinterpret_cast<uintptr_t>(va)) continue;
|
||||
*link = entry->next;
|
||||
used -= entry->size;
|
||||
_aligned_free(va);
|
||||
delete entry;
|
||||
return S_OK;
|
||||
}
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
BOOL WINAPI ApuIsVirtualAddressValid(const void* va, uint32_t /*size*/) {
|
||||
return va != nullptr;
|
||||
static uint32_t lookup_va(const void* va, uint32_t size) {
|
||||
const auto address = reinterpret_cast<uintptr_t>(va);
|
||||
std::lock_guard guard(heap_lock);
|
||||
for (auto* entry = allocations; entry; entry = entry->next) {
|
||||
const auto offset = address - entry->va;
|
||||
if (offset < entry->size && size <= entry->size - offset)
|
||||
return entry->base + static_cast<uint32_t>(offset);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void* WINAPI ApuMapApuAddress(uint32_t /*apu_addr*/) {
|
||||
BX_STUB_LOG("AcpHal.dll", "ApuMapApuAddress");
|
||||
BOOL WINAPI ApuIsVirtualAddressValid(const void* va, uint32_t size) {
|
||||
return lookup_va(va, size) != 0;
|
||||
}
|
||||
|
||||
void* WINAPI ApuMapApuAddress(uint32_t address) {
|
||||
std::lock_guard guard(heap_lock);
|
||||
for (auto* entry = allocations; entry && entry->base <= address; entry = entry->next) {
|
||||
const auto offset = address - entry->base;
|
||||
if (offset < entry->size) return reinterpret_cast<void*>(entry->va + offset);
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
uint32_t WINAPI ApuMapVirtualAddress(const void* va) {
|
||||
return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(va) & 0xFFFFFFFFu);
|
||||
uint32_t WINAPI ApuMapVirtualAddress(const void* va) { return lookup_va(va, 1); }
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
+27
-14
@@ -1,21 +1,34 @@
|
||||
#include <windows.h>
|
||||
#include <cstdint>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
/* Track E (M1-E2 / M5): chad.dll Xbox DSP command shim. */
|
||||
#define BX_DSP_CONNECTIONS
|
||||
#include "command_ring.h"
|
||||
|
||||
extern "C" {
|
||||
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(uint32_t, void** out) { return connect(out); }
|
||||
HRESULT WINAPI XDspDisconnect(void* handle) { return disconnect(handle); }
|
||||
|
||||
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(uint32_t /*max_streams*/, void** out_handle) {
|
||||
BX_STUB_LOG("chad.dll", "XDspConnectWithMaximumStreamLimit");
|
||||
if (out_handle) *out_handle = reinterpret_cast<void*>(0x5001);
|
||||
HRESULT WINAPI XDspActivate(void* handle) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(handle);
|
||||
if (!c) return E_HANDLE;
|
||||
c->active = true;
|
||||
// chad has no result export. Active DSP commands complete synchronously.
|
||||
while (c->queue.count) c->queue.pop();
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XDspDisconnect(void* /*handle*/) { return S_OK; }
|
||||
HRESULT WINAPI XDspActivate(void* /*handle*/) { return S_OK; }
|
||||
HRESULT WINAPI XDspDeactivate(void* /*handle*/) { return S_OK; }
|
||||
HRESULT WINAPI XDspSubmitCommand(void* /*handle*/, const void* /*cmd*/, uint32_t /*size*/) { return S_OK; }
|
||||
HRESULT WINAPI XDspDeactivate(void* handle) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(handle);
|
||||
if (!c) return E_HANDLE;
|
||||
c->active = false;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
HRESULT WINAPI XDspSubmitCommand(void* handle, const void* cmd, uint32_t size) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(handle);
|
||||
if (!c) return E_HANDLE;
|
||||
const HRESULT hr = c->queue.push(cmd, size);
|
||||
if (SUCCEEDED(hr) && c->active) c->queue.pop();
|
||||
return hr;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
|
||||
namespace {
|
||||
// A synthetic command completes by returning its opaque bytes unchanged.
|
||||
struct CommandRing {
|
||||
struct Packet {
|
||||
uint32_t size;
|
||||
unsigned char bytes[1024];
|
||||
};
|
||||
std::array<Packet, 32> packets;
|
||||
unsigned head = 0, count = 0;
|
||||
|
||||
HRESULT push(const void* data, uint32_t size) {
|
||||
if (!data || !size || size > sizeof(Packet::bytes)) return E_INVALIDARG;
|
||||
if (count == packets.size()) return HRESULT_FROM_WIN32(ERROR_BUSY);
|
||||
auto& packet = packets[(head + count) % packets.size()];
|
||||
packet.size = size;
|
||||
std::memcpy(packet.bytes, data, size);
|
||||
++count;
|
||||
return S_OK;
|
||||
}
|
||||
void pop() {
|
||||
head = (head + 1) % packets.size();
|
||||
--count;
|
||||
}
|
||||
HRESULT read(void* data, uint32_t size) {
|
||||
if (!data) return E_POINTER;
|
||||
if (!count) return S_FALSE;
|
||||
const auto& packet = packets[head];
|
||||
if (size < packet.size) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
|
||||
std::memcpy(data, packet.bytes, packet.size);
|
||||
pop();
|
||||
return S_OK;
|
||||
}
|
||||
};
|
||||
|
||||
struct Connection {
|
||||
uintptr_t id;
|
||||
Connection* next;
|
||||
CommandRing queue;
|
||||
bool active = false;
|
||||
};
|
||||
|
||||
// Each DLL owns its registry. An ID stays invalid after disconnect, including
|
||||
// when the allocator subsequently reuses the same Connection address.
|
||||
std::mutex connections_lock;
|
||||
Connection* connections;
|
||||
#ifdef BX_DSP_CONNECTIONS
|
||||
uintptr_t next_id = 2;
|
||||
#else
|
||||
uintptr_t next_id = 1;
|
||||
#endif
|
||||
|
||||
HRESULT connect(void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
std::lock_guard guard(connections_lock);
|
||||
if (next_id > UINTPTR_MAX - 2) return E_OUTOFMEMORY;
|
||||
auto* c = new (std::nothrow) Connection;
|
||||
if (!c) return E_OUTOFMEMORY;
|
||||
c->id = next_id;
|
||||
next_id += 2;
|
||||
c->next = connections;
|
||||
connections = c;
|
||||
*out = reinterpret_cast<void*>(c->id);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
// Caller holds connections_lock through the operation.
|
||||
Connection* lookup(void* handle) {
|
||||
for (auto* c = connections; c; c = c->next)
|
||||
if (c->id == reinterpret_cast<uintptr_t>(handle)) return c;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
HRESULT disconnect(void* handle) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
for (auto** link = &connections; *link; link = &(*link)->next) {
|
||||
auto* c = *link;
|
||||
if (c->id != reinterpret_cast<uintptr_t>(handle)) continue;
|
||||
*link = c->next;
|
||||
delete c;
|
||||
return S_OK;
|
||||
}
|
||||
return E_HANDLE;
|
||||
}
|
||||
}
|
||||
+15
-23
@@ -1,32 +1,24 @@
|
||||
#include <windows.h>
|
||||
#include <cstdint>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
/* Track E (M1-E2 / M5): xapu.dll APU command queue shim. */
|
||||
#include "command_ring.h"
|
||||
|
||||
extern "C" {
|
||||
HRESULT WINAPI XApuConnect(void** out) { return connect(out); }
|
||||
HRESULT WINAPI XApuDisconnect(void* conn) { return disconnect(conn); }
|
||||
|
||||
HRESULT WINAPI XApuConnect(void** out_conn) {
|
||||
BX_STUB_LOG("xapu.dll", "XApuConnect");
|
||||
if (out_conn) *out_conn = reinterpret_cast<void*>(0x4001);
|
||||
return S_OK;
|
||||
HRESULT WINAPI XApuEnqueueCommand(void* conn, const void* cmd, uint32_t size) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(conn);
|
||||
return c ? c->queue.push(cmd, size) : E_HANDLE;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XApuDisconnect(void* /*conn*/) {
|
||||
return S_OK;
|
||||
HRESULT WINAPI XApuDequeueResult(void* conn, void* result, uint32_t size) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(conn);
|
||||
return c ? c->queue.read(result, size) : E_HANDLE;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XApuEnqueueCommand(void* /*conn*/, const void* /*cmd*/, uint32_t /*size*/) {
|
||||
return S_OK;
|
||||
uint32_t WINAPI XApuGetResultCount(void* conn) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(conn);
|
||||
return c ? c->queue.count : 0;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XApuDequeueResult(void* /*conn*/, void* /*out_res*/, uint32_t /*size*/) {
|
||||
return S_FALSE;
|
||||
}
|
||||
|
||||
uint32_t WINAPI XApuGetResultCount(void* /*conn*/) {
|
||||
return 0u;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -1,13 +1,117 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <cstdint>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
/* Track E (M1-E2): GameInput.dll ordinal 1 (GameInputCreate) shim. */
|
||||
namespace {
|
||||
// GameInputCreate @1 exposes the legacy v0 COM layout.
|
||||
constexpr GUID game_input_v0 = {0x11be2a7e, 0x4254, 0x445a,
|
||||
{0x9c, 0x09, 0xff, 0xc4, 0x0f, 0x00, 0x69, 0x18}};
|
||||
using Callback = void (WINAPI*)();
|
||||
|
||||
extern "C" HRESULT WINAPI GameInputCreate(void** out_game_input) {
|
||||
BX_STUB_LOG("GameInput.dll", "GameInputCreate@1");
|
||||
if (out_game_input) {
|
||||
*out_game_input = nullptr;
|
||||
}
|
||||
template<class T>
|
||||
HRESULT unavailable(T* out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = {};
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
class GameInput final : public IUnknown {
|
||||
LONG refs = 0;
|
||||
public:
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (iid != IID_IUnknown && iid != game_input_v0) return E_NOINTERFACE;
|
||||
AddRef();
|
||||
*out = this;
|
||||
return S_OK;
|
||||
}
|
||||
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
|
||||
ULONG WINAPI Release() override { return InterlockedDecrement(&refs); }
|
||||
|
||||
virtual uint64_t WINAPI GetCurrentTimestamp() {
|
||||
return GetTickCount64() * 1000;
|
||||
}
|
||||
virtual HRESULT WINAPI GetCurrentReading(uint32_t, void*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 4, "GetCurrentReading");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI GetNextReading(void*, uint32_t, void*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 5, "GetNextReading");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI GetPreviousReading(void*, uint32_t, void*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 6, "GetPreviousReading");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI GetTemporalReading(uint64_t, void*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 7, "GetTemporalReading");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI RegisterReadingCallback(void*, uint32_t, float, void*, Callback, uint64_t* out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 8, "RegisterReadingCallback");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI RegisterDeviceCallback(void*, uint32_t, uint32_t, uint32_t, void*, Callback, uint64_t* out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 9, "RegisterDeviceCallback");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI RegisterSystemButtonCallback(void*, uint32_t, void*, Callback, uint64_t* out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 10, "RegisterSystemButtonCallback");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI RegisterKeyboardLayoutCallback(void*, void*, Callback, uint64_t* out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 11, "RegisterKeyboardLayoutCallback");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual void WINAPI StopCallback(uint64_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 12, "StopCallback");
|
||||
}
|
||||
virtual bool WINAPI UnregisterCallback(uint64_t, uint64_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 13, "UnregisterCallback");
|
||||
return false;
|
||||
}
|
||||
virtual HRESULT WINAPI CreateDispatcher(void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 14, "CreateDispatcher");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI CreateAggregateDevice(uint32_t, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 15, "CreateAggregateDevice");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI FindDeviceFromId(const void*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 16, "FindDeviceFromId");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI FindDeviceFromObject(IUnknown*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 17, "FindDeviceFromObject");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI FindDeviceFromPlatformHandle(HANDLE, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 18, "FindDeviceFromPlatformHandle");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI FindDeviceFromPlatformString(const wchar_t*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 19, "FindDeviceFromPlatformString");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI EnableOemDeviceSupport(uint16_t, uint16_t, uint8_t, uint8_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 20, "EnableOemDeviceSupport");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual void WINAPI SetFocusPolicy(uint32_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 21, "SetFocusPolicy");
|
||||
}
|
||||
};
|
||||
|
||||
GameInput singleton;
|
||||
}
|
||||
|
||||
extern "C" HRESULT WINAPI GameInputCreate(void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
singleton.AddRef();
|
||||
*out = &singleton;
|
||||
return S_OK;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_audio_input main.cpp)
|
||||
target_link_libraries(test_audio_input PRIVATE acphal xapu chad kernel32)
|
||||
add_dependencies(test_audio_input gameinput)
|
||||
@@ -0,0 +1,132 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <thread>
|
||||
|
||||
extern "C" {
|
||||
HRESULT WINAPI AcpHalCreate(void**);
|
||||
HRESULT WINAPI ApuCreateHeap(uint32_t, uint32_t);
|
||||
HRESULT WINAPI ApuAlloc(void**, uint32_t*, uint32_t, uint32_t);
|
||||
HRESULT WINAPI ApuFree(void*);
|
||||
BOOL WINAPI ApuIsVirtualAddressValid(const void*, uint32_t);
|
||||
void* WINAPI ApuMapApuAddress(uint32_t);
|
||||
uint32_t WINAPI ApuMapVirtualAddress(const void*);
|
||||
HRESULT WINAPI XApuConnect(void**);
|
||||
HRESULT WINAPI XApuDisconnect(void*);
|
||||
HRESULT WINAPI XApuEnqueueCommand(void*, const void*, uint32_t);
|
||||
HRESULT WINAPI XApuDequeueResult(void*, void*, uint32_t);
|
||||
uint32_t WINAPI XApuGetResultCount(void*);
|
||||
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(uint32_t, void**);
|
||||
HRESULT WINAPI XDspActivate(void*);
|
||||
HRESULT WINAPI XDspDeactivate(void*);
|
||||
HRESULT WINAPI XDspSubmitCommand(void*, const void*, uint32_t);
|
||||
HRESULT WINAPI XDspDisconnect(void*);
|
||||
}
|
||||
|
||||
#define CHECK(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0)
|
||||
|
||||
int main() {
|
||||
void* object = nullptr;
|
||||
CHECK(AcpHalCreate(&object) == S_OK && object);
|
||||
auto* hal = static_cast<IUnknown*>(object);
|
||||
CHECK(hal->QueryInterface(IID_IUnknown, &object) == S_OK && object == hal);
|
||||
CHECK(hal->Release() == 1);
|
||||
CHECK(ApuCreateHeap(64, 64) == S_OK);
|
||||
void *va = nullptr, *second = nullptr;
|
||||
uint32_t base = 0, other = 0;
|
||||
CHECK(ApuAlloc(&va, &base, 64, 256) == S_OK && va && base);
|
||||
CHECK(reinterpret_cast<uintptr_t>(va) % 256 == 0 && base % 256 == 0);
|
||||
CHECK(ApuAlloc(&second, &other, 64, 64) == S_OK && other != base);
|
||||
CHECK(ApuCreateHeap(0, 0) == HRESULT_FROM_WIN32(ERROR_BUSY));
|
||||
void* excess = nullptr;
|
||||
CHECK(ApuAlloc(&excess, nullptr, 1, 64) == E_OUTOFMEMORY);
|
||||
auto* tail = static_cast<unsigned char*>(va) + 63;
|
||||
CHECK(ApuMapApuAddress(base + 63) == tail && ApuMapVirtualAddress(tail) == base + 63);
|
||||
CHECK(ApuIsVirtualAddressValid(tail, 1) && !ApuIsVirtualAddressValid(tail, 2));
|
||||
CHECK(ApuFree(tail) == E_INVALIDARG);
|
||||
CHECK(ApuFree(va) == S_OK && !ApuMapApuAddress(base) && !ApuMapVirtualAddress(va));
|
||||
CHECK(ApuFree(va) == E_INVALIDARG && ApuMapApuAddress(other) == second);
|
||||
CHECK(ApuFree(second) == S_OK && hal->Release() == 0);
|
||||
|
||||
void *apu = nullptr, *peer = nullptr, *dsp = nullptr;
|
||||
CHECK(XApuConnect(&apu) == S_OK && XApuConnect(&peer) == S_OK && peer != apu);
|
||||
unsigned result = 0;
|
||||
CHECK(XApuDequeueResult(apu, &result, sizeof(result)) == S_FALSE);
|
||||
for (unsigned cycle = 0; cycle < 3; ++cycle) {
|
||||
HRESULT status = S_OK;
|
||||
unsigned accepted = 0;
|
||||
std::thread producer([&] {
|
||||
for (; accepted < 1024; ++accepted) {
|
||||
unsigned command = cycle * 1024 + accepted;
|
||||
status = XApuEnqueueCommand(apu, &command, sizeof(command));
|
||||
if (status != S_OK) break;
|
||||
}
|
||||
});
|
||||
producer.join();
|
||||
CHECK(accepted && status == HRESULT_FROM_WIN32(ERROR_BUSY));
|
||||
CHECK(XApuGetResultCount(apu) == accepted && XApuGetResultCount(peer) == 0);
|
||||
CHECK(XApuDequeueResult(apu, &result, 1) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER));
|
||||
for (unsigned i = 0; i < accepted; ++i) {
|
||||
CHECK(XApuDequeueResult(apu, &result, sizeof(result)) == S_OK);
|
||||
CHECK(result == cycle * 1024 + i);
|
||||
}
|
||||
CHECK(XApuGetResultCount(apu) == 0);
|
||||
}
|
||||
// A stalled peer must fail this test rather than wait forever.
|
||||
constexpr unsigned messages = 4096;
|
||||
const auto deadline = GetTickCount64() + 10000;
|
||||
std::atomic<bool> failed{false};
|
||||
std::thread worker([&] {
|
||||
for (unsigned i = 0; i < messages && !failed;) {
|
||||
const auto hr = XApuEnqueueCommand(apu, &i, sizeof(i));
|
||||
if (hr == S_OK) ++i;
|
||||
else if (hr != HRESULT_FROM_WIN32(ERROR_BUSY) || GetTickCount64() >= deadline)
|
||||
failed = true;
|
||||
else std::this_thread::yield();
|
||||
}
|
||||
});
|
||||
for (unsigned i = 0; i < messages && !failed;) {
|
||||
const auto hr = XApuDequeueResult(apu, &result, sizeof(result));
|
||||
if (hr == S_OK && result == i) ++i;
|
||||
else if (hr != S_FALSE || GetTickCount64() >= deadline) failed = true;
|
||||
else std::this_thread::yield();
|
||||
}
|
||||
worker.join();
|
||||
CHECK(!failed && XApuGetResultCount(apu) == 0);
|
||||
CHECK(XApuDisconnect(apu) == S_OK && XApuDisconnect(peer) == S_OK);
|
||||
CHECK(XApuEnqueueCommand(apu, &result, sizeof(result)) == E_HANDLE);
|
||||
|
||||
CHECK(XDspConnectWithMaximumStreamLimit(2, &dsp) == S_OK);
|
||||
for (unsigned cycle = 0; cycle < 2; ++cycle) {
|
||||
unsigned queued = 0;
|
||||
HRESULT hr = S_OK;
|
||||
while (queued < 1024 && (hr = XDspSubmitCommand(dsp, &result, sizeof(result))) == S_OK)
|
||||
++queued;
|
||||
CHECK(queued && hr == HRESULT_FROM_WIN32(ERROR_BUSY));
|
||||
CHECK(XDspActivate(dsp) == S_OK);
|
||||
for (unsigned i = 0; i <= queued; ++i)
|
||||
CHECK(XDspSubmitCommand(dsp, &result, sizeof(result)) == S_OK);
|
||||
CHECK(XDspDeactivate(dsp) == S_OK);
|
||||
}
|
||||
CHECK(XDspDisconnect(dsp) == S_OK && XDspActivate(dsp) == E_HANDLE);
|
||||
|
||||
HMODULE dll = LoadLibraryW(L"GameInput.dll");
|
||||
CHECK(dll);
|
||||
auto proc = GetProcAddress(dll, MAKEINTRESOURCEA(1));
|
||||
CHECK(proc && proc == GetProcAddress(dll, "GameInputCreate"));
|
||||
using Factory = HRESULT (WINAPI*)(void**);
|
||||
auto create = reinterpret_cast<Factory>(reinterpret_cast<void*>(proc));
|
||||
CHECK(create(&object) == S_OK && object);
|
||||
auto* input = static_cast<IUnknown*>(object);
|
||||
CHECK(create(&object) == S_OK && object == input && input->Release() == 1);
|
||||
CHECK(input->QueryInterface(IID_IUnknown, &object) == S_OK && object == input);
|
||||
CHECK(input->Release() == 1);
|
||||
auto** table = *reinterpret_cast<void***>(input);
|
||||
using Reading = HRESULT (WINAPI*)(IUnknown*, uint32_t, void*, void**);
|
||||
CHECK(reinterpret_cast<Reading>(table[4])(input, 0, nullptr, &object) == E_NOTIMPL && !object);
|
||||
CHECK(input->Release() == 0);
|
||||
FreeLibrary(dll);
|
||||
std::puts("PASS: audio mappings, APU and DSP queues, GameInput ordinal 1");
|
||||
}
|
||||
Reference in new issue
Block a user