Compare commits

..
Author SHA1 Message Date
ates 829a94fa2f bx-cli: print clwb VEH traps : 0 when no CLWB records exist
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:47:28 +03:00
ates a8c4dbb77e Report sampled CLWB bounds and guest crashes in bx-cli trace
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:08:33 +03:00
10 changed files with 200 additions and 526 deletions

No files matched your search

+1 -1
View File
@@ -10,7 +10,6 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- Implemented synthetic APU heap mappings, per-connection APU and DSP queues, and the GameInput ordinal 1 COM stub. Added an audio/input conformance executable covering all four shim DLLs (#419).
- Added structured unhandled exception logging with module-relative addresses and x64 registers, and expanded the CLWB conformance test to require six traps across ModRM, SIB, REX and RIP-relative operands (#409).
- Enforced the configured title memory cap for default heap allocations and virtual commits in `xmem.dll`. Added working-set accounting and a synthetic fixture for alignment, commit overlap, decommit, release, and memory transfer (#411).
- Added a BetterXen-only DirectStorage conformance interface for asynchronous uncompressed file and memory transfers, status arrays, and completion events in `XCRDAPI.dll` (#413).
@@ -69,6 +68,7 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Fixed
- `bx-cli trace` reports the highest sampled CLWB total as a lower bound, labels counterless CLWB records as samples, and lists unhandled exceptions with their code, module base, RVA, and RIP (#438).
- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed.
- Startup reports now reject existing destinations before guest execution, surface journal write failures, and preserve late errors alongside signal termination.
- Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command.
+39 -1
View File
@@ -153,6 +153,16 @@ fn cmd_probe(path: &str) -> ExitCode {
ExitCode::SUCCESS
}
fn format_clwb_line(clwb_events: usize, clwb_trap_lower_bound: Option<u64>) -> String {
if let Some(lower_bound) = clwb_trap_lower_bound {
format!("clwb VEH traps : at least {lower_bound} (sampled)")
} else if clwb_events == 0 {
"clwb VEH traps : 0".to_string()
} else {
format!("clwb VEH samples : {clwb_events}")
}
}
fn cmd_trace(path: &str) -> ExitCode {
let text = match fs::read_to_string(path) {
Ok(s) => s,
@@ -163,8 +173,26 @@ fn cmd_trace(path: &str) -> ExitCode {
};
let summary = summarize_jsonl(&text);
println!("Trace events : {}", summary.total_lines);
println!("clwb VEH traps : {}", summary.clwb_events);
println!(
"{}",
format_clwb_line(summary.clwb_events, summary.clwb_trap_lower_bound)
);
println!("ADX illegal ops : {}", summary.adx_errors);
if !summary.unhandled_exceptions.is_empty() {
println!(
"\nUnhandled exceptions ({}):",
summary.unhandled_exceptions.len()
);
for crash in summary.unhandled_exceptions {
println!(
" code={} module_base={} + RVA={} RIP={}",
crash.exception_code.as_deref().unwrap_or("unknown"),
crash.module_base.as_deref().unwrap_or("unknown"),
crash.rva.as_deref().unwrap_or("unknown"),
crash.rip.as_deref().unwrap_or("unknown"),
);
}
}
if !summary.unimpl_apis.is_empty() {
println!("\nUnimplemented APIs:");
for (api, count) in summary.unimpl_apis {
@@ -414,4 +442,14 @@ mod tests {
"Z:\\tmp\\bx-test.jsonl"
);
}
#[test]
fn formats_clwb_summary_lines() {
assert_eq!(format_clwb_line(0, None), "clwb VEH traps : 0");
assert_eq!(format_clwb_line(2, None), "clwb VEH samples : 2");
assert_eq!(
format_clwb_line(3, Some(4)),
"clwb VEH traps : at least 4 (sampled)"
);
}
}
+93 -3
View File
@@ -1,20 +1,32 @@
//! Track A / F: Structured JSONL shim trace aggregator.
//!
//! Summarizes `bx_runtime_veh.dll` logs (stub API calls, unimplemented COM vtable
//! slots, `clwb` traps, and ADX illegal-instruction tripwires) so tracks can prioritize
//! the exact next blocking API.
//! slots, `clwb` traps, ADX illegal-instruction tripwires, and unhandled exceptions)
//! so tracks can identify guest failures and missing APIs.
use std::collections::BTreeMap;
#[derive(Debug, Default, PartialEq, Eq)]
pub struct TraceSummary {
pub total_lines: usize,
/// Number of `clwb_trapped` records in the log.
pub clwb_events: usize,
/// Highest cumulative counter in the sampled CLWB records, if available.
pub clwb_trap_lower_bound: Option<u64>,
pub adx_errors: usize,
pub unhandled_exceptions: Vec<UnhandledException>,
pub unimpl_apis: BTreeMap<String, usize>,
pub unimpl_vtables: BTreeMap<String, usize>,
}
#[derive(Debug, PartialEq, Eq)]
pub struct UnhandledException {
pub exception_code: Option<String>,
pub module_base: Option<String>,
pub rva: Option<String>,
pub rip: Option<String>,
}
fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
let needle = format!("\"{key}\":\"");
let start = line.find(&needle)? + needle.len();
@@ -34,8 +46,23 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
let event = extract_json_str(trimmed, "event").unwrap_or("");
let detail = extract_json_str(trimmed, "detail").unwrap_or("");
match event {
"clwb_trapped" => summary.clwb_events += 1,
"clwb_trapped" => {
summary.clwb_events += 1;
let sample = detail
.split_ascii_whitespace()
.find_map(|field| field.strip_prefix("total_traps="))
.and_then(|count| count.parse::<u64>().ok());
summary.clwb_trap_lower_bound = summary.clwb_trap_lower_bound.max(sample);
}
"adx_illegal_instruction" => summary.adx_errors += 1,
"unhandled_exception" => {
summary.unhandled_exceptions.push(UnhandledException {
exception_code: extract_json_str(trimmed, "exception_code").map(str::to_owned),
module_base: extract_json_str(trimmed, "module_base").map(str::to_owned),
rva: extract_json_str(trimmed, "rva").map(str::to_owned),
rip: extract_json_str(trimmed, "rip").map(str::to_owned),
});
}
"unimpl_api" => *summary.unimpl_apis.entry(detail.to_string()).or_insert(0) += 1,
"unimpl_vtable" => {
*summary
@@ -64,7 +91,9 @@ mod tests {
let s = summarize_jsonl(sample);
assert_eq!(s.total_lines, 4);
assert_eq!(s.clwb_events, 1);
assert_eq!(s.clwb_trap_lower_bound, Some(1));
assert_eq!(s.adx_errors, 0);
assert!(s.unhandled_exceptions.is_empty());
assert_eq!(
s.unimpl_apis.get("d3d12_xs.dll!D3D12XboxCreateDevice"),
Some(&2)
@@ -75,4 +104,65 @@ mod tests {
Some(&1)
);
}
#[test]
fn uses_highest_counter_from_sampled_clwb_records() {
for (actual_traps, records, expected_bound) in [
(1, &[1][..], 1),
(6, &[1, 4, 2], 4),
(100, &[1, 2, 4, 8, 16, 32, 64], 64),
] {
let mut log = String::new();
for counter in records {
log.push_str(&format!(
"{{\"event\":\"clwb_trapped\",\"detail\":\"rip=0x1000 len=4 total_traps={counter}\"}}\n"
));
}
let summary = summarize_jsonl(&log);
assert_eq!(summary.clwb_events, records.len(), "{actual_traps} traps");
assert_eq!(
summary.clwb_trap_lower_bound,
Some(expected_bound),
"{actual_traps} traps"
);
}
}
#[test]
fn preserves_clwb_record_count_without_valid_counters() {
let summary = summarize_jsonl(
r#"{"event":"clwb_trapped","detail":"rip=0x1000 len=4"}
{"event":"clwb_trapped","detail":"rip=0x1000 len=4 total_traps=invalid"}
{"event":"unimpl_api","detail":"total_traps=100"}"#,
);
assert_eq!(summary.clwb_events, 2);
assert_eq!(summary.clwb_trap_lower_bound, None);
}
#[test]
fn collects_unhandled_exceptions_in_log_order() {
let log = r#"
{"ts_ms":16,"tid":1,"level":"ERROR","sub":"runtime_veh","event":"unhandled_exception","exception_code":"0xc0000005","module_base":"0x0000000140000000","rva":"0x0000000000001234","rip":"0x0000000140001234","rsp":"0x000000000021fd80","registers":{"rax":"0x0123456789abcdef","rbx":"0x0000000000000000","rcx":"0x0000000000000000","rdx":"0x0000000000000000","rsi":"0x0000000000000000","rdi":"0x0000000000000000","rbp":"0x0000000000000000","r8":"0x0000000000000000","r9":"0x0000000000000000","r10":"0x0000000000000000","r11":"0x0000000000000000","r12":"0x0000000000000000","r13":"0x0000000000000000","r14":"0x0000000000000000","r15":"0x0000000000000000"}}
{"ts_ms":20,"tid":1,"level":"ERROR","sub":"runtime_veh","event":"unhandled_exception","exception_code":"0xc000001d","module_base":"0x0000000000000000","rva":"0x0000000000000000","rip":"0x0000000000410000","rsp":"0x000000000021fd80","registers":{}}
"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.total_lines, 2);
assert_eq!(
summary.unhandled_exceptions,
[
UnhandledException {
exception_code: Some("0xc0000005".into()),
module_base: Some("0x0000000140000000".into()),
rva: Some("0x0000000000001234".into()),
rip: Some("0x0000000140001234".into()),
},
UnhandledException {
exception_code: Some("0xc000001d".into()),
module_base: Some("0x0000000000000000".into()),
rva: Some("0x0000000000000000".into()),
rip: Some("0x0000000000410000".into()),
},
]
);
}
}
+24 -108
View File
@@ -1,53 +1,20 @@
#include <windows.h>
#include <unknwn.h>
#include <cstdint>
#include <mutex>
#include <new>
#include <cstdlib>
#include "bx_log.h"
namespace {
class AcpHal final : public IUnknown {
LONG refs = 1;
public:
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (iid != IID_IUnknown) return E_NOINTERFACE;
AddRef();
*out = this;
return S_OK;
}
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
ULONG WINAPI Release() override {
ULONG left = InterlockedDecrement(&refs);
if (!left) delete this;
return left;
}
};
// Sorted synthetic address ranges. Zero is reserved for failed lookups.
struct Allocation {
uintptr_t va;
uint32_t base, size;
Allocation* next;
};
Allocation* allocations;
std::mutex heap_lock;
uint64_t capacity = 0;
uint64_t used = 0;
bool heap_created = false;
}
/* Track E (M1-E2 / M5): AcpHal.dll SHAPE Audio Coprocessor HAL shim. */
extern "C" {
HRESULT WINAPI AcpHalCreate(void** out) {
if (!out) return E_POINTER;
*out = new (std::nothrow) AcpHal;
return *out ? S_OK : E_OUTOFMEMORY;
HRESULT WINAPI AcpHalCreate(void** out_hal) {
BX_STUB_LOG("AcpHal.dll", "AcpHalCreate");
if (out_hal) *out_hal = nullptr;
return E_NOTIMPL;
}
HRESULT WINAPI AcpHalAllocateShapeContexts(void*) {
HRESULT WINAPI AcpHalAllocateShapeContexts(void* /*desc*/) {
BX_STUB_LOG("AcpHal.dll", "AcpHalAllocateShapeContexts");
return S_OK;
}
@@ -57,86 +24,35 @@ HRESULT WINAPI AcpHalReleaseShapeContexts(void) {
return S_OK;
}
HRESULT WINAPI ApuCreateHeap(uint32_t cached, uint32_t non_cached) {
std::lock_guard guard(heap_lock);
if (allocations) return HRESULT_FROM_WIN32(ERROR_BUSY);
// Invariant: allocations == nullptr implies used == 0; reset explicitly.
used = 0;
capacity = uint64_t(cached) + non_cached;
heap_created = true;
HRESULT WINAPI ApuCreateHeap(uint32_t /*cached_size*/, uint32_t /*non_cached_size*/) {
BX_STUB_LOG("AcpHal.dll", "ApuCreateHeap");
return S_OK;
}
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;
HRESULT WINAPI ApuAlloc(void** out_va, uint32_t* out_apu_addr, uint32_t size, uint32_t alignment) {
if (alignment < 64) alignment = 64;
if (!size) size = 64;
std::lock_guard guard(heap_lock);
if (!heap_created || size > capacity - used) return E_OUTOFMEMORY;
uint64_t base = alignment;
Allocation** link = &allocations;
while (*link && base + size > (*link)->base) {
const uint64_t end = uint64_t((*link)->base) + (*link)->size;
base = (end + alignment - 1) & ~(uint64_t(alignment) - 1);
link = &(*link)->next;
}
if (base + size > (uint64_t{1} << 32)) return E_OUTOFMEMORY;
void* ptr = _aligned_malloc(size, alignment);
if (!ptr) return E_OUTOFMEMORY;
auto* entry = new (std::nothrow) Allocation{reinterpret_cast<uintptr_t>(ptr),
static_cast<uint32_t>(base), size, *link};
if (!entry) {
_aligned_free(ptr);
return E_OUTOFMEMORY;
}
*link = entry;
used += size;
if (va) *va = ptr;
if (apu) *apu = entry->base;
return S_OK;
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;
}
HRESULT WINAPI ApuFree(void* va) {
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;
if (va) _aligned_free(va);
return S_OK;
}
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;
BOOL WINAPI ApuIsVirtualAddressValid(const void* va, uint32_t /*size*/) {
return va != nullptr;
}
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);
}
void* WINAPI ApuMapApuAddress(uint32_t /*apu_addr*/) {
BX_STUB_LOG("AcpHal.dll", "ApuMapApuAddress");
return nullptr;
}
uint32_t WINAPI ApuMapVirtualAddress(const void* va) { return lookup_va(va, 1); }
uint32_t WINAPI ApuMapVirtualAddress(const void* va) {
return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(va) & 0xFFFFFFFFu);
}
} // extern "C"
+14 -34
View File
@@ -1,41 +1,21 @@
#define BX_DSP_CONNECTIONS
#include "command_ring.h"
#include <windows.h>
#include <cstdint>
#include "bx_log.h"
/* Track E (M1-E2 / M5): chad.dll Xbox DSP command shim. */
extern "C" {
// Validate and record the caller's stream limit; the synthetic command ring
// holds a fixed 32-packet backlog independent of stream count.
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(uint32_t max_streams, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!max_streams) return E_INVALIDARG;
return connect(out, max_streams);
}
HRESULT WINAPI XDspDisconnect(void* handle) { return disconnect(handle); }
HRESULT WINAPI 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();
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);
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;
}
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 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;
}
}
} // extern "C"
-96
View File
@@ -1,96 +0,0 @@
#pragma once
#include <windows.h>
#include <array>
#include <cstdint>
#include <cstring>
#include <mutex>
#include <new>
namespace {
// A synthetic command completes by returning its opaque bytes unchanged.
struct CommandRing {
struct Packet {
uint32_t size;
unsigned char bytes[1024];
};
std::array<Packet, 32> packets;
unsigned head = 0, count = 0;
HRESULT push(const void* data, uint32_t size) {
if (!data || !size || size > sizeof(Packet::bytes)) return E_INVALIDARG;
if (count == packets.size()) return HRESULT_FROM_WIN32(ERROR_BUSY);
auto& packet = packets[(head + count) % packets.size()];
packet.size = size;
std::memcpy(packet.bytes, data, size);
++count;
return S_OK;
}
void pop() {
head = (head + 1) % packets.size();
--count;
}
HRESULT read(void* data, uint32_t size) {
if (!data) return E_POINTER;
if (!count) return S_FALSE;
const auto& packet = packets[head];
if (size < packet.size) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
std::memcpy(data, packet.bytes, packet.size);
pop();
return S_OK;
}
};
struct Connection {
uintptr_t id;
Connection* next;
CommandRing queue;
uint32_t max_streams = 0;
bool active = false;
};
// Each DLL owns its registry. An ID stays invalid after disconnect, including
// when the allocator subsequently reuses the same Connection address.
std::mutex connections_lock;
Connection* connections;
#ifdef BX_DSP_CONNECTIONS
uintptr_t next_id = 2;
#else
uintptr_t next_id = 1;
#endif
HRESULT connect(void** out, uint32_t max_streams = 0) {
if (!out) return E_POINTER;
*out = nullptr;
std::lock_guard guard(connections_lock);
if (next_id > UINTPTR_MAX - 2) return E_OUTOFMEMORY;
auto* c = new (std::nothrow) Connection;
if (!c) return E_OUTOFMEMORY;
c->id = next_id;
c->max_streams = max_streams;
next_id += 2;
c->next = connections;
connections = c;
*out = reinterpret_cast<void*>(c->id);
return S_OK;
}
// Caller holds connections_lock through the operation.
Connection* lookup(void* handle) {
for (auto* c = connections; c; c = c->next)
if (c->id == reinterpret_cast<uintptr_t>(handle)) return c;
return nullptr;
}
HRESULT disconnect(void* handle) {
std::lock_guard guard(connections_lock);
for (auto** link = &connections; *link; link = &(*link)->next) {
auto* c = *link;
if (c->id != reinterpret_cast<uintptr_t>(handle)) continue;
*link = c->next;
delete c;
return S_OK;
}
return E_HANDLE;
}
}
+23 -15
View File
@@ -1,24 +1,32 @@
#include "command_ring.h"
#include <windows.h>
#include <cstdint>
#include "bx_log.h"
/* Track E (M1-E2 / M5): xapu.dll APU command queue shim. */
extern "C" {
HRESULT WINAPI XApuConnect(void** out) { return connect(out); }
HRESULT WINAPI XApuDisconnect(void* conn) { return disconnect(conn); }
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 XApuConnect(void** out_conn) {
BX_STUB_LOG("xapu.dll", "XApuConnect");
if (out_conn) *out_conn = reinterpret_cast<void*>(0x4001);
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 XApuDisconnect(void* /*conn*/) {
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 XApuEnqueueCommand(void* /*conn*/, const void* /*cmd*/, uint32_t /*size*/) {
return S_OK;
}
HRESULT WINAPI XApuDequeueResult(void* /*conn*/, void* /*out_res*/, uint32_t /*size*/) {
return S_FALSE;
}
uint32_t WINAPI XApuGetResultCount(void* /*conn*/) {
return 0u;
}
} // extern "C"
+6 -110
View File
@@ -1,117 +1,13 @@
#include <windows.h>
#include <unknwn.h>
#include <cstdint>
#include "bx_log.h"
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*)();
/* Track E (M1-E2): GameInput.dll ordinal 1 (GameInputCreate) shim. */
template<class T>
HRESULT unavailable(T* out) {
if (!out) return E_POINTER;
*out = {};
extern "C" HRESULT WINAPI GameInputCreate(void** out_game_input) {
BX_STUB_LOG("GameInput.dll", "GameInputCreate@1");
if (out_game_input) {
*out_game_input = nullptr;
}
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;
}
@@ -1,3 +0,0 @@
add_executable(test_audio_input main.cpp)
target_link_libraries(test_audio_input PRIVATE acphal xapu chad kernel32)
add_dependencies(test_audio_input gameinput)
-155
View File
@@ -1,155 +0,0 @@
#include <windows.h>
#include <unknwn.h>
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <thread>
extern "C" {
HRESULT WINAPI AcpHalCreate(void**);
HRESULT WINAPI ApuCreateHeap(uint32_t, uint32_t);
HRESULT WINAPI ApuAlloc(void**, uint32_t*, uint32_t, uint32_t);
HRESULT WINAPI ApuFree(void*);
BOOL WINAPI ApuIsVirtualAddressValid(const void*, uint32_t);
void* WINAPI ApuMapApuAddress(uint32_t);
uint32_t WINAPI ApuMapVirtualAddress(const void*);
HRESULT WINAPI XApuConnect(void**);
HRESULT WINAPI XApuDisconnect(void*);
HRESULT WINAPI XApuEnqueueCommand(void*, const void*, uint32_t);
HRESULT WINAPI XApuDequeueResult(void*, void*, uint32_t);
uint32_t WINAPI XApuGetResultCount(void*);
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(uint32_t, void**);
HRESULT WINAPI XDspActivate(void*);
HRESULT WINAPI XDspDeactivate(void*);
HRESULT WINAPI XDspSubmitCommand(void*, const void*, uint32_t);
HRESULT WINAPI XDspDisconnect(void*);
}
#define CHECK(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0)
int main() {
void* object = nullptr;
CHECK(AcpHalCreate(&object) == S_OK && object);
auto* hal = static_cast<IUnknown*>(object);
CHECK(hal->QueryInterface(IID_IUnknown, &object) == S_OK && object == hal);
CHECK(hal->Release() == 1);
void *va = nullptr, *second = nullptr;
uint32_t base = 0, other = 0;
CHECK(ApuAlloc(&va, &base, 64, 64) == E_OUTOFMEMORY && !va && !base);
CHECK(ApuCreateHeap(64, 64) == S_OK);
CHECK(ApuAlloc(&va, nullptr, 64, 64) == S_OK && va);
CHECK(ApuFree(va) == S_OK);
va = nullptr;
CHECK(ApuAlloc(nullptr, &base, 64, 64) == S_OK && base);
va = ApuMapApuAddress(base);
CHECK(va && ApuFree(va) == S_OK);
va = nullptr;
base = 0;
CHECK(ApuAlloc(&va, &base, 64, 256) == S_OK && va && base);
CHECK(reinterpret_cast<uintptr_t>(va) % 256 == 0 && base % 256 == 0);
CHECK(ApuAlloc(&second, &other, 64, 64) == S_OK && other != base);
CHECK(ApuCreateHeap(0, 0) == HRESULT_FROM_WIN32(ERROR_BUSY));
void* excess = nullptr;
CHECK(ApuAlloc(&excess, nullptr, 1, 64) == E_OUTOFMEMORY);
auto* tail = static_cast<unsigned char*>(va) + 63;
CHECK(ApuMapApuAddress(base + 63) == tail && ApuMapVirtualAddress(tail) == base + 63);
CHECK(ApuIsVirtualAddressValid(tail, 1) && !ApuIsVirtualAddressValid(tail, 2));
CHECK(ApuFree(tail) == E_INVALIDARG);
CHECK(ApuFree(va) == S_OK && !ApuMapApuAddress(base) && !ApuMapVirtualAddress(va));
CHECK(ApuFree(va) == E_INVALIDARG && ApuMapApuAddress(other) == second);
CHECK(ApuFree(second) == S_OK && hal->Release() == 0);
void *apu = nullptr, *peer = nullptr, *dsp = nullptr;
CHECK(XApuConnect(&apu) == S_OK && XApuConnect(&peer) == S_OK && peer != apu);
unsigned result = 0;
CHECK(XApuDequeueResult(apu, &result, sizeof(result)) == S_FALSE);
for (unsigned cycle = 0; cycle < 3; ++cycle) {
HRESULT status = S_OK;
unsigned accepted = 0;
std::thread producer([&] {
for (; accepted < 1024; ++accepted) {
unsigned command = cycle * 1024 + accepted;
status = XApuEnqueueCommand(apu, &command, sizeof(command));
if (status != S_OK) break;
}
});
producer.join();
CHECK(accepted && status == HRESULT_FROM_WIN32(ERROR_BUSY));
CHECK(XApuGetResultCount(apu) == accepted && XApuGetResultCount(peer) == 0);
CHECK(XApuDequeueResult(apu, &result, 1) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER));
for (unsigned i = 0; i < accepted; ++i) {
CHECK(XApuDequeueResult(apu, &result, sizeof(result)) == S_OK);
CHECK(result == cycle * 1024 + i);
}
CHECK(XApuGetResultCount(apu) == 0);
}
// A stalled peer must fail this test rather than wait forever.
constexpr unsigned messages = 4096;
const auto deadline = GetTickCount64() + 10000;
std::atomic<bool> failed{false};
std::thread worker([&] {
for (unsigned i = 0; i < messages && !failed;) {
const auto hr = XApuEnqueueCommand(apu, &i, sizeof(i));
if (hr == S_OK) ++i;
else if (hr != HRESULT_FROM_WIN32(ERROR_BUSY) || GetTickCount64() >= deadline)
failed = true;
else std::this_thread::yield();
}
});
for (unsigned i = 0; i < messages && !failed;) {
const auto hr = XApuDequeueResult(apu, &result, sizeof(result));
if (hr == S_OK && result == i) ++i;
else if (hr != S_FALSE || GetTickCount64() >= deadline) failed = true;
else std::this_thread::yield();
}
worker.join();
CHECK(!failed && XApuGetResultCount(apu) == 0);
CHECK(XApuDisconnect(apu) == S_OK && XApuDisconnect(peer) == S_OK);
CHECK(XApuEnqueueCommand(apu, &result, sizeof(result)) == E_HANDLE);
CHECK(XDspConnectWithMaximumStreamLimit(0, &dsp) == E_INVALIDARG && !dsp);
CHECK(XDspConnectWithMaximumStreamLimit(2, &dsp) == S_OK && dsp);
for (unsigned cycle = 0; cycle < 2; ++cycle) {
unsigned queued = 0;
HRESULT hr = S_OK;
while (queued < 1024 && (hr = XDspSubmitCommand(dsp, &result, sizeof(result))) == S_OK)
++queued;
CHECK(queued && hr == HRESULT_FROM_WIN32(ERROR_BUSY));
CHECK(XDspActivate(dsp) == S_OK);
for (unsigned i = 0; i <= queued; ++i)
CHECK(XDspSubmitCommand(dsp, &result, sizeof(result)) == S_OK);
CHECK(XDspDeactivate(dsp) == S_OK);
}
CHECK(XDspDisconnect(dsp) == S_OK && XDspActivate(dsp) == E_HANDLE);
HMODULE dll = LoadLibraryW(L"GameInput.dll");
CHECK(dll);
auto proc = GetProcAddress(dll, MAKEINTRESOURCEA(1));
CHECK(proc && proc == GetProcAddress(dll, "GameInputCreate"));
using Factory = HRESULT (WINAPI*)(void**);
auto create = reinterpret_cast<Factory>(reinterpret_cast<void*>(proc));
CHECK(create(&object) == S_OK && object);
auto* input = static_cast<IUnknown*>(object);
CHECK(create(&object) == S_OK && object == input && input->Release() == 1);
CHECK(input->QueryInterface(IID_IUnknown, &object) == S_OK && object == input);
CHECK(input->Release() == 1);
constexpr GUID kGameInputV0 = {0x11be2a7e, 0x4254, 0x445a,
{0x9c, 0x09, 0xff, 0xc4, 0x0f, 0x00, 0x69, 0x18}};
constexpr GUID kUnknownIid = {0x00000001, 0x0002, 0x0003,
{0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b}};
void* unknown = reinterpret_cast<void*>(uintptr_t{1});
CHECK(input->QueryInterface(kUnknownIid, &unknown) == E_NOINTERFACE && !unknown);
void* v0_obj = nullptr;
CHECK(input->QueryInterface(kGameInputV0, &v0_obj) == S_OK && v0_obj == input);
auto* v0 = static_cast<IUnknown*>(v0_obj);
auto** table = *reinterpret_cast<void***>(v0);
using Timestamp = uint64_t (WINAPI*)(IUnknown*);
CHECK(reinterpret_cast<Timestamp>(table[3])(v0) > 0);
using Reading = HRESULT (WINAPI*)(IUnknown*, uint32_t, void*, void**);
void* reading = reinterpret_cast<void*>(uintptr_t{1});
CHECK(reinterpret_cast<Reading>(table[4])(v0, 0, nullptr, &reading) == E_NOTIMPL && !reading);
CHECK(v0->Release() == 1);
CHECK(input->Release() == 0);
FreeLibrary(dll);
std::puts("PASS: audio mappings, APU and DSP queues, GameInput ordinal 1");
}