Run Minecraft: runtime HLE, D3D12.X device on the host GPU, shader IR
Loader: map title-shipped DLLs, patch static TLS loads to slot 0, crash reporter, title paths for GetModuleFileName*. HLE: task queue and async, XUser (one offline user), system ids, title id, features, invites, game events, persistent local storage, GameInput with no devices, xmem, console audio hardware queues, life cycle (close suspends, then terminates), and a file layer with virtual drives rewritten in path-taking imports. GPU: D3D12.X device, DXGI chain, heaps, resources, fences, queues and command lists translated onto a host D3D12 device; clears, barriers, copies, resolves and PresentX into the title's window. Shaders: SGD5 reader and `victory translate`; SSA IR with node splitting for irreducible flow; structurisation removing EXEC. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
12caefe804
commit
754619f30e
61 files changed
+12775
-88
No files matched your search
@@ -0,0 +1,551 @@
|
||||
//! The console's audio hardware (`AcpHal.dll`, `xapu.dll`), enough for
|
||||
//! middleware to start and then mix in software:
|
||||
//!
|
||||
//! * the APU heap: host memory with 32-bit device addresses;
|
||||
//! * SHAPE context arrays allocated from it;
|
||||
//! * the audio coprocessor's command and message queues, where every
|
||||
//! command completes at once and is acknowledged as the hardware would;
|
||||
//! * the APU decoder's connections, which accept no work.
|
||||
//!
|
||||
//! What the hardware computes (XMA decoding, hardware rate conversion, EQ,
|
||||
//! mixing, Opus decoding) is not emulated, so voices that need it stay
|
||||
//! silent. Software-decoded audio plays through the host's WASAPI, which
|
||||
//! middleware reaches through COM like on PC. fmod's console build sets
|
||||
//! all of this up inside `System_Create` and waits there for its first
|
||||
//! command to be acknowledged.
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::alloc::Layout;
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::ffi::c_void;
|
||||
use std::sync::{Mutex, MutexGuard};
|
||||
use std::time::Instant;
|
||||
|
||||
use super::xasync::E_INVALIDARG;
|
||||
use super::xgameruntime::{HRESULT, S_OK};
|
||||
use crate::{HleModule, hle_export};
|
||||
|
||||
const E_FAIL: HRESULT = 0x8000_4005_u32 as i32;
|
||||
const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
|
||||
/// The decoder's "no result yet", which fmod checks for.
|
||||
const PENDING_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32;
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
// The APU heap.
|
||||
|
||||
struct Block {
|
||||
size: usize,
|
||||
apu: u32,
|
||||
layout: Layout,
|
||||
}
|
||||
|
||||
struct Heap {
|
||||
/// By host address.
|
||||
blocks: BTreeMap<usize, Block>,
|
||||
next_apu: u32,
|
||||
}
|
||||
|
||||
static HEAP: Mutex<Heap> = Mutex::new(Heap {
|
||||
blocks: BTreeMap::new(),
|
||||
next_apu: 0x0001_0000,
|
||||
});
|
||||
|
||||
/// Zeroed host memory and its device address.
|
||||
// shortcut: device addresses are handed out once and never reused, so the
|
||||
// 32-bit space runs out after 4 GiB of allocations in total; reuse freed
|
||||
// ranges if a title streams that much through the heap.
|
||||
fn heap_alloc(size: usize, align: usize) -> Option<(*mut u8, u32)> {
|
||||
let layout = Layout::from_size_align(size.max(1), align.max(16)).ok()?;
|
||||
let mut heap = lock(&HEAP);
|
||||
let apu = heap.next_apu.checked_next_multiple_of(align as u32)?;
|
||||
let next = apu.checked_add(u32::try_from(layout.size()).ok()?)?;
|
||||
// SAFETY: non-zero size.
|
||||
let ptr = unsafe { std::alloc::alloc_zeroed(layout) };
|
||||
if ptr.is_null() {
|
||||
return None;
|
||||
}
|
||||
heap.next_apu = next;
|
||||
heap.blocks
|
||||
.insert(ptr as usize, Block { size, apu, layout });
|
||||
Some((ptr, apu))
|
||||
}
|
||||
|
||||
fn heap_free(ptr: *mut u8) {
|
||||
let block = lock(&HEAP).blocks.remove(&(ptr as usize));
|
||||
if let Some(block) = block {
|
||||
// SAFETY: allocated by `heap_alloc` with this layout.
|
||||
unsafe { std::alloc::dealloc(ptr, block.layout) };
|
||||
}
|
||||
}
|
||||
|
||||
/// The device address of any byte of a heap block, 0 elsewhere.
|
||||
fn heap_map(ptr: usize) -> u32 {
|
||||
let heap = lock(&HEAP);
|
||||
match heap.blocks.range(..=ptr).next_back() {
|
||||
Some((&start, block)) if ptr < start + block.size.max(1) => {
|
||||
block.apu + (ptr - start) as u32
|
||||
}
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The host address of a device address, if a heap block holds it.
|
||||
fn heap_unmap(apu: u32) -> Option<*mut u8> {
|
||||
let heap = lock(&HEAP);
|
||||
heap.blocks
|
||||
.iter()
|
||||
.find(|(_, b)| (b.apu..b.apu.saturating_add(b.size as u32)).contains(&apu))
|
||||
.map(|(&start, b)| (start + (apu - b.apu) as usize) as *mut u8)
|
||||
}
|
||||
|
||||
pub extern "system" fn ApuAlloc(
|
||||
out: *mut *mut c_void,
|
||||
apu: *mut u32,
|
||||
size: u32,
|
||||
align: u32,
|
||||
_flags: u32,
|
||||
) -> HRESULT {
|
||||
if out.is_null() || size == 0 || align < 4 || !align.is_power_of_two() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let Some((ptr, address)) = heap_alloc(size as usize, align as usize) else {
|
||||
return E_OUTOFMEMORY;
|
||||
};
|
||||
// SAFETY: checked non-null; optional out parameter checked below.
|
||||
unsafe {
|
||||
out.write(ptr.cast());
|
||||
if !apu.is_null() {
|
||||
apu.write(address);
|
||||
}
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn ApuFree(ptr: *mut c_void) {
|
||||
heap_free(ptr.cast());
|
||||
}
|
||||
|
||||
pub extern "system" fn ApuMapVirtualAddress(ptr: *const c_void) -> u32 {
|
||||
heap_map(ptr as usize)
|
||||
}
|
||||
|
||||
pub extern "system" fn ApuIsVirtualAddressValid(ptr: *const c_void, align: u32) -> bool {
|
||||
let apu = heap_map(ptr as usize);
|
||||
apu != 0 && (align == 0 || apu.is_multiple_of(align))
|
||||
}
|
||||
|
||||
// SHAPE context arrays.
|
||||
|
||||
/// Six counts (rate conversion, EQ/compression, filter/volume, DMA, XMA,
|
||||
/// PCM), then the six arrays and their device addresses.
|
||||
#[repr(C, packed)]
|
||||
pub struct ShapeContexts {
|
||||
counts: [u32; 6],
|
||||
arrays: [*mut c_void; 6],
|
||||
apu: [u32; 6],
|
||||
}
|
||||
|
||||
/// Bytes per context: rate conversion, DMA and XMA as fmod clears them;
|
||||
/// the others (not seen yet) get a generous upper bound.
|
||||
const CONTEXT_BYTES: [usize; 6] = [32, 256, 256, 16, 64, 256];
|
||||
|
||||
static CONTEXTS: Mutex<Option<[usize; 6]>> = Mutex::new(None);
|
||||
|
||||
pub extern "system" fn AcpHalAllocateShapeContexts(contexts: *mut ShapeContexts) -> HRESULT {
|
||||
if contexts.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let mut allocated = lock(&CONTEXTS);
|
||||
if allocated.is_some() {
|
||||
return E_FAIL;
|
||||
}
|
||||
// SAFETY: the title passes its request; packed fields are copied out.
|
||||
let counts = unsafe { std::ptr::addr_of!((*contexts).counts).read_unaligned() };
|
||||
let mut arrays: [*mut c_void; 6] = [std::ptr::null_mut(); 6];
|
||||
let mut addresses = [0u32; 6];
|
||||
for i in 0..6 {
|
||||
if counts[i] == 0 {
|
||||
continue;
|
||||
}
|
||||
let Some((ptr, apu)) = heap_alloc(counts[i] as usize * CONTEXT_BYTES[i], 256) else {
|
||||
arrays.iter().for_each(|&p| heap_free(p.cast()));
|
||||
return E_OUTOFMEMORY;
|
||||
};
|
||||
(arrays[i], addresses[i]) = (ptr.cast(), apu);
|
||||
}
|
||||
// SAFETY: as above.
|
||||
unsafe {
|
||||
std::ptr::addr_of_mut!((*contexts).arrays).write_unaligned(arrays);
|
||||
std::ptr::addr_of_mut!((*contexts).apu).write_unaligned(addresses);
|
||||
}
|
||||
*allocated = Some(arrays.map(|p| p as usize));
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn AcpHalReleaseShapeContexts() -> HRESULT {
|
||||
match lock(&CONTEXTS).take() {
|
||||
Some(arrays) => {
|
||||
arrays.iter().for_each(|&p| heap_free(p as *mut u8));
|
||||
S_OK
|
||||
}
|
||||
None => E_FAIL,
|
||||
}
|
||||
}
|
||||
|
||||
// The audio coprocessor.
|
||||
|
||||
const LOAD_FLOWGRAPH: u32 = 1;
|
||||
const REGISTER_MESSAGES: u32 = 2;
|
||||
const UNREGISTER_MESSAGES: u32 = 3;
|
||||
|
||||
const FLOWGRAPH_COMPLETED: u32 = 0x02;
|
||||
const COMMAND_COMPLETED: u32 = 0x10;
|
||||
const DISCONNECTED: u32 = 0x80;
|
||||
|
||||
/// Audio frames of 128 samples at 48 kHz.
|
||||
const FRAMES_PER_SECOND: u64 = 375;
|
||||
|
||||
#[repr(C, packed)]
|
||||
#[derive(Clone, Copy)]
|
||||
struct Message {
|
||||
kind: u32,
|
||||
dropped: u32,
|
||||
usec: u32,
|
||||
data: [u8; 16],
|
||||
}
|
||||
|
||||
struct State {
|
||||
connected: bool,
|
||||
/// Message kinds the title registered for.
|
||||
mask: u32,
|
||||
messages: VecDeque<Message>,
|
||||
since: Instant,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn usec(&self) -> u64 {
|
||||
self.since.elapsed().as_micros() as u64
|
||||
}
|
||||
|
||||
fn frame(&self) -> u32 {
|
||||
(self.usec() * FRAMES_PER_SECOND / 1_000_000) as u32
|
||||
}
|
||||
|
||||
// shortcut: the queue is unbounded and never reports dropped messages;
|
||||
// bound it at the size given to `connect` if a title relies on drops.
|
||||
fn post(&mut self, kind: u32, data: &[u8]) {
|
||||
if self.mask & kind == 0 {
|
||||
return;
|
||||
}
|
||||
let mut message = Message {
|
||||
kind,
|
||||
dropped: 0,
|
||||
usec: self.usec() as u32,
|
||||
data: [0; 16],
|
||||
};
|
||||
message.data[..data.len()].copy_from_slice(data);
|
||||
self.messages.push_back(message);
|
||||
}
|
||||
}
|
||||
|
||||
/// The interface object: its method table, then our state.
|
||||
#[repr(C)]
|
||||
pub struct Acp {
|
||||
vtable: &'static AcpMethods,
|
||||
state: Mutex<State>,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct AcpMethods {
|
||||
connect: extern "system" fn(*mut Acp, u32, u32) -> HRESULT,
|
||||
disconnect: extern "system" fn(*mut Acp) -> HRESULT,
|
||||
submit: extern "system" fn(*mut Acp, u32, u64, u32, *const c_void, u32) -> HRESULT,
|
||||
pop_message: extern "system" fn(*mut Acp, *mut Message) -> bool,
|
||||
message_count: extern "system" fn(*mut Acp) -> u32,
|
||||
release: extern "system" fn(*mut Acp),
|
||||
}
|
||||
|
||||
static ACP_METHODS: AcpMethods = AcpMethods {
|
||||
connect,
|
||||
disconnect,
|
||||
submit,
|
||||
pop_message,
|
||||
message_count,
|
||||
release,
|
||||
};
|
||||
|
||||
fn state(this: *mut Acp) -> MutexGuard<'static, State> {
|
||||
// SAFETY: title code calls methods on the object `AcpHalCreate` made,
|
||||
// which lives until `release`.
|
||||
lock(unsafe { &(*this).state })
|
||||
}
|
||||
|
||||
extern "system" fn connect(this: *mut Acp, commands: u32, _messages: u32) -> HRESULT {
|
||||
if commands == 0 {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
state(this).connected = true;
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn disconnect(this: *mut Acp) -> HRESULT {
|
||||
let mut state = state(this);
|
||||
if !state.connected {
|
||||
return E_FAIL;
|
||||
}
|
||||
state.post(DISCONNECTED, &[]);
|
||||
state.connected = false;
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Done at once: message registrations take effect, a flowgraph completes
|
||||
/// unprocessed, a command with an id is acknowledged, and its notification
|
||||
/// word is set.
|
||||
extern "system" fn submit(
|
||||
this: *mut Acp,
|
||||
command: u32,
|
||||
id: u64,
|
||||
_frame: u32,
|
||||
data: *const c_void,
|
||||
notification: u32,
|
||||
) -> HRESULT {
|
||||
static SEEN: Mutex<u64> = Mutex::new(0);
|
||||
if command < 64 && *lock(&SEEN) & 1 << command == 0 {
|
||||
*lock(&SEEN) |= 1 << command;
|
||||
tracing::info!(command, "first coprocessor command of this kind");
|
||||
}
|
||||
let mut state = state(this);
|
||||
let word = |at: usize| -> Option<u32> {
|
||||
// SAFETY: the command's data starts with these u32 fields.
|
||||
(!data.is_null()).then(|| unsafe { data.cast::<u32>().add(at).read_unaligned() })
|
||||
};
|
||||
match command {
|
||||
REGISTER_MESSAGES => state.mask |= word(0).unwrap_or(0),
|
||||
UNREGISTER_MESSAGES => state.mask &= !word(0).unwrap_or(0),
|
||||
LOAD_FLOWGRAPH => {
|
||||
let flowgraph = word(1).unwrap_or(0);
|
||||
state.post(FLOWGRAPH_COMPLETED, &flowgraph.to_le_bytes());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if id != 0 {
|
||||
let mut done = [0u8; 16];
|
||||
done[..4].copy_from_slice(&command.to_le_bytes());
|
||||
done[4..12].copy_from_slice(&id.to_le_bytes());
|
||||
done[12..].copy_from_slice(&state.frame().to_le_bytes());
|
||||
state.post(COMMAND_COMPLETED, &done);
|
||||
}
|
||||
if notification != 0
|
||||
&& let Some(word) = heap_unmap(notification)
|
||||
{
|
||||
// SAFETY: a u32 in a heap block, which the title reads as volatile.
|
||||
unsafe { word.cast::<u32>().write_volatile(1) };
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn pop_message(this: *mut Acp, out: *mut Message) -> bool {
|
||||
let Some(message) = state(this).messages.pop_front() else {
|
||||
return false;
|
||||
};
|
||||
if !out.is_null() {
|
||||
// SAFETY: the title passes room for one message.
|
||||
unsafe { out.write_unaligned(message) };
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
extern "system" fn message_count(this: *mut Acp) -> u32 {
|
||||
state(this).messages.len() as u32
|
||||
}
|
||||
|
||||
extern "system" fn release(this: *mut Acp) {
|
||||
// SAFETY: made by `AcpHalCreate` with `Box::into_raw`; released once.
|
||||
drop(unsafe { Box::from_raw(this) });
|
||||
}
|
||||
|
||||
pub extern "system" fn AcpHalCreate(out: *mut *mut Acp) -> HRESULT {
|
||||
if out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let acp = Box::new(Acp {
|
||||
vtable: &ACP_METHODS,
|
||||
state: Mutex::new(State {
|
||||
connected: false,
|
||||
mask: 0,
|
||||
messages: VecDeque::new(),
|
||||
since: Instant::now(),
|
||||
}),
|
||||
});
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(Box::into_raw(acp)) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
// The APU decoder: connections get their memory, commands are refused.
|
||||
|
||||
#[repr(C)]
|
||||
pub struct ConnectInput {
|
||||
process: u32,
|
||||
streams: u32,
|
||||
commands_per_stream: u32,
|
||||
memory: u32,
|
||||
frames_per_output: u32,
|
||||
options: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct ConnectOutput {
|
||||
memory: *mut c_void,
|
||||
result_event: *mut c_void,
|
||||
}
|
||||
|
||||
/// The memory a connection hands out.
|
||||
pub struct Connection(*mut u8, Layout);
|
||||
|
||||
pub extern "system" fn XApuConnect(
|
||||
input: *const ConnectInput,
|
||||
output: *mut ConnectOutput,
|
||||
handle: *mut *mut Connection,
|
||||
) -> HRESULT {
|
||||
const RESULT_READY_EVENT: u32 = 8;
|
||||
if input.is_null() || output.is_null() || handle.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: checked non-null.
|
||||
let input = unsafe { &*input };
|
||||
if input.options & RESULT_READY_EVENT != 0 {
|
||||
// shortcut: no event to signal, since no result ever comes; create
|
||||
// one if a title asks for it.
|
||||
return E_FAIL;
|
||||
}
|
||||
let Ok(layout) = Layout::from_size_align(input.memory.max(16) as usize, 16) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
// SAFETY: non-zero size.
|
||||
let memory = unsafe { std::alloc::alloc_zeroed(layout) };
|
||||
if memory.is_null() {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
// SAFETY: checked non-null.
|
||||
unsafe {
|
||||
output.write(ConnectOutput {
|
||||
memory: memory.cast(),
|
||||
result_event: std::ptr::null_mut(),
|
||||
});
|
||||
handle.write(Box::into_raw(Box::new(Connection(memory, layout))));
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Nothing is decoded: the stream fails instead of waiting forever.
|
||||
pub extern "system" fn XApuEnqueueCommand() -> HRESULT {
|
||||
E_FAIL
|
||||
}
|
||||
|
||||
pub extern "system" fn XApuDequeueResult() -> HRESULT {
|
||||
PENDING_RESULTS
|
||||
}
|
||||
|
||||
pub extern "system" fn XApuDisconnect(handle: *mut Connection) -> HRESULT {
|
||||
if handle.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: made by `XApuConnect`; disconnected once.
|
||||
let Connection(memory, layout) = *unsafe { Box::from_raw(handle) };
|
||||
// SAFETY: allocated in `XApuConnect` with this layout.
|
||||
unsafe { std::alloc::dealloc(memory, layout) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "audio",
|
||||
dlls: &["acphal.dll", "xapu.dll"],
|
||||
exports: vec![
|
||||
hle_export!(AcpHalAllocateShapeContexts),
|
||||
hle_export!(AcpHalReleaseShapeContexts),
|
||||
hle_export!(AcpHalCreate),
|
||||
hle_export!(ApuAlloc),
|
||||
hle_export!(ApuFree),
|
||||
hle_export!(ApuIsVirtualAddressValid),
|
||||
hle_export!(ApuMapVirtualAddress),
|
||||
hle_export!(XApuConnect),
|
||||
hle_export!(XApuEnqueueCommand),
|
||||
hle_export!(XApuDequeueResult),
|
||||
hle_export!(XApuDisconnect),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn heap_maps_every_byte_of_a_block() {
|
||||
let (mut ptr, mut apu) = (std::ptr::null_mut(), 0);
|
||||
assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 128, 1), S_OK);
|
||||
assert!(apu != 0 && apu.is_multiple_of(128));
|
||||
let inner = ptr.cast::<u8>().wrapping_add(0x40).cast_const().cast();
|
||||
assert_eq!(ApuMapVirtualAddress(inner), apu + 0x40);
|
||||
assert!(ApuIsVirtualAddressValid(ptr, 128));
|
||||
assert_eq!(heap_unmap(apu + 4), Some(ptr.cast::<u8>().wrapping_add(4)));
|
||||
ApuFree(ptr);
|
||||
assert_eq!(ApuMapVirtualAddress(ptr), 0);
|
||||
assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 6, 1), E_INVALIDARG);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_as_fmod_does_it() {
|
||||
// Context arrays: rate conversion, DMA and XMA.
|
||||
let mut request = ShapeContexts {
|
||||
counts: [0x200, 0, 0, 0x400, 0x200, 0],
|
||||
arrays: [std::ptr::null_mut(); 6],
|
||||
apu: [0; 6],
|
||||
};
|
||||
assert_eq!(size_of::<ShapeContexts>(), 0x60);
|
||||
assert_eq!(AcpHalAllocateShapeContexts(&mut request), S_OK);
|
||||
let arrays = request.arrays;
|
||||
assert!(!arrays[0].is_null() && !arrays[3].is_null() && !arrays[4].is_null());
|
||||
assert!(arrays[1].is_null());
|
||||
// SAFETY: 0x200 rate-conversion contexts of 32 bytes were allocated.
|
||||
unsafe { arrays[0].cast::<u8>().write_bytes(0, 0x200 << 5) };
|
||||
|
||||
// Connect, register every message but frame starts, then wait for
|
||||
// the registration to be acknowledged.
|
||||
let mut acp = std::ptr::null_mut();
|
||||
assert_eq!(AcpHalCreate(&mut acp), S_OK);
|
||||
// SAFETY: just created.
|
||||
let m = unsafe { (*acp).vtable };
|
||||
assert_eq!((m.connect)(acp, 0x804, 0x804), S_OK);
|
||||
let mask = 0xfe_u32;
|
||||
let data = (&raw const mask).cast();
|
||||
assert_eq!(
|
||||
(m.submit)(acp, REGISTER_MESSAGES, 1, u32::MAX, data, 0),
|
||||
S_OK
|
||||
);
|
||||
let mut message = Message {
|
||||
kind: 0,
|
||||
dropped: 0,
|
||||
usec: 0,
|
||||
data: [0; 16],
|
||||
};
|
||||
assert!((m.pop_message)(acp, &mut message));
|
||||
let (kind, dropped) = (message.kind, message.dropped);
|
||||
assert_eq!((kind, dropped), (COMMAND_COMPLETED, 0));
|
||||
assert_eq!(
|
||||
u64::from_le_bytes(message.data[4..12].try_into().unwrap()),
|
||||
1
|
||||
);
|
||||
assert!(!(m.pop_message)(acp, &mut message));
|
||||
assert_eq!((m.disconnect)(acp), S_OK);
|
||||
assert_eq!((m.message_count)(acp), 1, "disconnected");
|
||||
(m.release)(acp);
|
||||
assert_eq!(AcpHalReleaseShapeContexts(), S_OK);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! `d3d12_xs.dll`: device creation. The device and everything it creates
|
||||
//! live in `victory-gpu`.
|
||||
|
||||
use victory_gpu::device;
|
||||
|
||||
use crate::{HleExport, HleModule};
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "d3d12x",
|
||||
dlls: &["d3d12_xs.dll"],
|
||||
exports: vec![
|
||||
HleExport {
|
||||
name: "D3D12XboxCreateDevice",
|
||||
address: device::create as *const () as usize,
|
||||
},
|
||||
HleExport {
|
||||
name: "D3D12SerializeRootSignature",
|
||||
address: victory_gpu::root::serialize as *const () as usize,
|
||||
},
|
||||
// A data import: the title reads the id at this address.
|
||||
HleExport {
|
||||
name: "IID_ID3D12Device",
|
||||
address: (&raw const device::IID) as usize,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{HleResolver, HostPolicy};
|
||||
use victory_loader::ImportResolver;
|
||||
use victory_loader::Resolution;
|
||||
use victory_pe::ImportSymbol;
|
||||
|
||||
#[test]
|
||||
fn the_interface_id_import_is_bound_to_data() {
|
||||
let symbol = ImportSymbol::Name {
|
||||
hint: 0,
|
||||
name: "IID_ID3D12Device".into(),
|
||||
};
|
||||
let r = HleResolver::new(HostPolicy::none());
|
||||
let Resolution::Found { address, .. } = r.resolve("d3d12_xs.dll", &symbol) else {
|
||||
panic!("not bound");
|
||||
};
|
||||
// SAFETY: the address is our static id.
|
||||
assert_eq!(unsafe { *(address as *const [u8; 16]) }, device::IID);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,587 @@
|
||||
//! Virtual drives over host folders: on the console, title storage is a
|
||||
//! drive of its own, and titles build paths on that assumption.
|
||||
//!
|
||||
//! Every title import that takes a path is bound here. A path on a virtual
|
||||
//! drive (`X:\..`, `X:/..`, `X:`, `\\?\X:\..`) is rewritten to the host
|
||||
//! folder behind it and handed to the host's own function; any other path
|
||||
//! goes to the host unchanged. A rewritten narrow path goes to the wide
|
||||
//! twin, so host folders outside the ANSI code page work. Letters are
|
||||
//! chosen among those the host does not use, so no host drive is hidden.
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
|
||||
use std::ffi::{CStr, c_char, c_void};
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
use std::sync::{Mutex, MutexGuard};
|
||||
|
||||
use windows_sys::Win32::Globalization::{CP_ACP, MultiByteToWideChar};
|
||||
use windows_sys::Win32::Storage::FileSystem::GetLogicalDrives;
|
||||
|
||||
use crate::{HleExport, HleModule, hle_export};
|
||||
|
||||
/// The host's own function: what the import would have been bound to.
|
||||
macro_rules! host {
|
||||
($dll:literal, $name:literal: $ty:ty) => {{
|
||||
static ADDRESS: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
|
||||
let address = *ADDRESS.get_or_init(|| {
|
||||
crate::host::function($dll, $name)
|
||||
.unwrap_or_else(|| panic!("the host lacks {}!{}", $dll, $name))
|
||||
});
|
||||
// SAFETY: the host exports this function with this signature.
|
||||
unsafe { std::mem::transmute::<usize, $ty>(address) }
|
||||
}};
|
||||
}
|
||||
|
||||
/// Mounted drives: upper-case letter and host root (UTF-16, no trailing
|
||||
/// separator, no NUL).
|
||||
static DRIVES: Mutex<Vec<(u16, Vec<u16>)>> = Mutex::new(Vec::new());
|
||||
|
||||
fn drives() -> MutexGuard<'static, Vec<(u16, Vec<u16>)>> {
|
||||
DRIVES.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Gives the host folder `root` a drive letter (the same one if it already
|
||||
/// has one): the highest letter neither the host nor another mount uses.
|
||||
pub fn mount(root: &Path) -> Option<char> {
|
||||
let mut wide: Vec<u16> = root.as_os_str().encode_wide().collect();
|
||||
while wide.len() > 3 && wide.last().is_some_and(|c| SEPARATORS.contains(c)) {
|
||||
wide.pop();
|
||||
}
|
||||
let mut drives = drives();
|
||||
if let Some(&(letter, _)) = drives.iter().find(|(_, r)| *r == wide) {
|
||||
return char::from_u32(letter.into());
|
||||
}
|
||||
// SAFETY: no arguments.
|
||||
let host = unsafe { GetLogicalDrives() };
|
||||
let letter = (b'D'..=b'Z').rev().find(|&l| {
|
||||
host >> (l - b'A') & 1 == 0 && !drives.iter().any(|(m, _)| *m == u16::from(l))
|
||||
})?;
|
||||
tracing::info!(drive = %char::from(letter), root = %root.display(), "virtual drive");
|
||||
drives.push((letter.into(), wide));
|
||||
Some(letter.into())
|
||||
}
|
||||
|
||||
const SEPARATORS: [u16; 2] = [b'\\' as u16, b'/' as u16];
|
||||
const VERBATIM: [u16; 4] = [b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16];
|
||||
|
||||
/// The host path, NUL-terminated, for `path` (without its NUL) if it is on
|
||||
/// a virtual drive.
|
||||
// shortcut: host roots are not made verbatim, so a long host root can push a
|
||||
// title path past MAX_PATH; switch to `\\?\` paths (normalising `..` and `/`
|
||||
// ourselves) if a title's paths get that long.
|
||||
fn translate(path: &[u16]) -> Option<Vec<u16>> {
|
||||
let (prefix, rest) = match path.strip_prefix(&VERBATIM[..]) {
|
||||
Some(rest) => (&VERBATIM[..], rest),
|
||||
None => (&[][..], path),
|
||||
};
|
||||
let &[letter, colon, ..] = rest else {
|
||||
return None;
|
||||
};
|
||||
if colon != u16::from(b':') {
|
||||
return None;
|
||||
}
|
||||
let letter = u8::try_from(letter).ok().filter(u8::is_ascii_alphabetic)?;
|
||||
let letter = u16::from(letter.to_ascii_uppercase());
|
||||
let drives = drives();
|
||||
let (_, root) = drives.iter().find(|(l, _)| *l == letter)?;
|
||||
let tail = &rest[2..];
|
||||
let mut out = prefix.to_vec();
|
||||
out.extend_from_slice(root);
|
||||
// `X:` and `X:name` are relative to the root.
|
||||
if !tail.first().is_some_and(|c| SEPARATORS.contains(c)) {
|
||||
out.push(b'\\'.into());
|
||||
}
|
||||
let verbatim = !prefix.is_empty();
|
||||
out.extend(tail.iter().map(|&c| {
|
||||
if verbatim && c == u16::from(b'/') {
|
||||
b'\\'.into()
|
||||
} else {
|
||||
c
|
||||
}
|
||||
}));
|
||||
out.push(0);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A title's wide path: the host path when it is on a virtual drive, else
|
||||
/// the title's own pointer.
|
||||
struct Wide(*const u16, Option<Vec<u16>>);
|
||||
|
||||
impl Wide {
|
||||
fn ptr(&self) -> *const u16 {
|
||||
self.1.as_ref().map_or(self.0, |p| p.as_ptr())
|
||||
}
|
||||
}
|
||||
|
||||
fn wide(path: *const u16) -> Wide {
|
||||
if path.is_null() {
|
||||
return Wide(path, None);
|
||||
}
|
||||
// SAFETY: the title passes a NUL-terminated path.
|
||||
let path_slice = unsafe {
|
||||
let len = (0..).take_while(|&i| *path.add(i) != 0).count();
|
||||
std::slice::from_raw_parts(path, len)
|
||||
};
|
||||
Wide(path, translate(path_slice))
|
||||
}
|
||||
|
||||
/// A narrow path (ANSI code page, as the host decodes it) on a virtual
|
||||
/// drive, as a wide host path.
|
||||
fn narrow(path: *const c_char) -> Option<Vec<u16>> {
|
||||
if path.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the title passes a NUL-terminated path.
|
||||
let bytes = unsafe { CStr::from_ptr(path) }.to_bytes();
|
||||
// The drive part is ASCII in every code page; decode only candidates.
|
||||
match bytes.strip_prefix(br"\\?\").unwrap_or(bytes) {
|
||||
[letter, b':', ..] if letter.is_ascii_alphabetic() => {}
|
||||
_ => return None,
|
||||
}
|
||||
let len = i32::try_from(bytes.len()).ok()?;
|
||||
// SAFETY: sizing call, then a call with room for `n` units.
|
||||
let wide = unsafe {
|
||||
let n = MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, std::ptr::null_mut(), 0);
|
||||
let mut wide = vec![0u16; usize::try_from(n).ok()?];
|
||||
MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, wide.as_mut_ptr(), n);
|
||||
wide
|
||||
};
|
||||
translate(&wide)
|
||||
}
|
||||
|
||||
/// An ASCII mode string (`"rb"`, `"w, ccs=UTF-8"`) for a wide CRT call.
|
||||
fn widen(mode: *const c_char) -> Vec<u16> {
|
||||
if mode.is_null() {
|
||||
return vec![0];
|
||||
}
|
||||
// SAFETY: a NUL-terminated mode string.
|
||||
let bytes = unsafe { CStr::from_ptr(mode) }.to_bytes();
|
||||
bytes.iter().map(|&b| u16::from(b)).chain([0]).collect()
|
||||
}
|
||||
|
||||
type Handle = *mut c_void;
|
||||
type File = *mut c_void;
|
||||
|
||||
// kernel32 and its file API sets.
|
||||
|
||||
pub extern "system" fn CreateFileW(
|
||||
path: *const u16,
|
||||
access: u32,
|
||||
share: u32,
|
||||
security: *const c_void,
|
||||
disposition: u32,
|
||||
flags: u32,
|
||||
template: Handle,
|
||||
) -> Handle {
|
||||
let p = wide(path);
|
||||
host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)(
|
||||
p.ptr(),
|
||||
access,
|
||||
share,
|
||||
security,
|
||||
disposition,
|
||||
flags,
|
||||
template,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn CreateFileA(
|
||||
path: *const c_char,
|
||||
access: u32,
|
||||
share: u32,
|
||||
security: *const c_void,
|
||||
disposition: u32,
|
||||
flags: u32,
|
||||
template: Handle,
|
||||
) -> Handle {
|
||||
match narrow(path) {
|
||||
Some(p) => CreateFileW(
|
||||
p.as_ptr(),
|
||||
access,
|
||||
share,
|
||||
security,
|
||||
disposition,
|
||||
flags,
|
||||
template,
|
||||
),
|
||||
None => {
|
||||
host!("kernel32.dll", "CreateFileA": extern "system" fn(*const c_char, u32, u32, *const c_void, u32, u32, Handle) -> Handle)(
|
||||
path,
|
||||
access,
|
||||
share,
|
||||
security,
|
||||
disposition,
|
||||
flags,
|
||||
template,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "system" fn DeleteFileA(path: *const c_char) -> i32 {
|
||||
match narrow(path) {
|
||||
Some(p) => {
|
||||
host!("kernel32.dll", "DeleteFileW": extern "system" fn(*const u16) -> i32)(p.as_ptr())
|
||||
}
|
||||
None => {
|
||||
host!("kernel32.dll", "DeleteFileA": extern "system" fn(*const c_char) -> i32)(path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "system" fn CreateDirectoryW(path: *const u16, security: *const c_void) -> i32 {
|
||||
let p = wide(path);
|
||||
host!("kernel32.dll", "CreateDirectoryW": extern "system" fn(*const u16, *const c_void) -> i32)(
|
||||
p.ptr(),
|
||||
security,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn GetFileAttributesExW(
|
||||
path: *const u16,
|
||||
level: i32,
|
||||
info: *mut c_void,
|
||||
) -> i32 {
|
||||
let p = wide(path);
|
||||
host!("kernel32.dll", "GetFileAttributesExW": extern "system" fn(*const u16, i32, *mut c_void) -> i32)(
|
||||
p.ptr(),
|
||||
level,
|
||||
info,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn GetDiskFreeSpaceExW(
|
||||
path: *const u16,
|
||||
available: *mut u64,
|
||||
total: *mut u64,
|
||||
free: *mut u64,
|
||||
) -> i32 {
|
||||
let p = wide(path);
|
||||
host!("kernel32.dll", "GetDiskFreeSpaceExW": extern "system" fn(*const u16, *mut u64, *mut u64, *mut u64) -> i32)(
|
||||
p.ptr(),
|
||||
available,
|
||||
total,
|
||||
free,
|
||||
)
|
||||
}
|
||||
|
||||
/// Wants a volume root: a virtual drive answers for the host volume its
|
||||
/// folder is on.
|
||||
pub extern "system" fn GetDiskFreeSpaceW(
|
||||
root: *const u16,
|
||||
sectors_per_cluster: *mut u32,
|
||||
bytes_per_sector: *mut u32,
|
||||
free_clusters: *mut u32,
|
||||
clusters: *mut u32,
|
||||
) -> i32 {
|
||||
let mut p = wide(root);
|
||||
if let Some(host) = &mut p.1
|
||||
&& let [letter, colon, sep, ..] = host[..]
|
||||
&& colon == u16::from(b':')
|
||||
&& SEPARATORS.contains(&sep)
|
||||
{
|
||||
*host = vec![letter, colon, sep, 0];
|
||||
}
|
||||
host!("kernel32.dll", "GetDiskFreeSpaceW": extern "system" fn(*const u16, *mut u32, *mut u32, *mut u32, *mut u32) -> i32)(
|
||||
p.ptr(),
|
||||
sectors_per_cluster,
|
||||
bytes_per_sector,
|
||||
free_clusters,
|
||||
clusters,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn FindFirstFileW(path: *const u16, data: *mut c_void) -> Handle {
|
||||
let p = wide(path);
|
||||
host!("kernel32.dll", "FindFirstFileW": extern "system" fn(*const u16, *mut c_void) -> Handle)(
|
||||
p.ptr(),
|
||||
data,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn FindFirstFileExW(
|
||||
path: *const u16,
|
||||
level: i32,
|
||||
data: *mut c_void,
|
||||
search: i32,
|
||||
filter: *mut c_void,
|
||||
flags: u32,
|
||||
) -> Handle {
|
||||
let p = wide(path);
|
||||
host!("kernel32.dll", "FindFirstFileExW": extern "system" fn(*const u16, i32, *mut c_void, i32, *mut c_void, u32) -> Handle)(
|
||||
p.ptr(),
|
||||
level,
|
||||
data,
|
||||
search,
|
||||
filter,
|
||||
flags,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32 {
|
||||
let (from, to) = (wide(from), wide(to));
|
||||
host!("kernel32.dll", "MoveFileExW": extern "system" fn(*const u16, *const u16, u32) -> i32)(
|
||||
from.ptr(),
|
||||
to.ptr(),
|
||||
flags,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn SetCurrentDirectoryA(path: *const c_char) -> i32 {
|
||||
match narrow(path) {
|
||||
Some(p) => {
|
||||
host!("kernel32.dll", "SetCurrentDirectoryW": extern "system" fn(*const u16) -> i32)(
|
||||
p.as_ptr(),
|
||||
)
|
||||
}
|
||||
None => {
|
||||
host!("kernel32.dll", "SetCurrentDirectoryA": extern "system" fn(*const c_char) -> i32)(
|
||||
path,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The C runtime (ucrtbase, which the title's CRT imports bind to).
|
||||
|
||||
pub extern "C" fn _wfopen(path: *const u16, mode: *const u16) -> File {
|
||||
let p = wide(path);
|
||||
host!("ucrtbase.dll", "_wfopen": extern "C" fn(*const u16, *const u16) -> File)(p.ptr(), mode)
|
||||
}
|
||||
|
||||
pub extern "C" fn _wfopen_s(out: *mut File, path: *const u16, mode: *const u16) -> i32 {
|
||||
let p = wide(path);
|
||||
host!("ucrtbase.dll", "_wfopen_s": extern "C" fn(*mut File, *const u16, *const u16) -> i32)(
|
||||
out,
|
||||
p.ptr(),
|
||||
mode,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> File {
|
||||
let p = wide(path);
|
||||
host!("ucrtbase.dll", "_wfsopen": extern "C" fn(*const u16, *const u16, i32) -> File)(
|
||||
p.ptr(),
|
||||
mode,
|
||||
share,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File {
|
||||
match narrow(path) {
|
||||
Some(p) => _wfopen(p.as_ptr(), widen(mode).as_ptr()),
|
||||
None => {
|
||||
host!("ucrtbase.dll", "fopen": extern "C" fn(*const c_char, *const c_char) -> File)(
|
||||
path, mode,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "C" fn fopen_s(out: *mut File, path: *const c_char, mode: *const c_char) -> i32 {
|
||||
match narrow(path) {
|
||||
Some(p) => _wfopen_s(out, p.as_ptr(), widen(mode).as_ptr()),
|
||||
None => {
|
||||
host!("ucrtbase.dll", "fopen_s": extern "C" fn(*mut File, *const c_char, *const c_char) -> i32)(
|
||||
out, path, mode,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "C" fn _wstat64(path: *const u16, stat: *mut c_void) -> i32 {
|
||||
let p = wide(path);
|
||||
host!("ucrtbase.dll", "_wstat64": extern "C" fn(*const u16, *mut c_void) -> i32)(p.ptr(), stat)
|
||||
}
|
||||
|
||||
pub extern "C" fn _stat64i32(path: *const c_char, stat: *mut c_void) -> i32 {
|
||||
match narrow(path) {
|
||||
Some(p) => {
|
||||
host!("ucrtbase.dll", "_wstat64i32": extern "C" fn(*const u16, *mut c_void) -> i32)(
|
||||
p.as_ptr(),
|
||||
stat,
|
||||
)
|
||||
}
|
||||
None => {
|
||||
host!("ucrtbase.dll", "_stat64i32": extern "C" fn(*const c_char, *mut c_void) -> i32)(
|
||||
path, stat,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "C" fn remove(path: *const c_char) -> i32 {
|
||||
match narrow(path) {
|
||||
Some(p) => host!("ucrtbase.dll", "_wremove": extern "C" fn(*const u16) -> i32)(p.as_ptr()),
|
||||
None => host!("ucrtbase.dll", "remove": extern "C" fn(*const c_char) -> i32)(path),
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "C" fn _wchmod(path: *const u16, mode: i32) -> i32 {
|
||||
let p = wide(path);
|
||||
host!("ucrtbase.dll", "_wchmod": extern "C" fn(*const u16, i32) -> i32)(p.ptr(), mode)
|
||||
}
|
||||
|
||||
pub extern "C" fn _wutime64(path: *const u16, times: *mut c_void) -> i32 {
|
||||
let p = wide(path);
|
||||
host!("ucrtbase.dll", "_wutime64": extern "C" fn(*const u16, *mut c_void) -> i32)(
|
||||
p.ptr(),
|
||||
times,
|
||||
)
|
||||
}
|
||||
|
||||
// The C++ library: `std::basic_filebuf::open` goes through `_Fiopen`.
|
||||
|
||||
const FIOPEN: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z";
|
||||
|
||||
/// `_Fiopen(const char* path, ios_base::openmode, int protection)`.
|
||||
extern "C" fn fiopen(path: *const c_char, mode: i32, protection: i32) -> File {
|
||||
match narrow(path) {
|
||||
Some(p) => {
|
||||
host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)(
|
||||
p.as_ptr(),
|
||||
mode,
|
||||
protection,
|
||||
)
|
||||
}
|
||||
None => {
|
||||
host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z": extern "C" fn(*const c_char, i32, i32) -> File)(
|
||||
path, mode, protection,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "files",
|
||||
dlls: &[
|
||||
"kernel32.dll",
|
||||
"kernelbase.dll",
|
||||
"api-ms-win-core-file-*",
|
||||
"api-ms-win-core-processenvironment-*",
|
||||
"ucrtbase.dll",
|
||||
"api-ms-win-crt-stdio-*",
|
||||
"api-ms-win-crt-filesystem-*",
|
||||
"api-ms-win-crt-time-*",
|
||||
"msvcp140.dll",
|
||||
],
|
||||
exports: vec![
|
||||
hle_export!(CreateFileW),
|
||||
hle_export!(CreateFileA),
|
||||
hle_export!(DeleteFileA),
|
||||
hle_export!(CreateDirectoryW),
|
||||
hle_export!(GetFileAttributesExW),
|
||||
hle_export!(GetDiskFreeSpaceExW),
|
||||
hle_export!(GetDiskFreeSpaceW),
|
||||
hle_export!(FindFirstFileW),
|
||||
hle_export!(FindFirstFileExW),
|
||||
hle_export!(MoveFileExW),
|
||||
hle_export!(SetCurrentDirectoryA),
|
||||
hle_export!(_wfopen),
|
||||
hle_export!(_wfopen_s),
|
||||
hle_export!(_wfsopen),
|
||||
hle_export!(fopen),
|
||||
hle_export!(fopen_s),
|
||||
hle_export!(_wstat64),
|
||||
hle_export!(_stat64i32),
|
||||
hle_export!(remove),
|
||||
hle_export!(_wchmod),
|
||||
hle_export!(_wutime64),
|
||||
HleExport {
|
||||
name: FIOPEN,
|
||||
address: fiopen as *const () as usize,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn w(s: &str) -> Vec<u16> {
|
||||
s.encode_utf16().chain([0]).collect()
|
||||
}
|
||||
|
||||
fn text(v: &[u16]) -> String {
|
||||
String::from_utf16_lossy(&v[..v.len() - 1])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_only_paths_on_mounted_drives() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().to_string_lossy().into_owned();
|
||||
let letter = mount(dir.path()).unwrap();
|
||||
assert_eq!(
|
||||
mount(dir.path()),
|
||||
Some(letter),
|
||||
"mounting twice reuses the letter"
|
||||
);
|
||||
let tr = |s: String| translate(&w(&s)[..s.encode_utf16().count()]).map(|v| text(&v));
|
||||
assert_eq!(
|
||||
tr(format!("{letter}:/a/b.txt")),
|
||||
Some(format!("{root}/a/b.txt"))
|
||||
);
|
||||
let lower = letter.to_ascii_lowercase();
|
||||
assert_eq!(tr(format!("{lower}:\\a")), Some(format!("{root}\\a")));
|
||||
assert_eq!(tr(format!("{letter}:")), Some(format!("{root}\\")));
|
||||
assert_eq!(
|
||||
tr(format!(r"\\?\{letter}:/a/b")),
|
||||
Some(format!(r"\\?\{root}\a\b"))
|
||||
);
|
||||
assert_eq!(tr(r"C:\Windows".into()), None);
|
||||
assert_eq!(tr("relative/path".into()), None);
|
||||
assert_eq!(tr(String::new()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn title_file_calls_land_in_the_host_folder() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let letter = mount(dir.path()).unwrap();
|
||||
const GENERIC_WRITE: u32 = 0x4000_0000;
|
||||
const CREATE_ALWAYS: u32 = 2;
|
||||
let close = host!("kernel32.dll", "CloseHandle": extern "system" fn(Handle) -> i32);
|
||||
let fclose = host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32);
|
||||
|
||||
let path = w(&format!(r"{letter}:\created.bin"));
|
||||
let null = std::ptr::null_mut();
|
||||
let h = CreateFileW(
|
||||
path.as_ptr(),
|
||||
GENERIC_WRITE,
|
||||
0,
|
||||
null,
|
||||
CREATE_ALWAYS,
|
||||
0,
|
||||
null,
|
||||
);
|
||||
assert_ne!(h as isize, -1);
|
||||
close(h);
|
||||
assert!(dir.path().join("created.bin").is_file());
|
||||
|
||||
let path = format!("{letter}:/opened.txt\0");
|
||||
let f = fopen(path.as_ptr().cast(), c"wb".as_ptr());
|
||||
assert!(!f.is_null());
|
||||
fclose(f);
|
||||
assert!(dir.path().join("opened.txt").is_file());
|
||||
|
||||
let path = format!("{letter}:/stream.txt\0");
|
||||
const OUT: i32 = 2;
|
||||
let f = fiopen(path.as_ptr().cast(), OUT, 0x40);
|
||||
assert!(!f.is_null());
|
||||
fclose(f);
|
||||
assert!(dir.path().join("stream.txt").is_file());
|
||||
|
||||
assert_eq!(remove(path.as_ptr().cast()), 0);
|
||||
assert!(!dir.path().join("stream.txt").exists());
|
||||
|
||||
// Other paths pass through untouched.
|
||||
let host_path = format!("{}\0", dir.path().join("plain.txt").display());
|
||||
let f = fopen(host_path.as_ptr().cast(), c"wb".as_ptr());
|
||||
assert!(!f.is_null());
|
||||
fclose(f);
|
||||
assert!(dir.path().join("plain.txt").is_file());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
//! `gameinput.dll`: input devices. For now nothing is ever connected:
|
||||
//! readings and device lookups fail as they do with no device plugged in,
|
||||
//! callbacks are accepted and never called.
|
||||
#![allow(non_snake_case)]
|
||||
// Title code calls these through the object, passing pointers the real API
|
||||
// would trust.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use super::xasync::{E_INVALIDARG, E_NOTIMPL};
|
||||
use super::xgameruntime::{HRESULT, S_OK};
|
||||
use crate::{HleExport, HleModule};
|
||||
|
||||
/// The documented "no such reading" and "no such device" errors.
|
||||
pub const READING_NOT_FOUND: HRESULT = 0x838A_0003_u32 as i32;
|
||||
pub const DEVICE_NOT_FOUND: HRESULT = 0x838A_0002_u32 as i32;
|
||||
const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32;
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Object {
|
||||
vtable: &'static Vtable,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Vtable([*const (); 22]);
|
||||
// SAFETY: function addresses only.
|
||||
unsafe impl Sync for Vtable {}
|
||||
|
||||
static OBJECT: Object = Object { vtable: &VTABLE };
|
||||
|
||||
type This = *const Object;
|
||||
type Out = *mut *const c_void;
|
||||
|
||||
/// The DLL's only export (ordinal 1): the input object, static and shared.
|
||||
pub extern "system" fn GameInputCreate(out: *mut This) -> HRESULT {
|
||||
tracing::info!("GameInputCreate: no input devices");
|
||||
if out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: checked non-null; the title passes room for a pointer.
|
||||
unsafe { out.write(&OBJECT) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Clears a COM out pointer and returns `hr`.
|
||||
fn fail(out: Out, hr: HRESULT) -> HRESULT {
|
||||
if !out.is_null() {
|
||||
// SAFETY: checked non-null; the title passes room for a pointer.
|
||||
unsafe { out.write(std::ptr::null()) };
|
||||
}
|
||||
hr
|
||||
}
|
||||
|
||||
extern "system" fn query_interface(_: This, _iid: *const c_void, out: Out) -> HRESULT {
|
||||
tracing::warn!("input QueryInterface not implemented");
|
||||
fail(out, E_NOINTERFACE)
|
||||
}
|
||||
extern "system" fn add_ref(_: This) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
static START: LazyLock<Instant> = LazyLock::new(Instant::now);
|
||||
|
||||
/// Microseconds; only ever compared with readings, and there are none.
|
||||
extern "system" fn timestamp(_: This) -> u64 {
|
||||
START.elapsed().as_micros() as u64
|
||||
}
|
||||
|
||||
extern "system" fn current_reading(
|
||||
_: This,
|
||||
_kind: u32,
|
||||
_device: *const c_void,
|
||||
out: Out,
|
||||
) -> HRESULT {
|
||||
fail(out, READING_NOT_FOUND)
|
||||
}
|
||||
extern "system" fn relative_reading(
|
||||
_: This,
|
||||
_reference: *const c_void,
|
||||
_kind: u32,
|
||||
_device: *const c_void,
|
||||
out: Out,
|
||||
) -> HRESULT {
|
||||
fail(out, READING_NOT_FOUND)
|
||||
}
|
||||
extern "system" fn temporal_reading(
|
||||
_: This,
|
||||
_time: u64,
|
||||
_device: *const c_void,
|
||||
out: Out,
|
||||
) -> HRESULT {
|
||||
fail(out, READING_NOT_FOUND)
|
||||
}
|
||||
|
||||
static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
fn token(out: *mut u64) -> HRESULT {
|
||||
if !out.is_null() {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(NEXT_TOKEN.fetch_add(1, Ordering::Relaxed)) };
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn register_reading(
|
||||
_: This,
|
||||
_device: *const c_void,
|
||||
_kind: u32,
|
||||
_threshold: f32,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
out: *mut u64,
|
||||
) -> HRESULT {
|
||||
token(out)
|
||||
}
|
||||
/// Enumerating existing devices finds none, so the callback never runs.
|
||||
extern "system" fn register_device(
|
||||
_: This,
|
||||
_device: *const c_void,
|
||||
kind: u32,
|
||||
_status: u32,
|
||||
_enumeration: u32,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
out: *mut u64,
|
||||
) -> HRESULT {
|
||||
tracing::info!(
|
||||
kind = format_args!("{kind:#x}"),
|
||||
"input device callback: no devices"
|
||||
);
|
||||
token(out)
|
||||
}
|
||||
/// Guide button and keyboard layout callbacks.
|
||||
extern "system" fn register_other(
|
||||
_: This,
|
||||
_device: *const c_void,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
out: *mut u64,
|
||||
) -> HRESULT {
|
||||
token(out)
|
||||
}
|
||||
extern "system" fn stop_callback(_: This, _token: u64) {}
|
||||
extern "system" fn unregister_callback(_: This, _token: u64, _timeout: u64) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Dispatcher and aggregate device: not needed while nothing is connected.
|
||||
extern "system" fn create_dispatcher(_: This, out: Out) -> HRESULT {
|
||||
tracing::warn!("input dispatcher not implemented");
|
||||
fail(out, E_NOTIMPL)
|
||||
}
|
||||
extern "system" fn create_aggregate(_: This, _kind: u32, out: Out) -> HRESULT {
|
||||
tracing::warn!("aggregate input device not implemented");
|
||||
fail(out, E_NOTIMPL)
|
||||
}
|
||||
/// Lookup by id, object, platform handle or platform string.
|
||||
extern "system" fn find_device(_: This, _value: *const c_void, out: Out) -> HRESULT {
|
||||
fail(out, DEVICE_NOT_FOUND)
|
||||
}
|
||||
extern "system" fn enable_oem_device(
|
||||
_: This,
|
||||
_vendor: u16,
|
||||
_product: u16,
|
||||
_interface: u8,
|
||||
_collection: u8,
|
||||
) -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
extern "system" fn set_focus_policy(_: This, _policy: u32) {}
|
||||
|
||||
static VTABLE: Vtable = Vtable([
|
||||
query_interface as *const (), // 0x00
|
||||
add_ref as *const (), // 0x08 AddRef
|
||||
add_ref as *const (), // 0x10 Release: the object is static
|
||||
timestamp as *const (), // 0x18
|
||||
current_reading as *const (), // 0x20
|
||||
relative_reading as *const (), // 0x28 next
|
||||
relative_reading as *const (), // 0x30 previous
|
||||
temporal_reading as *const (), // 0x38
|
||||
register_reading as *const (), // 0x40
|
||||
register_device as *const (), // 0x48
|
||||
register_other as *const (), // 0x50 guide button
|
||||
register_other as *const (), // 0x58 keyboard layout
|
||||
stop_callback as *const (), // 0x60
|
||||
unregister_callback as *const (), // 0x68
|
||||
create_dispatcher as *const (), // 0x70
|
||||
create_aggregate as *const (), // 0x78
|
||||
find_device as *const (), // 0x80 by id
|
||||
find_device as *const (), // 0x88 by object
|
||||
find_device as *const (), // 0x90 by platform handle
|
||||
find_device as *const (), // 0x98 by platform string
|
||||
enable_oem_device as *const (), // 0xa0
|
||||
set_focus_policy as *const (), // 0xa8
|
||||
]);
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "gameinput",
|
||||
dlls: &["gameinput.dll"],
|
||||
// Titles import it by ordinal only.
|
||||
exports: vec![HleExport {
|
||||
name: "#1",
|
||||
address: GameInputCreate as *const () as usize,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::HleResolver;
|
||||
use crate::HostPolicy;
|
||||
use victory_loader::Provenance;
|
||||
use victory_pe::ImportSymbol;
|
||||
|
||||
fn slot<F: Copy>(object: This, offset: usize) -> F {
|
||||
// SAFETY: `object` is ours.
|
||||
let f = unsafe { (*object).vtable.0[offset / 8] };
|
||||
// SAFETY: the caller names the slot's signature.
|
||||
unsafe { std::mem::transmute_copy(&f) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinal_one_resolves_to_create() {
|
||||
let r = HleResolver::new(HostPolicy::none());
|
||||
assert_eq!(
|
||||
r.classify("GameInput.dll", &ImportSymbol::Ordinal(1)),
|
||||
Some(Provenance::Hle)
|
||||
);
|
||||
assert_eq!(r.classify("GameInput.dll", &ImportSymbol::Ordinal(2)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_sees_no_devices() {
|
||||
type Register = extern "system" fn(
|
||||
This,
|
||||
*const c_void,
|
||||
u32,
|
||||
u32,
|
||||
u32,
|
||||
*mut c_void,
|
||||
*const c_void,
|
||||
*mut u64,
|
||||
) -> HRESULT;
|
||||
type Reading = extern "system" fn(This, u32, *const c_void, Out) -> HRESULT;
|
||||
type Find = extern "system" fn(This, *const c_void, Out) -> HRESULT;
|
||||
|
||||
let mut input = std::ptr::null();
|
||||
assert_eq!(GameInputCreate(&mut input), S_OK);
|
||||
assert!(!input.is_null());
|
||||
|
||||
let mut token = 0;
|
||||
let register = slot::<Register>(input, 0x48);
|
||||
let null = std::ptr::null_mut();
|
||||
assert_eq!(
|
||||
register(input, null, 0x40130, 1, 1, null, null, &mut token),
|
||||
S_OK
|
||||
);
|
||||
assert_ne!(token, 0);
|
||||
|
||||
let mut out = 0x1234 as *const c_void;
|
||||
let reading = slot::<Reading>(input, 0x20);
|
||||
assert_eq!(reading(input, 4, null, &mut out), READING_NOT_FOUND);
|
||||
assert!(out.is_null());
|
||||
out = 0x1234 as *const c_void;
|
||||
let find = slot::<Find>(input, 0x80);
|
||||
assert_eq!(find(input, null, &mut out), DEVICE_NOT_FOUND);
|
||||
assert!(out.is_null());
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,13 @@
|
||||
//! Only the differences live here; everything else passes through to the
|
||||
//! host (see `HostPolicy`).
|
||||
#![allow(non_snake_case)]
|
||||
// Title code calls these through its import table, passing pointers the real
|
||||
// API would trust.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::ffi::{CStr, c_void};
|
||||
|
||||
use crate::{HleModule, hle_export, runtime};
|
||||
use crate::{HleModule, HostPolicy, hle_export, registry, runtime};
|
||||
|
||||
/// `GetModuleHandleW(NULL)` must return the title's image, not our exe.
|
||||
pub extern "system" fn GetModuleHandleW(name: *const u16) -> *mut c_void {
|
||||
@@ -24,6 +27,207 @@ pub extern "system" fn GetModuleHandleA(name: *const u8) -> *mut c_void {
|
||||
host::get_module_handle_a(name)
|
||||
}
|
||||
|
||||
/// A title image's path is its original file, not our cache copy;
|
||||
/// `NULL` means the title's exe.
|
||||
pub extern "system" fn GetModuleFileNameW(module: *mut c_void, out: *mut u16, size: u32) -> u32 {
|
||||
let Some(path) = title_path(module) else {
|
||||
return host::get_module_file_name_w(module, out, size);
|
||||
};
|
||||
let wide: Vec<u16> = path.encode_utf16().collect();
|
||||
// SAFETY: the title passes a buffer of `size` characters.
|
||||
copy_truncated(&wide, unsafe {
|
||||
std::slice::from_raw_parts_mut(out, size as usize)
|
||||
})
|
||||
}
|
||||
|
||||
/// See [`GetModuleFileNameW`].
|
||||
pub extern "system" fn GetModuleFileNameA(module: *mut c_void, out: *mut u8, size: u32) -> u32 {
|
||||
let Some(path) = title_path(module) else {
|
||||
return host::get_module_file_name_a(module, out, size);
|
||||
};
|
||||
// SAFETY: the title passes a buffer of `size` bytes.
|
||||
copy_truncated(path.as_bytes(), unsafe {
|
||||
std::slice::from_raw_parts_mut(out, size as usize)
|
||||
})
|
||||
}
|
||||
|
||||
fn title_path(module: *mut c_void) -> Option<String> {
|
||||
let base = if module.is_null() {
|
||||
runtime::main_image()?
|
||||
} else {
|
||||
module as usize
|
||||
};
|
||||
Some(runtime::image_path(base)?.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
/// `GetModuleFileName`'s contract: copy with a NUL; if it does not fit,
|
||||
/// truncate to the buffer, report `ERROR_INSUFFICIENT_BUFFER` and return
|
||||
/// the buffer size.
|
||||
fn copy_truncated<T: Copy + Default>(text: &[T], out: &mut [T]) -> u32 {
|
||||
let Some(room) = out.len().checked_sub(1) else {
|
||||
host::set_last_error(ERROR_INSUFFICIENT_BUFFER);
|
||||
return 0;
|
||||
};
|
||||
let n = text.len().min(room);
|
||||
out[..n].copy_from_slice(&text[..n]);
|
||||
out[n] = T::default();
|
||||
if n < text.len() {
|
||||
host::set_last_error(ERROR_INSUFFICIENT_BUFFER);
|
||||
return out.len() as u32;
|
||||
}
|
||||
n as u32
|
||||
}
|
||||
|
||||
const ERROR_INSUFFICIENT_BUFFER: u32 = 122;
|
||||
|
||||
/// Console-only DLLs we implement load as a pseudo handle (titles load
|
||||
/// `xgameruntime.dll` this way); anything else loads on the host.
|
||||
pub extern "system" fn LoadLibraryExA(
|
||||
name: *const u8,
|
||||
file: *mut c_void,
|
||||
flags: u32,
|
||||
) -> *mut c_void {
|
||||
if !name.is_null() {
|
||||
// SAFETY: the title passes a NUL-terminated file name.
|
||||
let text = unsafe { CStr::from_ptr(name.cast()) }.to_string_lossy();
|
||||
if let Some(handle) = console_module(&text) {
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
host::load_library_ex_a(name, file, flags)
|
||||
}
|
||||
|
||||
/// See [`LoadLibraryExA`].
|
||||
pub extern "system" fn LoadLibraryExW(
|
||||
name: *const u16,
|
||||
file: *mut c_void,
|
||||
flags: u32,
|
||||
) -> *mut c_void {
|
||||
if !name.is_null() {
|
||||
// SAFETY: the title passes a NUL-terminated file name.
|
||||
let text = unsafe {
|
||||
let len = (0..).take_while(|&i| *name.add(i) != 0).count();
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(name, len))
|
||||
};
|
||||
if let Some(handle) = console_module(&text) {
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
host::load_library_ex_w(name, file, flags)
|
||||
}
|
||||
|
||||
pub extern "system" fn LoadLibraryA(name: *const u8) -> *mut c_void {
|
||||
LoadLibraryExA(name, std::ptr::null_mut(), 0)
|
||||
}
|
||||
|
||||
pub extern "system" fn LoadLibraryW(name: *const u16) -> *mut c_void {
|
||||
LoadLibraryExW(name, std::ptr::null_mut(), 0)
|
||||
}
|
||||
|
||||
/// Looks up our implementations behind a pseudo handle; real modules go to
|
||||
/// the host.
|
||||
pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void {
|
||||
let Some(m) = registry().iter().find(|m| handle(m) == module) else {
|
||||
return host::get_proc_address(module, name);
|
||||
};
|
||||
// Values below 0x10000 are ordinals; we export by name only.
|
||||
if (name as usize) < 0x1_0000 {
|
||||
tracing::warn!(
|
||||
module = m.name,
|
||||
ordinal = name as usize,
|
||||
"GetProcAddress by ordinal"
|
||||
);
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
// SAFETY: not an ordinal, so the title passes a NUL-terminated name.
|
||||
let name = unsafe { CStr::from_ptr(name.cast()) }.to_string_lossy();
|
||||
match m.exports.iter().find(|e| e.name == name) {
|
||||
Some(e) => e.address as *mut c_void,
|
||||
None => {
|
||||
tracing::warn!(module = m.name, %name, "GetProcAddress: not implemented");
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "system" fn FreeLibrary(module: *mut c_void) -> i32 {
|
||||
if registry().iter().any(|m| handle(m) == module) {
|
||||
return 1;
|
||||
}
|
||||
host::free_library(module)
|
||||
}
|
||||
|
||||
/// Title debug output goes to our log (no debugger needs to be attached).
|
||||
pub extern "system" fn OutputDebugStringA(text: *const u8) {
|
||||
if !text.is_null() {
|
||||
// SAFETY: the title passes a NUL-terminated string.
|
||||
let text = unsafe { CStr::from_ptr(text.cast()) }.to_string_lossy();
|
||||
tracing::info!(target: "title", "{}", text.trim_end());
|
||||
}
|
||||
}
|
||||
|
||||
/// See [`OutputDebugStringA`].
|
||||
pub extern "system" fn OutputDebugStringW(text: *const u16) {
|
||||
if !text.is_null() {
|
||||
// SAFETY: the title passes a NUL-terminated string.
|
||||
let text = unsafe {
|
||||
let len = (0..).take_while(|&i| *text.add(i) != 0).count();
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(text, len))
|
||||
};
|
||||
tracing::info!(target: "title", "{}", text.trim_end());
|
||||
}
|
||||
}
|
||||
|
||||
/// The CRT's `exit`, through which the title's entry point returns: logs
|
||||
/// the code and the caller, then exits on the host.
|
||||
pub extern "C" fn exit(code: i32) -> ! {
|
||||
tracing::warn!(code, from = %host::callers(), "title exits");
|
||||
host::exit(code)
|
||||
}
|
||||
|
||||
/// The CRT's `abort` (also reached from `terminate`): logged like [`exit`].
|
||||
pub extern "C" fn abort() -> ! {
|
||||
tracing::error!(from = %host::callers(), "title aborts");
|
||||
host::abort()
|
||||
}
|
||||
|
||||
/// The CRT's `terminate` and the STL's invalid-argument exit: logged, then
|
||||
/// the host's `abort`.
|
||||
pub extern "C" fn terminate() -> ! {
|
||||
tracing::error!(from = %host::callers(), "title calls terminate");
|
||||
host::abort()
|
||||
}
|
||||
|
||||
/// See [`terminate`].
|
||||
pub extern "C" fn _invalid_parameter_noinfo_noreturn() -> ! {
|
||||
tracing::error!(from = %host::callers(), "title passed an invalid parameter");
|
||||
host::abort()
|
||||
}
|
||||
|
||||
/// See [`exit`]; only the current process is logged.
|
||||
pub extern "system" fn TerminateProcess(process: *mut c_void, code: u32) -> i32 {
|
||||
if process as isize == -1 {
|
||||
tracing::warn!(code, from = %host::callers(), "title terminates the process");
|
||||
}
|
||||
host::terminate_process(process, code)
|
||||
}
|
||||
|
||||
/// The pseudo handle of one of our modules: its address, never a real image.
|
||||
fn handle(m: &HleModule) -> *mut c_void {
|
||||
m as *const HleModule as *mut c_void
|
||||
}
|
||||
|
||||
fn console_module(path: &str) -> Option<*mut c_void> {
|
||||
let file = path.rsplit(['\\', '/']).next().unwrap_or(path);
|
||||
// DLLs the host has too are real host modules, whatever `--strict` says.
|
||||
if HostPolicy::default().allows(file) {
|
||||
return None;
|
||||
}
|
||||
let m = registry().iter().find(|m| m.serves(file))?;
|
||||
tracing::info!(dll = file, "loaded as a pseudo module");
|
||||
Some(handle(m))
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "kernel",
|
||||
@@ -31,8 +235,29 @@ pub(crate) fn module() -> HleModule {
|
||||
"kernel32.dll",
|
||||
"kernelbase.dll",
|
||||
"api-ms-win-core-libraryloader-*",
|
||||
"api-ms-win-core-processthreads-*",
|
||||
"api-ms-win-core-debug-*",
|
||||
"api-ms-win-crt-runtime-*",
|
||||
],
|
||||
exports: vec![
|
||||
hle_export!(GetModuleHandleW),
|
||||
hle_export!(GetModuleHandleA),
|
||||
hle_export!(GetModuleFileNameW),
|
||||
hle_export!(GetModuleFileNameA),
|
||||
hle_export!(LoadLibraryExA),
|
||||
hle_export!(LoadLibraryExW),
|
||||
hle_export!(LoadLibraryA),
|
||||
hle_export!(LoadLibraryW),
|
||||
hle_export!(GetProcAddress),
|
||||
hle_export!(FreeLibrary),
|
||||
hle_export!(OutputDebugStringA),
|
||||
hle_export!(OutputDebugStringW),
|
||||
hle_export!(exit),
|
||||
hle_export!(abort),
|
||||
hle_export!(terminate),
|
||||
hle_export!(_invalid_parameter_noinfo_noreturn),
|
||||
hle_export!(TerminateProcess),
|
||||
],
|
||||
exports: vec![hle_export!(GetModuleHandleW), hle_export!(GetModuleHandleA)],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,14 +265,105 @@ pub(crate) fn module() -> HleModule {
|
||||
mod host {
|
||||
use std::ffi::c_void;
|
||||
|
||||
use windows_sys::Win32::Foundation::{FreeLibrary, SetLastError};
|
||||
use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace;
|
||||
use windows_sys::Win32::System::LibraryLoader::{
|
||||
GetModuleFileNameA, GetModuleFileNameW, GetModuleHandleA, GetModuleHandleW, GetProcAddress,
|
||||
LoadLibraryExA, LoadLibraryExW,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::TerminateProcess;
|
||||
|
||||
unsafe extern "C" {
|
||||
#[link_name = "exit"]
|
||||
fn crt_exit(code: i32) -> !;
|
||||
#[link_name = "abort"]
|
||||
fn crt_abort() -> !;
|
||||
}
|
||||
|
||||
// SAFETY (every function): forwarding the title's own arguments to the
|
||||
// host API of the same name.
|
||||
|
||||
pub(super) fn get_module_handle_w(name: *const u16) -> *mut c_void {
|
||||
// SAFETY: forwarding the title's own argument to the host API.
|
||||
unsafe { windows_sys::Win32::System::LibraryLoader::GetModuleHandleW(name) }
|
||||
// SAFETY: see above.
|
||||
unsafe { GetModuleHandleW(name) }
|
||||
}
|
||||
|
||||
pub(super) fn get_module_handle_a(name: *const u8) -> *mut c_void {
|
||||
// SAFETY: forwarding the title's own argument to the host API.
|
||||
unsafe { windows_sys::Win32::System::LibraryLoader::GetModuleHandleA(name) }
|
||||
// SAFETY: see above.
|
||||
unsafe { GetModuleHandleA(name) }
|
||||
}
|
||||
|
||||
pub(super) fn get_module_file_name_w(module: *mut c_void, out: *mut u16, size: u32) -> u32 {
|
||||
// SAFETY: see above.
|
||||
unsafe { GetModuleFileNameW(module, out, size) }
|
||||
}
|
||||
|
||||
pub(super) fn get_module_file_name_a(module: *mut c_void, out: *mut u8, size: u32) -> u32 {
|
||||
// SAFETY: see above.
|
||||
unsafe { GetModuleFileNameA(module, out, size) }
|
||||
}
|
||||
|
||||
pub(super) fn set_last_error(code: u32) {
|
||||
// SAFETY: see above.
|
||||
unsafe { SetLastError(code) }
|
||||
}
|
||||
|
||||
pub(super) fn load_library_ex_a(name: *const u8, file: *mut c_void, flags: u32) -> *mut c_void {
|
||||
// SAFETY: see above.
|
||||
unsafe { LoadLibraryExA(name, file, flags) }
|
||||
}
|
||||
|
||||
pub(super) fn load_library_ex_w(
|
||||
name: *const u16,
|
||||
file: *mut c_void,
|
||||
flags: u32,
|
||||
) -> *mut c_void {
|
||||
// SAFETY: see above.
|
||||
unsafe { LoadLibraryExW(name, file, flags) }
|
||||
}
|
||||
|
||||
pub(super) fn get_proc_address(module: *mut c_void, name: *const u8) -> *mut c_void {
|
||||
// SAFETY: see above.
|
||||
unsafe { GetProcAddress(module, name) }.map_or(std::ptr::null_mut(), |f| f as *mut c_void)
|
||||
}
|
||||
|
||||
pub(super) fn free_library(module: *mut c_void) -> i32 {
|
||||
// SAFETY: see above.
|
||||
unsafe { FreeLibrary(module) }
|
||||
}
|
||||
|
||||
pub(super) fn exit(code: i32) -> ! {
|
||||
// SAFETY: see above.
|
||||
unsafe { crt_exit(code) }
|
||||
}
|
||||
|
||||
pub(super) fn abort() -> ! {
|
||||
// SAFETY: see above.
|
||||
unsafe { crt_abort() }
|
||||
}
|
||||
|
||||
pub(super) fn terminate_process(process: *mut c_void, code: u32) -> i32 {
|
||||
// SAFETY: see above.
|
||||
unsafe { TerminateProcess(process, code) }
|
||||
}
|
||||
|
||||
/// Our caller's callers, as `module+rva`.
|
||||
pub(super) fn callers() -> String {
|
||||
let mut frames = [std::ptr::null_mut(); 12];
|
||||
// SAFETY: fills at most `frames.len()` return addresses.
|
||||
let n = unsafe {
|
||||
RtlCaptureStackBackTrace(
|
||||
2,
|
||||
frames.len() as u32,
|
||||
frames.as_mut_ptr(),
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
let names: Vec<_> = frames[..usize::from(n)]
|
||||
.iter()
|
||||
.map(|&f| victory_loader::locate(f as usize))
|
||||
.collect();
|
||||
names.join(" < ")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,4 +378,70 @@ mod host {
|
||||
pub(super) fn get_module_handle_a(_: *const u8) -> *mut c_void {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
|
||||
pub(super) fn load_library_ex_a(_: *const u8, _: *mut c_void, _: u32) -> *mut c_void {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
|
||||
pub(super) fn get_module_file_name_w(_: *mut c_void, _: *mut u16, _: u32) -> u32 {
|
||||
0
|
||||
}
|
||||
|
||||
pub(super) fn get_module_file_name_a(_: *mut c_void, _: *mut u8, _: u32) -> u32 {
|
||||
0
|
||||
}
|
||||
|
||||
pub(super) fn set_last_error(_: u32) {}
|
||||
|
||||
pub(super) fn load_library_ex_w(_: *const u16, _: *mut c_void, _: u32) -> *mut c_void {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
|
||||
pub(super) fn get_proc_address(_: *mut c_void, _: *const u8) -> *mut c_void {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
|
||||
pub(super) fn free_library(_: *mut c_void) -> i32 {
|
||||
0
|
||||
}
|
||||
|
||||
pub(super) fn exit(code: i32) -> ! {
|
||||
std::process::exit(code)
|
||||
}
|
||||
|
||||
pub(super) fn abort() -> ! {
|
||||
std::process::abort()
|
||||
}
|
||||
|
||||
pub(super) fn terminate_process(_: *mut c_void, code: u32) -> i32 {
|
||||
std::process::exit(code as i32)
|
||||
}
|
||||
|
||||
pub(super) fn callers() -> String {
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn title_images_report_their_original_path() {
|
||||
let base = 0x7000_0000_0000;
|
||||
runtime::set_image_path(base, std::path::Path::new(r"C:\title\game.exe"));
|
||||
let module = base as *mut c_void;
|
||||
let mut buf = [0xFFFFu16; 32];
|
||||
let n = GetModuleFileNameW(module, buf.as_mut_ptr(), buf.len() as u32);
|
||||
assert_eq!(
|
||||
String::from_utf16_lossy(&buf[..n as usize]),
|
||||
r"C:\title\game.exe"
|
||||
);
|
||||
assert_eq!(buf[n as usize], 0);
|
||||
|
||||
// Too small: truncated, NUL-terminated, the buffer size returned.
|
||||
let mut small = [0u8; 4];
|
||||
assert_eq!(GetModuleFileNameA(module, small.as_mut_ptr(), 4), 4);
|
||||
assert_eq!(&small, &[b'C', b':', b'\\', 0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
//! The title's life cycle. A console title is never told it is closing:
|
||||
//! quitting it first suspends it (its suspend routines run, and it has a
|
||||
//! second to save) and then ends the process. Closing the title's window
|
||||
//! does the same here.
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Mutex, MutexGuard};
|
||||
use std::time::Duration;
|
||||
|
||||
use windows_sys::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, WPARAM};
|
||||
use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, HMENU};
|
||||
use windows_sys::core::{PCSTR, PCWSTR, w};
|
||||
|
||||
use crate::{HleModule, hle_export};
|
||||
|
||||
type Routine = extern "system" fn(quiesced: u8, context: *mut c_void);
|
||||
|
||||
/// Registration id, routine and context of each suspend routine.
|
||||
static ROUTINES: Mutex<Vec<(usize, Routine, usize)>> = Mutex::new(Vec::new());
|
||||
|
||||
fn routines() -> MutexGuard<'static, Vec<(usize, Routine, usize)>> {
|
||||
ROUTINES.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// How long the console lets suspend routines run before it ends the title.
|
||||
const SUSPEND_DEADLINE: Duration = Duration::from_secs(1);
|
||||
|
||||
const ERROR_INVALID_PARAMETER: u32 = 87;
|
||||
|
||||
pub extern "system" fn RegisterAppStateChangeNotification(
|
||||
routine: Option<Routine>,
|
||||
context: *mut c_void,
|
||||
registration: *mut usize,
|
||||
) -> u32 {
|
||||
let Some(routine) = routine else {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
};
|
||||
if registration.is_null() {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
}
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(1);
|
||||
let id = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
routines().push((id, routine, context as usize));
|
||||
// SAFETY: checked non-null; the title passes room for its registration.
|
||||
unsafe { registration.write(id) };
|
||||
0
|
||||
}
|
||||
|
||||
pub extern "system" fn UnregisterAppStateChangeNotification(registration: usize) {
|
||||
routines().retain(|&(id, ..)| id != registration);
|
||||
}
|
||||
|
||||
/// The window procedure a title window had before ours.
|
||||
const TITLE_PROC: PCWSTR = w!("victory.wndproc");
|
||||
|
||||
pub extern "system" fn CreateWindowExW(
|
||||
ex_style: u32,
|
||||
class: PCWSTR,
|
||||
name: PCWSTR,
|
||||
style: u32,
|
||||
x: i32,
|
||||
y: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
parent: HWND,
|
||||
menu: HMENU,
|
||||
instance: HINSTANCE,
|
||||
param: *const c_void,
|
||||
) -> HWND {
|
||||
// SAFETY: the title's own arguments, forwarded.
|
||||
let hwnd = unsafe {
|
||||
wm::CreateWindowExW(
|
||||
ex_style, class, name, style, x, y, width, height, parent, menu, instance, param,
|
||||
)
|
||||
};
|
||||
hook(hwnd);
|
||||
hwnd
|
||||
}
|
||||
|
||||
/// See [`CreateWindowExW`].
|
||||
pub extern "system" fn CreateWindowExA(
|
||||
ex_style: u32,
|
||||
class: PCSTR,
|
||||
name: PCSTR,
|
||||
style: u32,
|
||||
x: i32,
|
||||
y: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
parent: HWND,
|
||||
menu: HMENU,
|
||||
instance: HINSTANCE,
|
||||
param: *const c_void,
|
||||
) -> HWND {
|
||||
// SAFETY: the title's own arguments, forwarded.
|
||||
let hwnd = unsafe {
|
||||
wm::CreateWindowExA(
|
||||
ex_style, class, name, style, x, y, width, height, parent, menu, instance, param,
|
||||
)
|
||||
};
|
||||
hook(hwnd);
|
||||
hwnd
|
||||
}
|
||||
|
||||
/// Puts our procedure in front of the title's.
|
||||
fn hook(hwnd: HWND) {
|
||||
if hwnd.is_null() {
|
||||
return;
|
||||
}
|
||||
// SAFETY: a window this thread just created. The title's procedure is
|
||||
// stored before ours can run.
|
||||
unsafe {
|
||||
let title = wm::GetWindowLongPtrW(hwnd, wm::GWLP_WNDPROC);
|
||||
wm::SetPropW(hwnd, TITLE_PROC, title as *mut c_void);
|
||||
wm::SetWindowLongPtrW(hwnd, wm::GWLP_WNDPROC, window_proc as *const () as isize);
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn window_proc(
|
||||
hwnd: HWND,
|
||||
message: u32,
|
||||
wparam: WPARAM,
|
||||
lparam: LPARAM,
|
||||
) -> LRESULT {
|
||||
// A user close (close button, Alt+F4, window or taskbar menu); a
|
||||
// console title never sees one, nor a WM_CLOSE from it.
|
||||
if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_CLOSE as usize {
|
||||
quit();
|
||||
return 0;
|
||||
}
|
||||
// SAFETY: the procedure `hook` stored, called the way the system would.
|
||||
unsafe {
|
||||
let title = wm::GetPropW(hwnd, TITLE_PROC);
|
||||
if message == wm::WM_NCDESTROY {
|
||||
wm::RemovePropW(hwnd, TITLE_PROC);
|
||||
}
|
||||
let title = std::mem::transmute::<*mut c_void, wm::WNDPROC>(title);
|
||||
wm::CallWindowProcW(title, hwnd, message, wparam, lparam)
|
||||
}
|
||||
}
|
||||
|
||||
/// Suspends the title as the console would on quit, then ends the process.
|
||||
fn quit() {
|
||||
static QUITTING: AtomicBool = AtomicBool::new(false);
|
||||
if QUITTING.swap(true, Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let suspend = routines().clone();
|
||||
tracing::info!(routines = suspend.len(), "window closed: suspending the title");
|
||||
// Not on the window thread: titles hand the suspend to that thread and
|
||||
// wait for it inside the routine.
|
||||
std::thread::spawn(move || {
|
||||
for (_, routine, context) in suspend {
|
||||
routine(1, context as *mut c_void);
|
||||
}
|
||||
tracing::info!("title suspended; ending it");
|
||||
end();
|
||||
});
|
||||
std::thread::spawn(|| {
|
||||
std::thread::sleep(SUSPEND_DEADLINE);
|
||||
tracing::warn!("title did not finish suspending in time; ending it");
|
||||
end();
|
||||
});
|
||||
}
|
||||
|
||||
fn end() {
|
||||
// SAFETY: ends this process, as the console ends a suspended title.
|
||||
unsafe { TerminateProcess(GetCurrentProcess(), 0) };
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "lifecycle",
|
||||
dlls: &[
|
||||
"api-ms-win-core-psm-appnotify-*",
|
||||
"ext-ms-win-rtcore-ntuser-window-*",
|
||||
],
|
||||
exports: vec![
|
||||
hle_export!(RegisterAppStateChangeNotification),
|
||||
hle_export!(UnregisterAppStateChangeNotification),
|
||||
hle_export!(CreateWindowExW),
|
||||
hle_export!(CreateWindowExA),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
extern "system" fn noop(_: u8, _: *mut c_void) {}
|
||||
|
||||
#[test]
|
||||
fn registrations_come_and_go() {
|
||||
let (mut a, mut b) = (0, 0);
|
||||
assert_eq!(
|
||||
RegisterAppStateChangeNotification(Some(noop), std::ptr::null_mut(), &mut a),
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
RegisterAppStateChangeNotification(Some(noop), std::ptr::null_mut(), &mut b),
|
||||
0
|
||||
);
|
||||
UnregisterAppStateChangeNotification(a);
|
||||
let left: Vec<_> = routines().iter().map(|r| r.0).collect();
|
||||
assert_eq!(left, [b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hooked_windows_still_reach_the_title_procedure() {
|
||||
let null = std::ptr::null_mut();
|
||||
let hwnd = CreateWindowExW(
|
||||
0,
|
||||
w!("STATIC"),
|
||||
w!("before"),
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
10,
|
||||
10,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
std::ptr::null(),
|
||||
);
|
||||
assert!(!hwnd.is_null());
|
||||
let mut text = [0u16; 16];
|
||||
// SAFETY: our window; the buffer holds 16 characters.
|
||||
unsafe {
|
||||
wm::SetWindowTextW(hwnd, w!("after"));
|
||||
let n = wm::GetWindowTextW(hwnd, text.as_mut_ptr(), 16);
|
||||
assert_eq!(String::from_utf16_lossy(&text[..n as usize]), "after");
|
||||
assert!(!wm::GetPropW(hwnd, TITLE_PROC).is_null());
|
||||
wm::DestroyWindow(hwnd);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,15 +5,41 @@
|
||||
//! Run `victory census` over your titles to see what is still missing.
|
||||
//!
|
||||
//! Planned areas (driven by census results, not by completeness):
|
||||
//! `xmem` (console memory types, GPU-visible allocations), `file` (package
|
||||
//! paths), `thread` (TLS callbacks for title threads), `d3d12x` (bridge to
|
||||
//! `victory-gpu`), `xaudio2`, `gameinput`, `xuser`/`xstore` stubs.
|
||||
//! `file` (package paths), `thread` (TLS callbacks for title threads),
|
||||
//! `xaudio2`, `xstore` stubs.
|
||||
|
||||
pub mod audio;
|
||||
pub mod d3d12x;
|
||||
#[cfg(windows)]
|
||||
pub mod files;
|
||||
pub mod gameinput;
|
||||
pub mod kernel;
|
||||
#[cfg(windows)]
|
||||
pub mod lifecycle;
|
||||
pub mod storage;
|
||||
pub mod xasync;
|
||||
pub mod xgame;
|
||||
pub mod xgameruntime;
|
||||
#[cfg(windows)]
|
||||
pub mod xmem;
|
||||
pub mod xsystem;
|
||||
pub mod xuser;
|
||||
|
||||
use crate::HleModule;
|
||||
|
||||
pub(crate) fn all() -> Vec<HleModule> {
|
||||
vec![kernel::module(), xgameruntime::module()]
|
||||
let mut all = vec![
|
||||
kernel::module(),
|
||||
xgameruntime::module(),
|
||||
gameinput::module(),
|
||||
d3d12x::module(),
|
||||
audio::module(),
|
||||
];
|
||||
#[cfg(windows)]
|
||||
all.push(files::module());
|
||||
#[cfg(windows)]
|
||||
all.push(lifecycle::module());
|
||||
#[cfg(windows)]
|
||||
all.push(xmem::module());
|
||||
all
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
//! Persistent local storage: a host folder of the title's own
|
||||
//! (`runtime::Title::storage`, under the data directory, never the cache)
|
||||
//! with the quota its manifest declares, seen by the title as a drive
|
||||
//! (`files`).
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use super::xasync::{self, AsyncBlock, E_ABORT};
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, S_OK, add_ref, missing, put,
|
||||
put_string,
|
||||
};
|
||||
use crate::runtime;
|
||||
|
||||
pub const PROVIDER: Guid = Guid::new(
|
||||
0xf4fa_f4d4,
|
||||
0x2d04,
|
||||
0x4fce,
|
||||
[0xb3, 0xe0, 0x47, 0x4a, 0x71, 0x3a, 0x3e, 0x84],
|
||||
);
|
||||
pub const IID: Guid = Guid::new(
|
||||
0xd294_11df,
|
||||
0x0794,
|
||||
0x4553,
|
||||
[0x8b, 0x27, 0x95, 0xfc, 0x02, 0xd0, 0xf7, 0x5d],
|
||||
);
|
||||
|
||||
pub static OBJECT: Object = Object::new("persistent local storage", &VTABLE);
|
||||
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT)];
|
||||
|
||||
type This = *const Object;
|
||||
|
||||
/// The path titles get: the root of a virtual drive over the folder. On the
|
||||
/// console storage is a drive of its own, and titles rely on it: Minecraft
|
||||
/// keeps only what precedes the path's last `:\` and mounts that as a
|
||||
/// drive, so a host folder such as `C:\Users\..` would make it write to the
|
||||
/// root of `C:`. None (the path calls fail) before the title is set.
|
||||
fn folder() -> Option<String> {
|
||||
let storage = runtime::title().storage;
|
||||
if storage.as_os_str().is_empty() {
|
||||
return None;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
return super::files::mount(&storage).map(|letter| format!("{letter}:\\"));
|
||||
#[cfg(not(windows))]
|
||||
None
|
||||
}
|
||||
|
||||
extern "system" fn path_size(_: This, out: *mut usize) -> HRESULT {
|
||||
match folder() {
|
||||
Some(path) => put(out, path.len() + 1),
|
||||
None => NOT_SUPPORTED,
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn path(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
|
||||
match folder() {
|
||||
Some(path) => put_string(&path, size, buffer, used),
|
||||
None => NOT_SUPPORTED,
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct SpaceInfo {
|
||||
/// Writable now.
|
||||
pub available_free: u64,
|
||||
/// Left in the quota.
|
||||
pub total_free: u64,
|
||||
pub used: u64,
|
||||
/// The quota.
|
||||
pub total: u64,
|
||||
}
|
||||
|
||||
fn used_bytes(dir: &Path) -> u64 {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return 0;
|
||||
};
|
||||
entries
|
||||
.flatten()
|
||||
.map(|e| match e.metadata() {
|
||||
Ok(m) if m.is_dir() => used_bytes(&e.path()),
|
||||
Ok(m) => m.len(),
|
||||
Err(_) => 0,
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn space() -> SpaceInfo {
|
||||
let title = runtime::title();
|
||||
let used = used_bytes(&title.storage);
|
||||
let free = title.storage_bytes.saturating_sub(used);
|
||||
// shortcut: the host disk's free space is not checked; do so if a title
|
||||
// fills its quota on a nearly full disk.
|
||||
SpaceInfo {
|
||||
available_free: free,
|
||||
total_free: free,
|
||||
used,
|
||||
total: title.storage_bytes,
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn space_info(_: This, out: *mut SpaceInfo) -> HRESULT {
|
||||
put(out, space())
|
||||
}
|
||||
|
||||
/// Tells our prompts apart from other calls on the same block.
|
||||
static PROMPT: u8 = 0;
|
||||
|
||||
/// There is nobody to ask: granted when the quota has room, else declined.
|
||||
extern "system" fn prompt_for_space(_: This, bytes: u64, block: *mut AsyncBlock) -> HRESULT {
|
||||
let hr = if bytes <= space().total_free {
|
||||
S_OK
|
||||
} else {
|
||||
E_ABORT
|
||||
};
|
||||
xasync::finished(block, (&raw const PROMPT).cast(), hr)
|
||||
}
|
||||
|
||||
extern "system" fn prompt_result(_: This, block: *mut AsyncBlock) -> HRESULT {
|
||||
let none = std::ptr::null_mut();
|
||||
xasync::XAsyncGetResult(block, (&raw const PROMPT).cast(), 0, none, none.cast())
|
||||
}
|
||||
|
||||
static VTABLE: Methods<8> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
path_size as *const (), // 0x18
|
||||
path as *const (), // 0x20
|
||||
space_info as *const (), // 0x28
|
||||
prompt_for_space as *const (), // 0x30
|
||||
prompt_result as *const (), // 0x38
|
||||
]);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::modules::xgameruntime::method;
|
||||
|
||||
#[test]
|
||||
fn serves_a_drive_over_the_title_folder_and_its_quota() {
|
||||
type Size = extern "system" fn(This, *mut usize) -> HRESULT;
|
||||
type Get = extern "system" fn(This, usize, *mut u8, *mut usize) -> HRESULT;
|
||||
type Space = extern "system" fn(This, *mut SpaceInfo) -> HRESULT;
|
||||
type Prompt = extern "system" fn(This, u64, *mut AsyncBlock) -> HRESULT;
|
||||
type Result = extern "system" fn(This, *mut AsyncBlock) -> HRESULT;
|
||||
let this: This = &OBJECT;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("save.dat"), [0u8; 100]).unwrap();
|
||||
runtime::set_title(runtime::Title {
|
||||
id: 1,
|
||||
storage: dir.path().to_owned(),
|
||||
storage_bytes: 1000,
|
||||
});
|
||||
|
||||
// The path is a drive root, never the host folder.
|
||||
let mut size = 0;
|
||||
assert_eq!(method::<Size>(&OBJECT, 0x18)(this, &mut size), S_OK);
|
||||
assert_eq!(size, 4, "X:\\ and its NUL");
|
||||
let (mut buffer, mut used) = ([0u8; 4], 0);
|
||||
let get = method::<Get>(&OBJECT, 0x20);
|
||||
assert_eq!(get(this, 4, buffer.as_mut_ptr(), &mut used), S_OK);
|
||||
let drive = std::str::from_utf8(&buffer[..3]).unwrap();
|
||||
assert!(drive.ends_with(":\\"), "{drive}");
|
||||
// Title file calls on it reach the folder.
|
||||
let path = format!("{drive}save.dat\0");
|
||||
let mut attributes = [0u8; 36];
|
||||
let get_attributes = super::super::files::GetFileAttributesExW;
|
||||
let wide: Vec<u16> = path.encode_utf16().collect();
|
||||
assert_ne!(
|
||||
get_attributes(wide.as_ptr(), 0, attributes.as_mut_ptr().cast()),
|
||||
0
|
||||
);
|
||||
|
||||
let mut info = SpaceInfo {
|
||||
available_free: 0,
|
||||
total_free: 0,
|
||||
used: 0,
|
||||
total: 0,
|
||||
};
|
||||
assert_eq!(method::<Space>(&OBJECT, 0x28)(this, &mut info), S_OK);
|
||||
assert_eq!((info.used, info.total_free, info.total), (100, 900, 1000));
|
||||
|
||||
let prompt = method::<Prompt>(&OBJECT, 0x30);
|
||||
let result = method::<Result>(&OBJECT, 0x38);
|
||||
for (bytes, expect) in [(900, S_OK), (901, E_ABORT)] {
|
||||
let mut block = AsyncBlock {
|
||||
queue: std::ptr::null(),
|
||||
context: std::ptr::null_mut(),
|
||||
callback: None,
|
||||
internal: [0; 4],
|
||||
};
|
||||
assert_eq!(prompt(this, bytes, &mut block), S_OK);
|
||||
assert_eq!(xasync::XAsyncGetStatus(&mut block, true), expect);
|
||||
assert_eq!(result(this, &mut block), expect, "{bytes} bytes");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,959 @@
|
||||
//! XTaskQueue and XAsync: the runtime's callback queues and async-call
|
||||
//! blocks, served as the task-queue provider's object from `QueryApiImpl`.
|
||||
//!
|
||||
//! As documented for the public API: a queue has a work port and a
|
||||
//! completion port, each dispatched manually (the title calls dispatch),
|
||||
//! on a thread pool, serialised on one thread, or immediately on the
|
||||
//! submitting thread. A null queue handle means the process queue. An
|
||||
//! async block's system area holds its status and result size, so both
|
||||
//! stay readable after our state for the call is gone.
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::ffi::c_void;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard};
|
||||
use std::time::Duration;
|
||||
|
||||
use super::xgameruntime::{Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing};
|
||||
|
||||
/// The task-queue provider; it is also the interface id titles ask for.
|
||||
pub const PROVIDER: Guid = Guid {
|
||||
data1: 0x073b_7dcb,
|
||||
data2: 0x1fcf,
|
||||
data3: 0x4030,
|
||||
data4: [0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28],
|
||||
};
|
||||
|
||||
pub const E_PENDING: HRESULT = 0x8000_000A_u32 as i32;
|
||||
pub const E_ABORT: HRESULT = 0x8000_4004_u32 as i32;
|
||||
pub const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32;
|
||||
pub const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32;
|
||||
pub const E_NOT_SUFFICIENT_BUFFER: HRESULT = 0x8007_007A_u32 as i32;
|
||||
pub const E_ILLEGAL_METHOD_CALL: HRESULT = 0x8000_000E_u32 as i32;
|
||||
|
||||
const WORK: u32 = 0;
|
||||
const COMPLETION: u32 = 1;
|
||||
const INFINITE: u32 = u32::MAX;
|
||||
|
||||
type Callback = extern "system" fn(*mut c_void, bool);
|
||||
type MonitorCallback = extern "system" fn(*mut c_void, *const Queue, u32);
|
||||
type TerminatedCallback = extern "system" fn(*mut c_void);
|
||||
type CompletionRoutine = extern "system" fn(*mut AsyncBlock);
|
||||
type Provider = extern "system" fn(u32, *const ProviderData) -> HRESULT;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
Manual,
|
||||
ThreadPool,
|
||||
Serialized,
|
||||
Immediate,
|
||||
}
|
||||
|
||||
impl Mode {
|
||||
fn from_raw(mode: u32) -> Option<Mode> {
|
||||
[
|
||||
Mode::Manual,
|
||||
Mode::ThreadPool,
|
||||
Mode::Serialized,
|
||||
Mode::Immediate,
|
||||
]
|
||||
.get(mode as usize)
|
||||
.copied()
|
||||
}
|
||||
}
|
||||
|
||||
/// A title callback and its context (addresses, so tasks can cross threads).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Task {
|
||||
context: usize,
|
||||
callback: usize,
|
||||
}
|
||||
|
||||
impl Task {
|
||||
fn new(context: *mut c_void, callback: Callback) -> Task {
|
||||
Task {
|
||||
context: context as usize,
|
||||
callback: callback as usize,
|
||||
}
|
||||
}
|
||||
|
||||
fn run(self, canceled: bool) {
|
||||
// SAFETY: built from a `Callback` in `new`.
|
||||
let callback: Callback = unsafe { std::mem::transmute(self.callback) };
|
||||
callback(self.context as *mut c_void, canceled);
|
||||
}
|
||||
}
|
||||
|
||||
struct Port {
|
||||
mode: Mode,
|
||||
tasks: Mutex<VecDeque<Task>>,
|
||||
ready: Condvar,
|
||||
}
|
||||
|
||||
impl Port {
|
||||
fn new(mode: Mode) -> Arc<Port> {
|
||||
let port = Arc::new(Port {
|
||||
mode,
|
||||
tasks: Mutex::default(),
|
||||
ready: Condvar::new(),
|
||||
});
|
||||
if mode == Mode::Serialized {
|
||||
// shortcut: the worker lives as long as the process, even after
|
||||
// the queue closes; join it on close if titles churn queues.
|
||||
let worker = port.clone();
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
if let Some(task) = worker.take(INFINITE) {
|
||||
task.run(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
port
|
||||
}
|
||||
|
||||
fn submit(&self, task: Task) {
|
||||
match self.mode {
|
||||
Mode::Immediate => task.run(false),
|
||||
// shortcut: a thread per callback, not a pool; fine at startup
|
||||
// rates, pool them if a title submits thousands per frame.
|
||||
Mode::ThreadPool => drop(std::thread::spawn(move || task.run(false))),
|
||||
Mode::Manual | Mode::Serialized => {
|
||||
lock(&self.tasks).push_back(task);
|
||||
self.ready.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The next queued task, waiting up to `timeout_ms`.
|
||||
fn take(&self, timeout_ms: u32) -> Option<Task> {
|
||||
let tasks = lock(&self.tasks);
|
||||
let mut tasks = if timeout_ms == INFINITE {
|
||||
self.ready
|
||||
.wait_while(tasks, |t| t.is_empty())
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
} else {
|
||||
let timeout = Duration::from_millis(timeout_ms.into());
|
||||
self.ready
|
||||
.wait_timeout_while(tasks, timeout, |t| t.is_empty())
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.0
|
||||
};
|
||||
tasks.pop_front()
|
||||
}
|
||||
}
|
||||
|
||||
/// A queue handle is `Arc::into_raw` of this; duplicating and closing a
|
||||
/// handle add and drop a reference.
|
||||
pub struct Queue {
|
||||
ports: [Arc<Port>; 2],
|
||||
monitors: Mutex<Vec<(u64, usize, usize)>>,
|
||||
terminated: AtomicBool,
|
||||
}
|
||||
|
||||
impl Queue {
|
||||
fn new(ports: [Arc<Port>; 2]) -> Arc<Queue> {
|
||||
Arc::new(Queue {
|
||||
ports,
|
||||
monitors: Mutex::default(),
|
||||
terminated: AtomicBool::new(false),
|
||||
})
|
||||
}
|
||||
|
||||
fn submit(self: &Arc<Self>, port: u32, delay_ms: u32, task: Task) -> HRESULT {
|
||||
if port > COMPLETION {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if self.terminated.load(Ordering::Acquire) {
|
||||
return E_ABORT;
|
||||
}
|
||||
if delay_ms == 0 {
|
||||
self.deliver(port, task);
|
||||
} else {
|
||||
let queue = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(delay_ms.into()));
|
||||
queue.deliver(port, task);
|
||||
});
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
fn deliver(self: &Arc<Self>, port: u32, task: Task) {
|
||||
self.ports[port as usize].submit(task);
|
||||
// Copied out: a monitor may unregister itself.
|
||||
let monitors = lock(&self.monitors).clone();
|
||||
for (_, context, callback) in monitors {
|
||||
// SAFETY: stored from a `MonitorCallback` in `register_monitor`.
|
||||
let callback: MonitorCallback = unsafe { std::mem::transmute(callback) };
|
||||
callback(context as *mut c_void, Arc::as_ptr(self), port);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// The process queue: `None` until first used (then a thread-pool queue),
|
||||
/// `Some(None)` once the title clears it.
|
||||
static PROCESS_QUEUE: Mutex<Option<Option<Arc<Queue>>>> = Mutex::new(None);
|
||||
|
||||
fn process_queue() -> Option<Arc<Queue>> {
|
||||
lock(&PROCESS_QUEUE)
|
||||
.get_or_insert_with(|| {
|
||||
Some(Queue::new([
|
||||
Port::new(Mode::ThreadPool),
|
||||
Port::new(Mode::ThreadPool),
|
||||
]))
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// A new reference to the queue behind `handle` (null: the process queue).
|
||||
fn queue(handle: *const Queue) -> Option<Arc<Queue>> {
|
||||
if handle.is_null() {
|
||||
return process_queue();
|
||||
}
|
||||
// SAFETY: a handle we returned, which the title has not closed.
|
||||
unsafe {
|
||||
Arc::increment_strong_count(handle);
|
||||
Some(Arc::from_raw(handle))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn XTaskQueueCreate(work: u32, completion: u32, out: *mut *const Queue) -> HRESULT {
|
||||
let (Some(work), Some(completion)) = (Mode::from_raw(work), Mode::from_raw(completion)) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let queue = Queue::new([Port::new(work), Port::new(completion)]);
|
||||
// SAFETY: checked non-null; the title passes room for a handle.
|
||||
unsafe { out.write(Arc::into_raw(queue)) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// A port handle points at the port, which its queue keeps alive.
|
||||
pub fn XTaskQueueGetPort(handle: *const Queue, port: u32, out: *mut *const c_void) -> HRESULT {
|
||||
let Some(queue) = queue(handle) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if port > COMPLETION || out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(Arc::as_ptr(&queue.ports[port as usize]).cast()) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub fn XTaskQueueCreateComposite(
|
||||
work: *const c_void,
|
||||
completion: *const c_void,
|
||||
out: *mut *const Queue,
|
||||
) -> HRESULT {
|
||||
if work.is_null() || completion.is_null() || out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let port = |p: *const c_void| {
|
||||
// SAFETY: a port handle from `XTaskQueueGetPort`, whose queue is open.
|
||||
unsafe {
|
||||
Arc::increment_strong_count(p.cast::<Port>());
|
||||
Arc::from_raw(p.cast::<Port>())
|
||||
}
|
||||
};
|
||||
let queue = Queue::new([port(work), port(completion)]);
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(Arc::into_raw(queue)) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub fn XTaskQueueDuplicateHandle(handle: *const Queue, out: *mut *const Queue) -> HRESULT {
|
||||
match queue(handle) {
|
||||
Some(queue) if !out.is_null() => {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(Arc::into_raw(queue)) };
|
||||
S_OK
|
||||
}
|
||||
_ => E_INVALIDARG,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn XTaskQueueCloseHandle(handle: *const Queue) {
|
||||
if !handle.is_null() {
|
||||
// SAFETY: a handle we returned; this drops its reference.
|
||||
unsafe { Arc::decrement_strong_count(handle) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one queued callback of a manual port; false if none came in time.
|
||||
pub fn XTaskQueueDispatch(handle: *const Queue, port: u32, timeout_ms: u32) -> bool {
|
||||
let Some(queue) = queue(handle) else {
|
||||
return false;
|
||||
};
|
||||
let Some(port) = queue.ports.get(port as usize) else {
|
||||
return false;
|
||||
};
|
||||
if port.mode != Mode::Manual {
|
||||
return false;
|
||||
}
|
||||
match port.take(timeout_ms) {
|
||||
Some(task) => {
|
||||
task.run(false);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn XTaskQueueSubmitDelayedCallback(
|
||||
handle: *const Queue,
|
||||
port: u32,
|
||||
delay_ms: u32,
|
||||
context: *mut c_void,
|
||||
callback: Option<Callback>,
|
||||
) -> HRESULT {
|
||||
match (queue(handle), callback) {
|
||||
(Some(queue), Some(callback)) => queue.submit(port, delay_ms, Task::new(context, callback)),
|
||||
_ => E_INVALIDARG,
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancels what is still queued (callbacks see `canceled`), refuses new
|
||||
/// work, then calls `callback`.
|
||||
pub fn XTaskQueueTerminate(
|
||||
handle: *const Queue,
|
||||
_wait: bool,
|
||||
context: *mut c_void,
|
||||
callback: Option<TerminatedCallback>,
|
||||
) -> HRESULT {
|
||||
let Some(queue) = queue(handle) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
queue.terminated.store(true, Ordering::Release);
|
||||
for port in &queue.ports {
|
||||
let pending: Vec<Task> = lock(&port.tasks).drain(..).collect();
|
||||
for task in pending {
|
||||
task.run(true);
|
||||
}
|
||||
}
|
||||
if let Some(callback) = callback {
|
||||
callback(context);
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
pub fn XTaskQueueRegisterMonitor(
|
||||
handle: *const Queue,
|
||||
context: *mut c_void,
|
||||
callback: Option<MonitorCallback>,
|
||||
token: *mut u64,
|
||||
) -> HRESULT {
|
||||
let (Some(queue), Some(callback)) = (queue(handle), callback) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if token.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let id = NEXT_TOKEN.fetch_add(1, Ordering::Relaxed);
|
||||
lock(&queue.monitors).push((id, context as usize, callback as usize));
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { token.write(id) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub fn XTaskQueueUnregisterMonitor(handle: *const Queue, token: u64) {
|
||||
if let Some(queue) = queue(handle) {
|
||||
lock(&queue.monitors).retain(|m| m.0 != token);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new handle to the process queue, if there is one.
|
||||
pub fn XTaskQueueGetCurrentProcessTaskQueue(out: *mut *const Queue) -> bool {
|
||||
let found = process_queue();
|
||||
if !out.is_null() {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(found.clone().map_or(std::ptr::null(), Arc::into_raw)) };
|
||||
}
|
||||
found.is_some()
|
||||
}
|
||||
|
||||
pub fn XTaskQueueSetCurrentProcessTaskQueue(handle: *const Queue) {
|
||||
let new = if handle.is_null() {
|
||||
None
|
||||
} else {
|
||||
queue(handle)
|
||||
};
|
||||
*lock(&PROCESS_QUEUE) = Some(new);
|
||||
}
|
||||
|
||||
/// An async block: what the title fills in, then the system area.
|
||||
#[repr(C)]
|
||||
pub struct AsyncBlock {
|
||||
pub queue: *const Queue,
|
||||
pub context: *mut c_void,
|
||||
pub callback: Option<CompletionRoutine>,
|
||||
/// Ours: [unused, status, result size, unused].
|
||||
pub internal: [usize; 4],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct ProviderData {
|
||||
pub block: *mut AsyncBlock,
|
||||
pub buffer_size: usize,
|
||||
pub buffer: *mut c_void,
|
||||
pub context: *mut c_void,
|
||||
}
|
||||
|
||||
const OP_BEGIN: u32 = 0;
|
||||
const OP_DO_WORK: u32 = 1;
|
||||
const OP_GET_RESULT: u32 = 2;
|
||||
const OP_CANCEL: u32 = 3;
|
||||
const OP_CLEANUP: u32 = 4;
|
||||
|
||||
/// One call in flight, until its result is taken or it fails.
|
||||
struct Call {
|
||||
provider: Provider,
|
||||
context: usize,
|
||||
identity: usize,
|
||||
done: Mutex<bool>,
|
||||
finished: Condvar,
|
||||
}
|
||||
|
||||
impl Call {
|
||||
fn provider(
|
||||
&self,
|
||||
op: u32,
|
||||
block: *mut AsyncBlock,
|
||||
size: usize,
|
||||
buffer: *mut c_void,
|
||||
) -> HRESULT {
|
||||
let data = ProviderData {
|
||||
block,
|
||||
buffer_size: size,
|
||||
buffer,
|
||||
context: self.context as *mut c_void,
|
||||
};
|
||||
(self.provider)(op, &data)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls by block address.
|
||||
static CALLS: LazyLock<Mutex<HashMap<usize, Arc<Call>>>> = LazyLock::new(Default::default);
|
||||
|
||||
fn call(block: *mut AsyncBlock) -> Option<Arc<Call>> {
|
||||
lock(&CALLS).get(&(block as usize)).cloned()
|
||||
}
|
||||
|
||||
/// The block's status and result-size words.
|
||||
fn words(block: *mut AsyncBlock) -> (&'static AtomicUsize, &'static AtomicUsize) {
|
||||
// SAFETY: the title's block outlives the call; its system area is ours.
|
||||
unsafe {
|
||||
let internal = std::ptr::addr_of_mut!((*block).internal).cast::<AtomicUsize>();
|
||||
(&*internal.add(1), &*internal.add(2))
|
||||
}
|
||||
}
|
||||
|
||||
fn status(block: *mut AsyncBlock) -> HRESULT {
|
||||
words(block).0.load(Ordering::Acquire) as u32 as i32
|
||||
}
|
||||
|
||||
fn release(block: *mut AsyncBlock) {
|
||||
// Unlocked before the provider runs: it may call back into us.
|
||||
let removed = lock(&CALLS).remove(&(block as usize));
|
||||
if let Some(call) = removed {
|
||||
call.provider(OP_CLEANUP, block, 0, std::ptr::null_mut());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn XAsyncBegin(
|
||||
block: *mut AsyncBlock,
|
||||
context: *mut c_void,
|
||||
identity: *const c_void,
|
||||
_identity_name: *const u8,
|
||||
provider: Option<Provider>,
|
||||
) -> HRESULT {
|
||||
let Some(provider) = provider else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if block.is_null() || call(block).is_some() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let (status, size) = words(block);
|
||||
status.store(E_PENDING as u32 as usize, Ordering::Release);
|
||||
size.store(0, Ordering::Release);
|
||||
let call = Arc::new(Call {
|
||||
provider,
|
||||
context: context as usize,
|
||||
identity: identity as usize,
|
||||
done: Mutex::new(false),
|
||||
finished: Condvar::new(),
|
||||
});
|
||||
lock(&CALLS).insert(block as usize, call.clone());
|
||||
// A failed begin fails the call, so the completion routine still runs.
|
||||
let hr = call.provider(OP_BEGIN, block, 0, std::ptr::null_mut());
|
||||
if hr < 0 {
|
||||
XAsyncComplete(block, hr, 0);
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Queues the provider's `DoWork` on the block's work port.
|
||||
pub fn XAsyncSchedule(block: *mut AsyncBlock, delay_ms: u32) -> HRESULT {
|
||||
extern "system" fn work(block: *mut c_void, canceled: bool) {
|
||||
let block = block.cast::<AsyncBlock>();
|
||||
let Some(call) = call(block) else { return };
|
||||
let hr = if canceled {
|
||||
E_ABORT
|
||||
} else {
|
||||
call.provider(OP_DO_WORK, block, 0, std::ptr::null_mut())
|
||||
};
|
||||
if hr != E_PENDING {
|
||||
XAsyncComplete(block, hr, 0);
|
||||
}
|
||||
}
|
||||
if block.is_null() || call(block).is_none() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: a block in flight is valid.
|
||||
let handle = unsafe { (*block).queue };
|
||||
match queue(handle) {
|
||||
Some(queue) => queue.submit(WORK, delay_ms, Task::new(block.cast(), work)),
|
||||
None => E_INVALIDARG,
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the result (the first one wins), wakes waiters and queues the
|
||||
/// completion routine on the block's completion port.
|
||||
pub fn XAsyncComplete(block: *mut AsyncBlock, result: HRESULT, required_size: usize) {
|
||||
extern "system" fn complete(block: *mut c_void, _canceled: bool) {
|
||||
let block = block.cast::<AsyncBlock>();
|
||||
// SAFETY: read before the status was published; see below.
|
||||
if let Some(routine) = unsafe { (*block).callback } {
|
||||
routine(block);
|
||||
}
|
||||
}
|
||||
let Some(call) = call(block) else { return };
|
||||
if result == E_PENDING {
|
||||
return;
|
||||
}
|
||||
let mut done = lock(&call.done);
|
||||
if *done {
|
||||
return;
|
||||
}
|
||||
// Read before publishing: once the status is set, the title may free
|
||||
// the block.
|
||||
// SAFETY: a block in flight is valid.
|
||||
let (handle, routine) = unsafe { ((*block).queue, (*block).callback) };
|
||||
let (status, size) = words(block);
|
||||
if result < 0 || required_size == 0 {
|
||||
release(block);
|
||||
}
|
||||
size.store(required_size, Ordering::Release);
|
||||
status.store(result as u32 as usize, Ordering::Release);
|
||||
*done = true;
|
||||
call.finished.notify_all();
|
||||
drop(done);
|
||||
if routine.is_some() {
|
||||
let task = Task::new(block.cast(), complete);
|
||||
match queue(handle) {
|
||||
Some(queue) if queue.submit(COMPLETION, 0, task) == S_OK => {}
|
||||
_ => task.run(true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn XAsyncGetStatus(block: *mut AsyncBlock, wait: bool) -> HRESULT {
|
||||
if block.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if wait && let Some(call) = call(block) {
|
||||
let done = lock(&call.done);
|
||||
drop(call.finished.wait_while(done, |d| !*d));
|
||||
}
|
||||
status(block)
|
||||
}
|
||||
|
||||
pub fn XAsyncGetResultSize(block: *mut AsyncBlock, out: *mut usize) -> HRESULT {
|
||||
if block.is_null() || out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let hr = status(block);
|
||||
if hr == S_OK {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(words(block).1.load(Ordering::Acquire)) };
|
||||
}
|
||||
hr
|
||||
}
|
||||
|
||||
/// Asks the provider to cancel; the call fails with `E_ABORT` unless the
|
||||
/// provider completed it first.
|
||||
pub fn XAsyncCancel(block: *mut AsyncBlock) {
|
||||
if let Some(call) = call(block) {
|
||||
call.provider(OP_CANCEL, block, 0, std::ptr::null_mut());
|
||||
XAsyncComplete(block, E_ABORT, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Has the provider write the result into `buffer`, then ends the call.
|
||||
pub fn XAsyncGetResult(
|
||||
block: *mut AsyncBlock,
|
||||
identity: *const c_void,
|
||||
buffer_size: usize,
|
||||
buffer: *mut c_void,
|
||||
used: *mut usize,
|
||||
) -> HRESULT {
|
||||
if block.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let hr = status(block);
|
||||
let size = words(block).1.load(Ordering::Acquire);
|
||||
if hr != S_OK || size == 0 {
|
||||
if hr == S_OK && !used.is_null() {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { used.write(0) };
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
let Some(call) = call(block) else {
|
||||
return E_ILLEGAL_METHOD_CALL;
|
||||
};
|
||||
if call.identity != identity as usize {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if buffer_size < size || buffer.is_null() {
|
||||
return E_NOT_SUFFICIENT_BUFFER;
|
||||
}
|
||||
let hr = call.provider(OP_GET_RESULT, block, buffer_size, buffer);
|
||||
if !used.is_null() {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { used.write(size) };
|
||||
}
|
||||
release(block);
|
||||
hr
|
||||
}
|
||||
|
||||
/// Starts a call on `block` that is already over: it completes with `hr`
|
||||
/// and no result data, through the block's completion port as usual.
|
||||
pub fn finished(block: *mut AsyncBlock, identity: *const c_void, hr: HRESULT) -> HRESULT {
|
||||
extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT {
|
||||
// SAFETY: the runtime passes valid provider data.
|
||||
let data = unsafe { &*data };
|
||||
if op == OP_BEGIN {
|
||||
XAsyncComplete(data.block, data.context as usize as u32 as i32, 0);
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
let context = hr as u32 as usize as *mut c_void;
|
||||
XAsyncBegin(block, context, identity, std::ptr::null(), Some(provider))
|
||||
}
|
||||
|
||||
// The object `QueryApiImpl` returns. Each method takes the object first,
|
||||
// then the API's arguments; slot offsets as titles call them.
|
||||
|
||||
pub static OBJECT: Object = Object::new("task queue", &VTABLE);
|
||||
|
||||
/// Its interface id is the provider's.
|
||||
pub const INTERFACES: &[Interface] = &[(PROVIDER, PROVIDER, &OBJECT)];
|
||||
|
||||
type This = *const Object;
|
||||
extern "system" fn m_get_status(_: This, b: *mut AsyncBlock, wait: u8) -> HRESULT {
|
||||
XAsyncGetStatus(b, wait != 0)
|
||||
}
|
||||
extern "system" fn m_get_result_size(_: This, b: *mut AsyncBlock, out: *mut usize) -> HRESULT {
|
||||
XAsyncGetResultSize(b, out)
|
||||
}
|
||||
extern "system" fn m_cancel(_: This, b: *mut AsyncBlock) {
|
||||
XAsyncCancel(b)
|
||||
}
|
||||
extern "system" fn m_begin(
|
||||
_: This,
|
||||
b: *mut AsyncBlock,
|
||||
context: *mut c_void,
|
||||
identity: *const c_void,
|
||||
name: *const u8,
|
||||
provider: Option<Provider>,
|
||||
) -> HRESULT {
|
||||
XAsyncBegin(b, context, identity, name, provider)
|
||||
}
|
||||
extern "system" fn m_schedule(_: This, b: *mut AsyncBlock, delay: u32) -> HRESULT {
|
||||
XAsyncSchedule(b, delay)
|
||||
}
|
||||
extern "system" fn m_complete(_: This, b: *mut AsyncBlock, hr: HRESULT, size: usize) {
|
||||
XAsyncComplete(b, hr, size)
|
||||
}
|
||||
extern "system" fn m_get_result(
|
||||
_: This,
|
||||
b: *mut AsyncBlock,
|
||||
identity: *const c_void,
|
||||
size: usize,
|
||||
buffer: *mut c_void,
|
||||
used: *mut usize,
|
||||
) -> HRESULT {
|
||||
XAsyncGetResult(b, identity, size, buffer, used)
|
||||
}
|
||||
extern "system" fn m_create(
|
||||
_: This,
|
||||
work: u32,
|
||||
completion: u32,
|
||||
out: *mut *const Queue,
|
||||
) -> HRESULT {
|
||||
XTaskQueueCreate(work, completion, out)
|
||||
}
|
||||
extern "system" fn m_create_composite(
|
||||
_: This,
|
||||
work: *const c_void,
|
||||
completion: *const c_void,
|
||||
out: *mut *const Queue,
|
||||
) -> HRESULT {
|
||||
XTaskQueueCreateComposite(work, completion, out)
|
||||
}
|
||||
extern "system" fn m_get_port(
|
||||
_: This,
|
||||
q: *const Queue,
|
||||
port: u32,
|
||||
out: *mut *const c_void,
|
||||
) -> HRESULT {
|
||||
XTaskQueueGetPort(q, port, out)
|
||||
}
|
||||
extern "system" fn m_duplicate(_: This, q: *const Queue, out: *mut *const Queue) -> HRESULT {
|
||||
XTaskQueueDuplicateHandle(q, out)
|
||||
}
|
||||
extern "system" fn m_dispatch(_: This, q: *const Queue, port: u32, timeout: u32) -> bool {
|
||||
XTaskQueueDispatch(q, port, timeout)
|
||||
}
|
||||
extern "system" fn m_close(_: This, q: *const Queue) {
|
||||
XTaskQueueCloseHandle(q)
|
||||
}
|
||||
extern "system" fn m_submit(
|
||||
_: This,
|
||||
q: *const Queue,
|
||||
port: u32,
|
||||
context: *mut c_void,
|
||||
callback: Option<Callback>,
|
||||
) -> HRESULT {
|
||||
XTaskQueueSubmitDelayedCallback(q, port, 0, context, callback)
|
||||
}
|
||||
extern "system" fn m_submit_delayed(
|
||||
_: This,
|
||||
q: *const Queue,
|
||||
port: u32,
|
||||
delay: u32,
|
||||
context: *mut c_void,
|
||||
callback: Option<Callback>,
|
||||
) -> HRESULT {
|
||||
XTaskQueueSubmitDelayedCallback(q, port, delay, context, callback)
|
||||
}
|
||||
extern "system" fn m_terminate(
|
||||
_: This,
|
||||
q: *const Queue,
|
||||
wait: u8,
|
||||
context: *mut c_void,
|
||||
callback: Option<TerminatedCallback>,
|
||||
) -> HRESULT {
|
||||
XTaskQueueTerminate(q, wait != 0, context, callback)
|
||||
}
|
||||
extern "system" fn m_register_monitor(
|
||||
_: This,
|
||||
q: *const Queue,
|
||||
context: *mut c_void,
|
||||
callback: Option<MonitorCallback>,
|
||||
token: *mut u64,
|
||||
) -> HRESULT {
|
||||
XTaskQueueRegisterMonitor(q, context, callback, token)
|
||||
}
|
||||
extern "system" fn m_unregister_monitor(_: This, q: *const Queue, token: u64) {
|
||||
XTaskQueueUnregisterMonitor(q, token)
|
||||
}
|
||||
extern "system" fn m_get_process_queue(_: This, out: *mut *const Queue) -> bool {
|
||||
XTaskQueueGetCurrentProcessTaskQueue(out)
|
||||
}
|
||||
extern "system" fn m_set_process_queue(_: This, q: *const Queue) {
|
||||
XTaskQueueSetCurrentProcessTaskQueue(q)
|
||||
}
|
||||
/// The runtime's debug check that the caller is not a time-critical thread,
|
||||
/// which every runtime call in a title makes first.
|
||||
extern "system" fn m_check_thread(_: This) {}
|
||||
|
||||
static VTABLE: Methods<31> = Methods([
|
||||
missing::<0> as *const (), // 0x00 QueryInterface
|
||||
add_ref as *const (), // 0x08 AddRef
|
||||
add_ref as *const (), // 0x10 Release: the object is static
|
||||
m_get_status as *const (), // 0x18
|
||||
m_get_result_size as *const (), // 0x20
|
||||
m_cancel as *const (), // 0x28
|
||||
missing::<6> as *const (), // 0x30 run a work callback as a call
|
||||
m_begin as *const (), // 0x38
|
||||
missing::<8> as *const (), // 0x40
|
||||
m_schedule as *const (), // 0x48
|
||||
m_complete as *const (), // 0x50
|
||||
m_get_result as *const (), // 0x58
|
||||
m_create as *const (), // 0x60
|
||||
m_create_composite as *const (), // 0x68
|
||||
m_get_port as *const (), // 0x70
|
||||
m_duplicate as *const (), // 0x78
|
||||
m_dispatch as *const (), // 0x80
|
||||
m_close as *const (), // 0x88
|
||||
m_submit as *const (), // 0x90
|
||||
m_submit_delayed as *const (), // 0x98
|
||||
missing::<20> as *const (), // 0xa0 register a wait handle
|
||||
missing::<21> as *const (), // 0xa8 unregister it
|
||||
m_terminate as *const (), // 0xb0
|
||||
m_register_monitor as *const (), // 0xb8
|
||||
m_unregister_monitor as *const (), // 0xc0
|
||||
m_get_process_queue as *const (), // 0xc8
|
||||
m_set_process_queue as *const (), // 0xd0
|
||||
missing::<27> as *const (), // 0xd8 thread time-sensitivity
|
||||
missing::<28> as *const (), // 0xe0
|
||||
m_check_thread as *const (), // 0xe8
|
||||
missing::<30> as *const (), // 0xf0
|
||||
]);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::AtomicU32;
|
||||
|
||||
fn slot<F: Copy>(offset: usize) -> F {
|
||||
crate::modules::xgameruntime::method(&OBJECT, offset)
|
||||
}
|
||||
|
||||
static RAN: AtomicU32 = AtomicU32::new(0);
|
||||
extern "system" fn count(context: *mut c_void, canceled: bool) {
|
||||
RAN.fetch_add(
|
||||
if canceled { 100 } else { context as u32 },
|
||||
Ordering::SeqCst,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_ports_run_callbacks_when_dispatched() {
|
||||
type Create = extern "system" fn(This, u32, u32, *mut *const Queue) -> HRESULT;
|
||||
type Submit = extern "system" fn(This, *const Queue, u32, *mut c_void, Callback) -> HRESULT;
|
||||
type Dispatch = extern "system" fn(This, *const Queue, u32, u32) -> bool;
|
||||
type Close = extern "system" fn(This, *const Queue);
|
||||
let this: This = &OBJECT;
|
||||
let mut q = std::ptr::null();
|
||||
assert_eq!(slot::<Create>(0x60)(this, 0, 0, &mut q), S_OK);
|
||||
assert_eq!(
|
||||
slot::<Submit>(0x90)(this, q, COMPLETION, 5 as *mut c_void, count),
|
||||
S_OK
|
||||
);
|
||||
assert_eq!(RAN.load(Ordering::SeqCst), 0, "manual: nothing runs yet");
|
||||
assert!(
|
||||
!slot::<Dispatch>(0x80)(this, q, WORK, 0),
|
||||
"work port is empty"
|
||||
);
|
||||
assert!(slot::<Dispatch>(0x80)(this, q, COMPLETION, 0));
|
||||
assert_eq!(RAN.load(Ordering::SeqCst), 5);
|
||||
assert!(!slot::<Dispatch>(0x80)(this, q, COMPLETION, 0));
|
||||
slot::<Close>(0x88)(this, q);
|
||||
}
|
||||
|
||||
/// A provider that schedules its work and returns a u64 result.
|
||||
extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT {
|
||||
// SAFETY: the runtime passes valid provider data.
|
||||
let data = unsafe { &*data };
|
||||
match op {
|
||||
OP_BEGIN => XAsyncSchedule(data.block, 0),
|
||||
OP_DO_WORK => {
|
||||
XAsyncComplete(data.block, S_OK, 8);
|
||||
S_OK
|
||||
}
|
||||
OP_GET_RESULT => {
|
||||
// SAFETY: at least 8 bytes, checked by the runtime.
|
||||
unsafe { data.buffer.cast::<u64>().write(data.context as u64) };
|
||||
S_OK
|
||||
}
|
||||
_ => S_OK,
|
||||
}
|
||||
}
|
||||
|
||||
static COMPLETED: AtomicU32 = AtomicU32::new(0);
|
||||
extern "system" fn completed(_: *mut AsyncBlock) {
|
||||
COMPLETED.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_calls_complete_and_return_results() {
|
||||
let mut q = std::ptr::null();
|
||||
// Work on a thread pool, completion dispatched by hand.
|
||||
assert_eq!(XTaskQueueCreate(1, 0, &mut q), S_OK);
|
||||
let mut block = AsyncBlock {
|
||||
queue: q,
|
||||
context: std::ptr::null_mut(),
|
||||
callback: Some(completed),
|
||||
internal: [0; 4],
|
||||
};
|
||||
let identity = 0x1d as *const c_void;
|
||||
assert_eq!(
|
||||
XAsyncBegin(
|
||||
&mut block,
|
||||
42 as *mut c_void,
|
||||
identity,
|
||||
std::ptr::null(),
|
||||
Some(provider)
|
||||
),
|
||||
S_OK
|
||||
);
|
||||
assert_eq!(XAsyncGetStatus(&mut block, true), S_OK);
|
||||
let mut size = 0;
|
||||
assert_eq!(XAsyncGetResultSize(&mut block, &mut size), S_OK);
|
||||
assert_eq!(size, 8);
|
||||
assert_eq!(COMPLETED.load(Ordering::SeqCst), 0, "completion is manual");
|
||||
assert!(XTaskQueueDispatch(q, COMPLETION, INFINITE));
|
||||
assert_eq!(COMPLETED.load(Ordering::SeqCst), 1);
|
||||
|
||||
let mut value = 0u64;
|
||||
let mut small = 0u32;
|
||||
let out = (&mut small as *mut u32).cast();
|
||||
assert_eq!(
|
||||
XAsyncGetResult(&mut block, identity, 4, out, std::ptr::null_mut()),
|
||||
E_NOT_SUFFICIENT_BUFFER
|
||||
);
|
||||
let out = (&mut value as *mut u64).cast();
|
||||
let mut used = 0;
|
||||
assert_eq!(
|
||||
XAsyncGetResult(&mut block, identity, 8, out, &mut used),
|
||||
S_OK
|
||||
);
|
||||
assert_eq!((value, used), (42, 8));
|
||||
assert!(call(&mut block).is_none(), "the call ends with its result");
|
||||
XTaskQueueCloseHandle(q);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminate_cancels_what_is_queued() {
|
||||
static TERMINATED: AtomicBool = AtomicBool::new(false);
|
||||
extern "system" fn terminated(_: *mut c_void) {
|
||||
TERMINATED.store(true, Ordering::SeqCst);
|
||||
}
|
||||
extern "system" fn note(context: *mut c_void, canceled: bool) {
|
||||
// SAFETY: the test passes a pointer to its flag.
|
||||
unsafe { *context.cast::<bool>() = canceled };
|
||||
}
|
||||
let mut q = std::ptr::null();
|
||||
assert_eq!(XTaskQueueCreate(0, 0, &mut q), S_OK);
|
||||
let mut canceled = false;
|
||||
let flag = (&mut canceled as *mut bool).cast();
|
||||
assert_eq!(
|
||||
XTaskQueueSubmitDelayedCallback(q, WORK, 0, flag, Some(note)),
|
||||
S_OK
|
||||
);
|
||||
assert_eq!(
|
||||
XTaskQueueTerminate(q, true, std::ptr::null_mut(), Some(terminated)),
|
||||
S_OK
|
||||
);
|
||||
assert!(canceled && TERMINATED.load(Ordering::SeqCst));
|
||||
assert_eq!(
|
||||
XTaskQueueSubmitDelayedCallback(q, WORK, 0, flag, Some(note)),
|
||||
E_ABORT
|
||||
);
|
||||
XTaskQueueCloseHandle(q);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
//! The title's own id (from its manifest), which runtime areas exist, and
|
||||
//! game invites and events. Offline no invite arrives and events go
|
||||
//! nowhere.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::{CStr, c_char, c_void};
|
||||
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, token,
|
||||
};
|
||||
use crate::runtime;
|
||||
|
||||
/// Title id and launching another title.
|
||||
pub const TITLE_PROVIDER: Guid = Guid::new(
|
||||
0x973a_344e,
|
||||
0x24bf,
|
||||
0x4d0f,
|
||||
[0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29],
|
||||
);
|
||||
/// As Minecraft (2022) asks for it.
|
||||
pub const TITLE_IID: Guid = Guid::new(
|
||||
0x2549_f142,
|
||||
0x6419,
|
||||
0x4a06,
|
||||
[0x97, 0xb5, 0x93, 0x1a, 0xab, 0x7c, 0x2f, 0x34],
|
||||
);
|
||||
/// Feature checks; the interface id is the provider's, as for the next two.
|
||||
pub const FEATURES: Guid = Guid::new(
|
||||
0x8836_fe87,
|
||||
0xedb9,
|
||||
0x4fe3,
|
||||
[0x8d, 0xad, 0x05, 0xf0, 0xd2, 0xcd, 0x5b, 0x40],
|
||||
);
|
||||
pub const INVITES: Guid = Guid::new(
|
||||
0x0651_aae2,
|
||||
0x4012,
|
||||
0x4077,
|
||||
[0xbf, 0x84, 0x8b, 0x90, 0x97, 0x09, 0x0e, 0x2c],
|
||||
);
|
||||
pub const EVENTS: Guid = Guid::new(
|
||||
0xbbfb_dcc7,
|
||||
0xbfe7,
|
||||
0x409b,
|
||||
[0xa5, 0xca, 0xed, 0xf0, 0x54, 0x96, 0x0b, 0x4d],
|
||||
);
|
||||
|
||||
pub static TITLE_OBJECT: Object = Object::new("title", &TITLE_VTABLE);
|
||||
pub static FEATURES_OBJECT: Object = Object::new("features", &FEATURES_VTABLE);
|
||||
pub static INVITES_OBJECT: Object = Object::new("invites", &INVITES_VTABLE);
|
||||
pub static EVENTS_OBJECT: Object = Object::new("events", &EVENTS_VTABLE);
|
||||
|
||||
pub const INTERFACES: &[Interface] = &[
|
||||
(TITLE_PROVIDER, TITLE_IID, &TITLE_OBJECT),
|
||||
(FEATURES, FEATURES, &FEATURES_OBJECT),
|
||||
(INVITES, INVITES, &INVITES_OBJECT),
|
||||
(EVENTS, EVENTS, &EVENTS_OBJECT),
|
||||
];
|
||||
|
||||
type This = *const Object;
|
||||
|
||||
extern "system" fn title_id(_: This, out: *mut u32) -> HRESULT {
|
||||
put(out, runtime::title().id)
|
||||
}
|
||||
|
||||
/// Runtime areas by number, in the public feature list's order, that we
|
||||
/// serve: async calls and providers (2, 3), game (5), invites (6),
|
||||
/// persistent local storage (12), system (15), task queues (16), users
|
||||
/// (18), error reports (19), game events (20). Not the others: store, game
|
||||
/// saves, UI, networking, packages, streaming, threads...
|
||||
const AVAILABLE: [u32; 10] = [2, 3, 5, 6, 12, 15, 16, 18, 19, 20];
|
||||
|
||||
extern "system" fn is_feature_available(_: This, feature: u32) -> bool {
|
||||
AVAILABLE.contains(&feature)
|
||||
}
|
||||
|
||||
/// Nothing raises these events offline, so the callback never runs.
|
||||
extern "system" fn register(
|
||||
_: This,
|
||||
_queue: *const c_void,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
out: *mut u64,
|
||||
) -> HRESULT {
|
||||
put(out, token())
|
||||
}
|
||||
extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Accepted and dropped; the name goes to the debug log.
|
||||
extern "system" fn write_event(
|
||||
_: This,
|
||||
_user: *const c_void,
|
||||
_service_config: *const c_char,
|
||||
_session: *const c_char,
|
||||
name: *const c_char,
|
||||
_dimensions: *const c_char,
|
||||
_measurements: *const c_char,
|
||||
) -> HRESULT {
|
||||
if !name.is_null() {
|
||||
// SAFETY: a non-null name is a NUL-terminated string.
|
||||
let name = unsafe { CStr::from_ptr(name) }.to_string_lossy();
|
||||
tracing::debug!(%name, "game event dropped");
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
static TITLE_VTABLE: Methods<5> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
title_id as *const (), // 0x18
|
||||
missing::<4> as *const (), // 0x20 launch another title (returns nothing)
|
||||
]);
|
||||
|
||||
static FEATURES_VTABLE: Methods<4> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
is_feature_available as *const (), // 0x18
|
||||
]);
|
||||
|
||||
static INVITES_VTABLE: Methods<5> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
register as *const (), // 0x18
|
||||
unregister as *const (), // 0x20
|
||||
]);
|
||||
|
||||
static EVENTS_VTABLE: Methods<4> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
write_event as *const (), // 0x18
|
||||
]);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::modules::xgameruntime::method;
|
||||
|
||||
#[test]
|
||||
fn served_areas_are_available_others_not() {
|
||||
type Check = extern "system" fn(This, u32) -> bool;
|
||||
let check = method::<Check>(&FEATURES_OBJECT, 0x18);
|
||||
assert!(check(&FEATURES_OBJECT, 18), "users");
|
||||
assert!(!check(&FEATURES_OBJECT, 14), "store");
|
||||
|
||||
type Register = extern "system" fn(
|
||||
This,
|
||||
*const c_void,
|
||||
*mut c_void,
|
||||
*const c_void,
|
||||
*mut u64,
|
||||
) -> HRESULT;
|
||||
type Unregister = extern "system" fn(This, u64, bool) -> bool;
|
||||
let null = std::ptr::null();
|
||||
let mut token = 0;
|
||||
let register = method::<Register>(&INVITES_OBJECT, 0x18);
|
||||
assert_eq!(
|
||||
register(&INVITES_OBJECT, null, null as _, null, &mut token),
|
||||
S_OK
|
||||
);
|
||||
assert_ne!(token, 0);
|
||||
assert!(method::<Unregister>(&INVITES_OBJECT, 0x20)(
|
||||
&INVITES_OBJECT,
|
||||
token,
|
||||
true
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,165 @@
|
||||
//! `xgameruntime.dll`: the console game runtime (XGame*, XUser*, XTaskQueue*...).
|
||||
//!
|
||||
//! The DLL names titles actually import these from are confirmed by running
|
||||
//! `victory census` on real titles; extend `dlls` accordingly.
|
||||
//! Titles rarely import it. A stub linked into the title loads the DLL with
|
||||
//! `LoadLibraryExA` (answered with a pseudo handle, see `kernel`), looks up
|
||||
//! the `*ApiImpl` functions and `XErrorReport` with `GetProcAddress`, and
|
||||
//! initialises. Each runtime API call then asks `QueryApiImpl` for a COM-style
|
||||
//! object of its area (provider and interface GUIDs), calls one method and
|
||||
//! releases it. Until an area is implemented its query fails, and the call
|
||||
//! returns that error without touching the object. An area's interface id
|
||||
//! changes when its method table does, so each object answers only the ids
|
||||
//! whose slots we know. Implemented: task queues and async blocks
|
||||
//! (`xasync`), one offline user (`xuser`), system information (`xsystem`),
|
||||
//! title id, feature checks, invites and events (`xgame`), persistent local
|
||||
//! storage (`storage`).
|
||||
#![allow(non_snake_case)]
|
||||
// Title code calls these through its import table, passing pointers the real
|
||||
// API would trust.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::{CStr, c_char, c_void};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use super::{storage, xasync, xgame, xsystem, xuser};
|
||||
use crate::{HleModule, hle_export};
|
||||
|
||||
pub type HRESULT = i32;
|
||||
pub const S_OK: HRESULT = 0;
|
||||
/// `HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)`.
|
||||
pub const NOT_SUPPORTED: HRESULT = 0x8007_0032_u32 as i32;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Guid {
|
||||
pub data1: u32,
|
||||
pub data2: u16,
|
||||
pub data3: u16,
|
||||
pub data4: [u8; 8],
|
||||
}
|
||||
|
||||
impl Guid {
|
||||
pub const fn new(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> Guid {
|
||||
Guid {
|
||||
data1,
|
||||
data2,
|
||||
data3,
|
||||
data4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Guid {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let d = self.data4;
|
||||
write!(
|
||||
f,
|
||||
"{:08x}-{:04x}-{:04x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
|
||||
self.data1, self.data2, self.data3, d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A runtime object as title code calls it: its first word points at the
|
||||
/// method table. Ours are static, so reference counting is a no-op.
|
||||
#[repr(C)]
|
||||
pub struct Object {
|
||||
vtable: *const *const (),
|
||||
/// Named in the log when a title calls a method we lack.
|
||||
area: &'static str,
|
||||
}
|
||||
|
||||
// SAFETY: the table is a static array of function addresses.
|
||||
unsafe impl Sync for Object {}
|
||||
|
||||
impl Object {
|
||||
pub const fn new<const N: usize>(area: &'static str, methods: &'static Methods<N>) -> Object {
|
||||
Object {
|
||||
vtable: methods.0.as_ptr(),
|
||||
area,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An object's method table, by slot (`QueryInterface`, `AddRef`,
|
||||
/// `Release`, then the area's methods from offset 0x18).
|
||||
pub struct Methods<const N: usize>(pub [*const (); N]);
|
||||
|
||||
// SAFETY: function addresses only.
|
||||
unsafe impl<const N: usize> Sync for Methods<N> {}
|
||||
|
||||
/// A (provider, interface id) pair a title may ask for, and our object.
|
||||
pub type Interface = (Guid, Guid, &'static Object);
|
||||
|
||||
const AREAS: [&[Interface]; 5] = [
|
||||
xasync::INTERFACES,
|
||||
xuser::INTERFACES,
|
||||
xsystem::INTERFACES,
|
||||
xgame::INTERFACES,
|
||||
storage::INTERFACES,
|
||||
];
|
||||
|
||||
/// `AddRef` and `Release`.
|
||||
pub extern "system" fn add_ref(_: *const Object) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
/// A slot nobody has needed yet; logged with its area. Wrong for a slot
|
||||
/// that returns `bool` or a value.
|
||||
pub extern "system" fn missing<const SLOT: usize>(this: *const Object) -> HRESULT {
|
||||
// SAFETY: title code calls methods on objects we handed out.
|
||||
let area = unsafe { (*this).area };
|
||||
tracing::warn!(
|
||||
area,
|
||||
slot = format_args!("{:#x}", SLOT * 8),
|
||||
"runtime method not implemented"
|
||||
);
|
||||
xasync::E_NOTIMPL
|
||||
}
|
||||
|
||||
/// Writes `value` through `out` if it is non-null.
|
||||
pub fn put<T>(out: *mut T, value: T) -> HRESULT {
|
||||
if out.is_null() {
|
||||
return xasync::E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: checked non-null; the title passes room for a `T`.
|
||||
unsafe { out.write(value) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Copies `text` and a NUL into the title's `size`-byte buffer and reports
|
||||
/// the bytes used, as the runtime's string getters do.
|
||||
pub fn put_string(text: &str, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
|
||||
let len = text.len() + 1;
|
||||
if buffer.is_null() || size < len {
|
||||
return xasync::E_NOT_SUFFICIENT_BUFFER;
|
||||
}
|
||||
// SAFETY: the buffer holds `size` bytes, checked above.
|
||||
unsafe {
|
||||
buffer.copy_from_nonoverlapping(text.as_ptr(), text.len());
|
||||
buffer.add(text.len()).write(0);
|
||||
}
|
||||
if !used.is_null() {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { used.write(len) };
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// A new registration token for callbacks we never call (events nobody
|
||||
/// raises offline).
|
||||
pub fn token() -> u64 {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Calls method `slot` (byte offset) of `object` as title code would.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn method<F: Copy>(object: &Object, slot: usize) -> F {
|
||||
// SAFETY: the caller names the slot's signature; tables cover the slots
|
||||
// tests use.
|
||||
unsafe { std::mem::transmute_copy(&*object.vtable.add(slot / 8)) }
|
||||
}
|
||||
|
||||
pub extern "system" fn XGameRuntimeInitialize() -> HRESULT {
|
||||
tracing::info!("XGameRuntimeInitialize");
|
||||
@@ -18,6 +170,63 @@ pub extern "system" fn XGameRuntimeUninitialize() {
|
||||
tracing::info!("XGameRuntimeUninitialize");
|
||||
}
|
||||
|
||||
/// The arguments identify the title's build of the stub; not checked.
|
||||
pub extern "system" fn InitializeApiImpl(version: u64, build: u64) -> HRESULT {
|
||||
tracing::info!(version, build, "InitializeApiImpl");
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn InitializeApiImplEx(version: u64, build: u64, flags: u64) -> HRESULT {
|
||||
tracing::info!(version, build, flags, "InitializeApiImplEx");
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn UninitializeApiImpl() {
|
||||
tracing::info!("UninitializeApiImpl");
|
||||
}
|
||||
|
||||
/// The object for an implemented (provider, interface id); others fail,
|
||||
/// each pair logged once.
|
||||
pub extern "system" fn QueryApiImpl(
|
||||
provider: *const Guid,
|
||||
iid: *const Guid,
|
||||
out: *mut *mut c_void,
|
||||
) -> HRESULT {
|
||||
static QUERIED: Mutex<Vec<(Guid, Guid)>> = Mutex::new(Vec::new());
|
||||
// SAFETY: the title passes pointers to GUIDs (null is tolerated).
|
||||
let (Some(&provider), Some(&iid)) = (unsafe { provider.as_ref() }, unsafe { iid.as_ref() })
|
||||
else {
|
||||
return NOT_SUPPORTED;
|
||||
};
|
||||
let found = AREAS
|
||||
.iter()
|
||||
.flat_map(|area| area.iter())
|
||||
.find(|(p, i, _)| (*p, *i) == (provider, iid));
|
||||
if let Some(&(_, _, object)) = found
|
||||
&& !out.is_null()
|
||||
{
|
||||
// SAFETY: checked non-null; the title passes room for a pointer.
|
||||
unsafe { out.write((object as *const Object).cast_mut().cast()) };
|
||||
return S_OK;
|
||||
}
|
||||
let mut queried = QUERIED.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !queried.contains(&(provider, iid)) {
|
||||
queried.push((provider, iid));
|
||||
tracing::warn!(%provider, %iid, "runtime API area not implemented");
|
||||
}
|
||||
NOT_SUPPORTED
|
||||
}
|
||||
|
||||
pub extern "system" fn XErrorReport(hr: HRESULT, message: *const c_char) {
|
||||
let message = if message.is_null() {
|
||||
"".into()
|
||||
} else {
|
||||
// SAFETY: a non-null message is a NUL-terminated string.
|
||||
unsafe { CStr::from_ptr(message) }.to_string_lossy()
|
||||
};
|
||||
tracing::warn!(hr = format_args!("{:#010x}", hr as u32), %message, "XErrorReport");
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "xgameruntime",
|
||||
@@ -25,6 +234,66 @@ pub(crate) fn module() -> HleModule {
|
||||
exports: vec![
|
||||
hle_export!(XGameRuntimeInitialize),
|
||||
hle_export!(XGameRuntimeUninitialize),
|
||||
hle_export!(InitializeApiImpl),
|
||||
hle_export!(InitializeApiImplEx),
|
||||
hle_export!(UninitializeApiImpl),
|
||||
hle_export!(QueryApiImpl),
|
||||
hle_export!(XErrorReport),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::modules::kernel::{FreeLibrary, GetProcAddress, LoadLibraryExA};
|
||||
|
||||
#[test]
|
||||
fn title_stub_loads_the_runtime_dynamically() {
|
||||
let load = |name: &CStr| LoadLibraryExA(name.as_ptr().cast(), std::ptr::null_mut(), 0x800);
|
||||
let runtime = load(c"xgameruntime.dll");
|
||||
assert!(!runtime.is_null());
|
||||
let proc = |name: &CStr| GetProcAddress(runtime, name.as_ptr().cast());
|
||||
for name in [
|
||||
c"InitializeApiImpl",
|
||||
c"InitializeApiImplEx",
|
||||
c"QueryApiImpl",
|
||||
c"UninitializeApiImpl",
|
||||
c"XErrorReport",
|
||||
] {
|
||||
assert!(!proc(name).is_null(), "{name:?}");
|
||||
}
|
||||
assert!(proc(c"NotAnExport").is_null());
|
||||
let ordinal = std::ptr::without_provenance::<u8>(1);
|
||||
assert!(GetProcAddress(runtime, ordinal).is_null());
|
||||
|
||||
type Init = extern "system" fn(u64, u64, u64) -> HRESULT;
|
||||
type Query = extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> HRESULT;
|
||||
// SAFETY: the addresses are our functions with these signatures.
|
||||
let (init, query) = unsafe {
|
||||
(
|
||||
std::mem::transmute::<*mut c_void, Init>(proc(c"InitializeApiImplEx")),
|
||||
std::mem::transmute::<*mut c_void, Query>(proc(c"QueryApiImpl")),
|
||||
)
|
||||
};
|
||||
assert_eq!(init(1, 2, 2), S_OK);
|
||||
let guid = Guid {
|
||||
data1: 1,
|
||||
data2: 2,
|
||||
data3: 3,
|
||||
data4: [4; 8],
|
||||
};
|
||||
let untouched = 0x1234 as *mut c_void;
|
||||
let mut out = untouched;
|
||||
assert!(query(&guid, &guid, &mut out) < 0);
|
||||
assert_eq!(out, untouched);
|
||||
assert_eq!(FreeLibrary(runtime), 1);
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let kernel32 = load(c"kernel32.dll");
|
||||
assert!(!kernel32.is_null(), "host DLLs still load from the host");
|
||||
assert!(!GetProcAddress(kernel32, c"GetTickCount".as_ptr().cast()).is_null());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
//! `xmem.dll`: console memory, served from host memory. The GPU side works
|
||||
//! from CPU addresses (unified memory), so memory types and bandwidth
|
||||
//! classes change nothing here; what constrains addresses (alignment,
|
||||
//! 2 MiB pages, address-bit limits) is honoured.
|
||||
#![allow(non_snake_case)]
|
||||
// Title code calls these through its import table, passing pointers the real
|
||||
// API would trust.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::alloc::{Layout, alloc, dealloc};
|
||||
use std::ffi::c_void;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, MEM_RELEASE, MEM_RESERVE,
|
||||
MEMORY_BASIC_INFORMATION, MemExtendedParameterAddressRequirements, PAGE_NOACCESS,
|
||||
PAGE_READWRITE, VirtualAlloc2, VirtualFree, VirtualQueryEx,
|
||||
};
|
||||
use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
|
||||
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||
use windows_sys::core::BOOL;
|
||||
|
||||
use crate::{HleModule, hle_export};
|
||||
|
||||
const MIB: usize = 1 << 20;
|
||||
const GIB: usize = 1 << 30;
|
||||
/// Title memory of an Xbox Series X in the advanced mode: 10 GiB of
|
||||
/// GPU-optimal and 3.5 GiB of standard memory.
|
||||
const GPU_OPTIMAL_LIMIT: usize = 10 * GIB;
|
||||
const STANDARD_LIMIT: usize = 7 * GIB / 2;
|
||||
|
||||
/// Standard memory the title has handed to the system.
|
||||
static TRANSFERRED: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
// Console additions to the host's flags.
|
||||
/// 2 MiB pages; the host reads this bit as large pages, which need a
|
||||
/// privilege.
|
||||
const PAGES_2M: u32 = 0x2000_0000;
|
||||
/// With `PAGES_2M`: 64 KiB pages; the host reads it as AWE memory.
|
||||
const PAGES_64K_BIT: u32 = 0x40_0000;
|
||||
/// The host's protection constants and `PAGE_GUARD`. Above them the console
|
||||
/// adds GPU access bits (0x800-0x40000). Write-combining and uncached are
|
||||
/// dropped too: our GPU side reads this memory through the CPU.
|
||||
const HOST_PROTECTION: u32 = 0x1ff;
|
||||
/// XMem flags of memory both processors reach: all of ours.
|
||||
const GRAPHICS: u64 = 3;
|
||||
/// XMem flag bit of 32-bit graphics memory.
|
||||
const ADDRESS_32BIT: u64 = 4;
|
||||
|
||||
/// The highest address XMem `flags` allow, 0 for no limit: 32 bits, or
|
||||
/// 46 down to 40 bits from the field at bit 12.
|
||||
fn highest_address(flags: u64) -> usize {
|
||||
let bits = match (flags & ADDRESS_32BIT, flags >> 12 & 7) {
|
||||
(0, 0) => return 0,
|
||||
(0, field) => 47 - field,
|
||||
_ => 32,
|
||||
};
|
||||
(1 << bits) - 1
|
||||
}
|
||||
|
||||
pub extern "system" fn XMemVirtualAlloc(
|
||||
base: *mut c_void,
|
||||
size: usize,
|
||||
kind: u32,
|
||||
flags: u64,
|
||||
protect: u32,
|
||||
) -> *mut c_void {
|
||||
let mut requirements = MEM_ADDRESS_REQUIREMENTS {
|
||||
HighestEndingAddress: highest_address(flags) as *mut c_void,
|
||||
Alignment: if kind & (PAGES_2M | PAGES_64K_BIT) == PAGES_2M {
|
||||
2 * MIB
|
||||
} else {
|
||||
0
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let mut kind = kind & !(PAGES_2M | PAGES_64K_BIT);
|
||||
let protect = match protect & HOST_PROTECTION {
|
||||
0 => PAGE_NOACCESS,
|
||||
p => p,
|
||||
};
|
||||
let mut parameter = MEM_EXTENDED_PARAMETER::default();
|
||||
parameter.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64;
|
||||
parameter.Anonymous2.Pointer = (&raw mut requirements).cast();
|
||||
// Address requirements apply to reservations at an address of our choice.
|
||||
let constrained = base.is_null()
|
||||
&& (!requirements.HighestEndingAddress.is_null() || requirements.Alignment != 0);
|
||||
if constrained {
|
||||
kind |= MEM_RESERVE;
|
||||
}
|
||||
// SAFETY: the title's own arguments, cleaned of console bits; the
|
||||
// parameter points at `requirements`, which outlives the call.
|
||||
unsafe {
|
||||
VirtualAlloc2(
|
||||
GetCurrentProcess(),
|
||||
base,
|
||||
size,
|
||||
kind,
|
||||
protect,
|
||||
if constrained { &mut parameter } else { std::ptr::null_mut() },
|
||||
constrained.into(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the
|
||||
/// same), then the XMem flags and tag.
|
||||
#[repr(C)]
|
||||
pub struct BasicInformation {
|
||||
host: MEMORY_BASIC_INFORMATION,
|
||||
flags: u64,
|
||||
tag_code: u32,
|
||||
tag: [u8; 4],
|
||||
}
|
||||
|
||||
// shortcut: every committed page reports graphics memory and no tag, since
|
||||
// all of it is GPU-reachable here; remember the flags of `XMemVirtualAlloc`
|
||||
// regions if a title tells CPU-only memory apart.
|
||||
pub extern "system" fn XMemVirtualQuery(
|
||||
process: HANDLE,
|
||||
address: *const c_void,
|
||||
out: *mut BasicInformation,
|
||||
) -> BOOL {
|
||||
let size = size_of::<MEMORY_BASIC_INFORMATION>();
|
||||
// SAFETY: the title passes room for the whole structure; the host
|
||||
// fails on a null one.
|
||||
unsafe {
|
||||
if VirtualQueryEx(process, address, out.cast(), size) == 0 {
|
||||
return 0;
|
||||
}
|
||||
let info = &mut *out;
|
||||
info.flags = if info.host.State == MEM_COMMIT { GRAPHICS } else { 0 };
|
||||
info.tag_code = 0;
|
||||
info.tag = [0; 4];
|
||||
}
|
||||
1
|
||||
}
|
||||
|
||||
// `XMemAlloc` attributes: alignment as log2 (5 bits at 24, 4 bytes and up
|
||||
// from 2), then the memory type, then bit 33: a 32-bit address.
|
||||
const ALIGNMENT_SHIFT: u64 = 24;
|
||||
const ALLOC_32BIT: u64 = 1 << 33;
|
||||
/// Our block header: the block's size and alignment, just below the
|
||||
/// pointer handed out.
|
||||
const HEADER: usize = 2 * size_of::<usize>();
|
||||
|
||||
fn layout(size: usize, attributes: u64) -> Option<Layout> {
|
||||
// An alignment of at least 16 leaves room for the header.
|
||||
let align = 1usize << (attributes >> ALIGNMENT_SHIFT & 0x1f).max(4);
|
||||
Layout::from_size_align(size.checked_add(align)?, align).ok()
|
||||
}
|
||||
|
||||
/// The title's general allocator, for middleware too.
|
||||
// shortcut: allocation hooks (`XMemSetAllocationHooks`, or hooks the title
|
||||
// exports) are not called; no title we have sets them.
|
||||
pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void {
|
||||
if attributes & ALLOC_32BIT != 0 {
|
||||
return XMemVirtualAlloc(
|
||||
std::ptr::null_mut(),
|
||||
size,
|
||||
MEM_RESERVE | MEM_COMMIT,
|
||||
GRAPHICS | ADDRESS_32BIT,
|
||||
PAGE_READWRITE,
|
||||
);
|
||||
}
|
||||
let Some(layout) = layout(size, attributes) else {
|
||||
return std::ptr::null_mut();
|
||||
};
|
||||
// SAFETY: the layout has a non-zero size.
|
||||
let block = unsafe { alloc(layout) };
|
||||
if block.is_null() {
|
||||
return block.cast();
|
||||
}
|
||||
// SAFETY: the block holds the alignment (at least the header) and then
|
||||
// `size` bytes.
|
||||
unsafe {
|
||||
let user = block.add(layout.align());
|
||||
user.sub(HEADER)
|
||||
.cast::<[usize; 2]>()
|
||||
.write([layout.size(), layout.align()]);
|
||||
user.cast()
|
||||
}
|
||||
}
|
||||
|
||||
/// Frees what [`XMemAlloc`] returned, given the same attributes.
|
||||
pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) {
|
||||
if address.is_null() {
|
||||
return;
|
||||
}
|
||||
// SAFETY: the address came from `XMemAlloc` with these attributes: a
|
||||
// whole reservation, or a header-prefixed block.
|
||||
unsafe {
|
||||
if attributes & ALLOC_32BIT != 0 {
|
||||
VirtualFree(address, 0, MEM_RELEASE);
|
||||
return;
|
||||
}
|
||||
let user = address.cast::<u8>();
|
||||
let [size, align] = user.sub(HEADER).cast::<[usize; 2]>().read();
|
||||
dealloc(
|
||||
user.sub(align),
|
||||
Layout::from_size_align_unchecked(size, align),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The oldest layout we know; newer titles pass other flag values (Minecraft
|
||||
/// 0x20000001) and read the same leading fields.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Default)]
|
||||
pub struct WorkingSet {
|
||||
pub title_limit: usize,
|
||||
pub title_used: usize,
|
||||
pub tools_limit: usize,
|
||||
pub tools_used: usize,
|
||||
pub stack_used: u32,
|
||||
pub physical_pages: u32,
|
||||
pub gpu_optimal_limit: usize,
|
||||
pub gpu_optimal_used: usize,
|
||||
pub tools_gpu_optimal_limit: usize,
|
||||
pub tools_gpu_optimal_used: usize,
|
||||
pub kernel_pool_used: u32,
|
||||
pub kernel_pool_limit: u32,
|
||||
}
|
||||
|
||||
/// The title's budget and our process's commit as what it uses. No tools
|
||||
/// memory: a retail console.
|
||||
// shortcut: all fields are filled whatever the flags ask for, and use is
|
||||
// not split by bandwidth class (GPU-optimal use reads 0); track
|
||||
// allocations per class if a title budgets from that field.
|
||||
pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut WorkingSet) -> BOOL {
|
||||
if out.is_null() {
|
||||
return 0;
|
||||
}
|
||||
let mut counters = PROCESS_MEMORY_COUNTERS {
|
||||
cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: our own process and a sized structure.
|
||||
unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) };
|
||||
let stats = WorkingSet {
|
||||
title_limit: GPU_OPTIMAL_LIMIT + STANDARD_LIMIT - TRANSFERRED.load(Ordering::Relaxed),
|
||||
title_used: counters.PagefileUsage,
|
||||
gpu_optimal_limit: GPU_OPTIMAL_LIMIT,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: checked non-null; the title passes room for the structure.
|
||||
unsafe { out.write(stats) };
|
||||
1
|
||||
}
|
||||
|
||||
/// Hands title memory (standard, in 2 MiB pages) to the system. The other
|
||||
/// transfers involve tools memory, which a retail console has none of.
|
||||
pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL {
|
||||
const TITLE_TO_SYSTEM: u32 = 0;
|
||||
tracing::info!(kind, size, "XMemTransferMemory");
|
||||
if size == 0 {
|
||||
return 1;
|
||||
}
|
||||
let Some(size) = size.checked_next_multiple_of(2 * MIB) else {
|
||||
return 0;
|
||||
};
|
||||
let moved = kind == TITLE_TO_SYSTEM
|
||||
&& TRANSFERRED
|
||||
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |t| {
|
||||
t.checked_add(size).filter(|&t| t <= STANDARD_LIMIT)
|
||||
})
|
||||
.is_ok();
|
||||
moved.into()
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "xmem",
|
||||
dlls: &["xmem.dll"],
|
||||
exports: vec![
|
||||
hle_export!(XMemAlloc),
|
||||
hle_export!(XMemFree),
|
||||
hle_export!(XMemVirtualAlloc),
|
||||
hle_export!(XMemVirtualQuery),
|
||||
hle_export!(XMemGetWorkingSetStatistics),
|
||||
hle_export!(XMemTransferMemory),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn query(address: *const c_void) -> BasicInformation {
|
||||
// SAFETY: plain data; zero is a valid value.
|
||||
let mut info: BasicInformation = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: a pseudo handle needs no closing.
|
||||
let process = unsafe { GetCurrentProcess() };
|
||||
assert_eq!(XMemVirtualQuery(process, address, &mut info), 1);
|
||||
info
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alloc_honours_alignment_and_frees() {
|
||||
for (field, align) in [(0, 16), (4, 16), (0xc, 4096), (0x10, 64 * 1024)] {
|
||||
let attributes = field << ALIGNMENT_SHIFT | 1 << 29; // a graphics type
|
||||
let p = XMemAlloc(100, attributes);
|
||||
assert!(!p.is_null());
|
||||
assert_eq!(p as usize % align, 0, "field {field:#x}");
|
||||
// SAFETY: 100 bytes were allocated.
|
||||
unsafe { p.cast::<u8>().write_bytes(0xab, 100) };
|
||||
XMemFree(p, attributes);
|
||||
}
|
||||
let p = XMemAlloc(4096, ALLOC_32BIT);
|
||||
assert!(!p.is_null() && (p as usize) < 1 << 32);
|
||||
XMemFree(p, ALLOC_32BIT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn virtual_alloc_meets_console_constraints() {
|
||||
const GPU_READ_WRITE: u32 = 0x2000;
|
||||
let p = XMemVirtualAlloc(
|
||||
std::ptr::null_mut(),
|
||||
4 * MIB,
|
||||
PAGES_2M | MEM_RESERVE | MEM_COMMIT,
|
||||
GRAPHICS | 7 << 12, // 40-bit addresses
|
||||
PAGE_READWRITE | GPU_READ_WRITE,
|
||||
);
|
||||
assert!(!p.is_null());
|
||||
assert_eq!(p as usize % (2 * MIB), 0);
|
||||
assert!((p as usize) < 1 << 40);
|
||||
let info = query(p);
|
||||
assert_eq!(info.host.State, MEM_COMMIT);
|
||||
assert_eq!(info.host.Protect, PAGE_READWRITE);
|
||||
assert_eq!(info.flags & GRAPHICS, GRAPHICS);
|
||||
// SAFETY: our own reservation.
|
||||
assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
|
||||
assert_eq!(query(p).flags, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transfers_shrink_the_title_budget() {
|
||||
let mut before = WorkingSet::default();
|
||||
assert_eq!(XMemGetWorkingSetStatistics(0x2000_0001, &mut before), 1);
|
||||
assert!(before.title_used > 0);
|
||||
assert_eq!(XMemTransferMemory(0, 128 * MIB - 1), 1);
|
||||
assert_eq!(XMemTransferMemory(2, MIB), 0, "no tools memory");
|
||||
assert_eq!(XMemTransferMemory(0, STANDARD_LIMIT), 0, "over budget");
|
||||
let mut after = WorkingSet::default();
|
||||
XMemGetWorkingSetStatistics(0x2000_0001, &mut after);
|
||||
assert_eq!(before.title_limit - after.title_limit, 128 * MIB);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statistics_have_the_console_layout() {
|
||||
assert_eq!(size_of::<WorkingSet>(), 0x50);
|
||||
assert_eq!(size_of::<BasicInformation>(), 0x40);
|
||||
assert_eq!(std::mem::offset_of!(WorkingSet, gpu_optimal_limit), 0x28);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
//! XSystem: the console's identity and sandbox, and how analytics describe
|
||||
//! the device. Fixed values: one offline retail Xbox Series X.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, Object, add_ref, missing, put_string,
|
||||
};
|
||||
|
||||
pub const PROVIDER: Guid = Guid::new(
|
||||
0xe349_bd1a,
|
||||
0xfc20,
|
||||
0x4e40,
|
||||
[0xb9, 0x9c, 0x41, 0x78, 0xcc, 0x6b, 0x40, 0x9f],
|
||||
);
|
||||
|
||||
/// The interface as Minecraft (2022) asks for it; an older table
|
||||
/// ended before the device id.
|
||||
pub const IID: Guid = Guid::new(
|
||||
0x6fd7_1f09,
|
||||
0x7513,
|
||||
0x49f0,
|
||||
[0x89, 0xbc, 0xbf, 0xaf, 0x5d, 0xf6, 0xf8, 0x52],
|
||||
);
|
||||
|
||||
/// Analytics information; its interface id is the provider's.
|
||||
pub const ANALYTICS: Guid = Guid::new(
|
||||
0xb884_675d,
|
||||
0xb738,
|
||||
0x4a9c,
|
||||
[0x81, 0x5d, 0x9a, 0x9a, 0x1e, 0x0c, 0x6c, 0x9b],
|
||||
);
|
||||
|
||||
/// 38 characters (39 bytes with the NUL).
|
||||
const CONSOLE_ID: &str = "00000000000000000000000000000000000001";
|
||||
/// The retail sandbox.
|
||||
const SANDBOX: &str = "RETAIL";
|
||||
/// Base64 of 32 bytes: 44 characters (45 bytes with the NUL).
|
||||
const DEVICE_ID: &str = "VkljdG9yeSBvZmZsaW5lIGRldmljZSBpZGVudGl0eSE=";
|
||||
|
||||
pub static OBJECT: Object = Object::new("system", &VTABLE);
|
||||
pub static ANALYTICS_OBJECT: Object = Object::new("analytics", &ANALYTICS_VTABLE);
|
||||
|
||||
pub const INTERFACES: &[Interface] = &[
|
||||
(PROVIDER, IID, &OBJECT),
|
||||
(ANALYTICS, ANALYTICS, &ANALYTICS_OBJECT),
|
||||
];
|
||||
|
||||
type This = *const Object;
|
||||
|
||||
extern "system" fn console_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
|
||||
put_string(CONSOLE_ID, size, buffer, used)
|
||||
}
|
||||
extern "system" fn sandbox_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
|
||||
put_string(SANDBOX, size, buffer, used)
|
||||
}
|
||||
/// The device id this title sees (titles see different ones).
|
||||
extern "system" fn device_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
|
||||
put_string(DEVICE_ID, size, buffer, used)
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Version {
|
||||
pub major: u16,
|
||||
pub minor: u16,
|
||||
pub build: u16,
|
||||
pub revision: u16,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct AnalyticsInfo {
|
||||
pub os: Version,
|
||||
pub hosting_os: Version,
|
||||
/// NUL-terminated.
|
||||
pub family: [u8; 64],
|
||||
pub form: [u8; 64],
|
||||
}
|
||||
|
||||
const OS: Version = Version {
|
||||
major: 10,
|
||||
minor: 0,
|
||||
build: 22000,
|
||||
revision: 0,
|
||||
};
|
||||
|
||||
fn text(s: &str) -> [u8; 64] {
|
||||
let mut out = [0; 64];
|
||||
out[..s.len()].copy_from_slice(s.as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// A struct this large comes back through the caller's buffer, whose
|
||||
/// address is also the return value.
|
||||
extern "system" fn analytics_info(_: This, out: *mut AnalyticsInfo) -> *mut AnalyticsInfo {
|
||||
let info = AnalyticsInfo {
|
||||
os: OS,
|
||||
hosting_os: OS,
|
||||
family: text("Xbox"),
|
||||
form: text("Xbox Series X"),
|
||||
};
|
||||
// SAFETY: the caller passes room for the struct.
|
||||
unsafe { out.write(info) };
|
||||
out
|
||||
}
|
||||
|
||||
static VTABLE: Methods<6> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
console_id as *const (), // 0x18, by the older table; titles seen do not call it
|
||||
sandbox_id as *const (), // 0x20
|
||||
device_id as *const (), // 0x28
|
||||
]);
|
||||
|
||||
static ANALYTICS_VTABLE: Methods<4> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
analytics_info as *const (), // 0x18
|
||||
]);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::modules::xgameruntime::{S_OK, method};
|
||||
|
||||
#[test]
|
||||
fn identity_strings_fit_the_documented_sizes() {
|
||||
type Get = extern "system" fn(This, usize, *mut u8, *mut usize) -> HRESULT;
|
||||
let this: This = &OBJECT;
|
||||
let mut buffer = [0u8; 64];
|
||||
let mut used = 0;
|
||||
for (slot, size) in [(0x18, 39), (0x20, 16), (0x28, 45)] {
|
||||
let get = method::<Get>(&OBJECT, slot);
|
||||
assert_eq!(get(this, size, buffer.as_mut_ptr(), &mut used), S_OK);
|
||||
assert!(used <= size && buffer[used - 1] == 0, "slot {slot:#x}");
|
||||
}
|
||||
assert_eq!(&buffer[..7], b"VkljdG9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analytics_info_comes_back_through_the_buffer() {
|
||||
type Get = extern "system" fn(This, *mut AnalyticsInfo) -> *mut AnalyticsInfo;
|
||||
let mut info = std::mem::MaybeUninit::<AnalyticsInfo>::uninit();
|
||||
let get = method::<Get>(&ANALYTICS_OBJECT, 0x18);
|
||||
let back = get(&ANALYTICS_OBJECT, info.as_mut_ptr());
|
||||
assert_eq!(back, info.as_mut_ptr());
|
||||
// SAFETY: written by the call.
|
||||
let info = unsafe { info.assume_init() };
|
||||
assert_eq!(size_of::<AnalyticsInfo>(), 0x90);
|
||||
assert_eq!(info.os.build, 22000);
|
||||
assert_eq!(&info.form[..14], b"Xbox Series X\0");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
//! XUser: one offline local user, signed in, never a guest, with every
|
||||
//! privilege. Served as the user provider's objects from `QueryApiImpl`;
|
||||
//! adding a user completes through `xasync` like any other async call. No
|
||||
//! input device is associated with the user (there are none, `gameinput`).
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
|
||||
use super::xasync::{self, AsyncBlock, ProviderData};
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, token,
|
||||
};
|
||||
|
||||
/// The user provider.
|
||||
pub const PROVIDER: Guid = Guid {
|
||||
data1: 0x01ac_d177,
|
||||
data2: 0x91f9,
|
||||
data3: 0x4763,
|
||||
data4: [0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0],
|
||||
};
|
||||
|
||||
/// Its main interface.
|
||||
pub const IID: Guid = Guid {
|
||||
data1: 0xeb9b_f948,
|
||||
data2: 0x18dc,
|
||||
data3: 0x4d82,
|
||||
data4: [0xbb, 0xcc, 0x40, 0xe0, 0xa8, 0x09, 0xc4, 0xc0],
|
||||
};
|
||||
|
||||
/// The interface titles ask for to read a gamertag.
|
||||
pub const GAMERTAG_IID: Guid = Guid {
|
||||
data1: 0xcef4_fac0,
|
||||
data2: 0x7676,
|
||||
data3: 0x4a94,
|
||||
data4: [0xa1, 0x19, 0x4c, 0x43, 0xf9, 0xeb, 0x5b, 0x74],
|
||||
};
|
||||
|
||||
/// The user's devices and audio endpoints.
|
||||
pub const DEVICE_PROVIDER: Guid = Guid::new(
|
||||
0x7d82_4997,
|
||||
0x10dc,
|
||||
0x45ab,
|
||||
[0x86, 0xb7, 0x27, 0x37, 0x76, 0x7c, 0x0b, 0xf1],
|
||||
);
|
||||
|
||||
/// The device interface as Minecraft (2022) asks for it.
|
||||
pub const DEVICE_IID: Guid = Guid::new(
|
||||
0x0cc6_a956,
|
||||
0xe7e1,
|
||||
0x4fdf,
|
||||
[0x93, 0x41, 0x9d, 0x5d, 0xa6, 0x49, 0xeb, 0xc8],
|
||||
);
|
||||
|
||||
/// The documented "no such user" error.
|
||||
pub const USER_NOT_FOUND: HRESULT = 0x8924_5104_u32 as i32;
|
||||
|
||||
pub const XUID: u64 = 0x0009_0000_0000_0001;
|
||||
pub const LOCAL_ID: u64 = 1;
|
||||
const GAMERTAG: &str = "Player";
|
||||
|
||||
/// The only user; a handle is its address, duplicating and closing are free.
|
||||
pub struct User;
|
||||
static USER: User = User;
|
||||
type Handle = *const User;
|
||||
|
||||
fn user() -> Handle {
|
||||
&USER
|
||||
}
|
||||
|
||||
fn found(found: bool, out: *mut Handle) -> HRESULT {
|
||||
if found {
|
||||
put(out, user())
|
||||
} else {
|
||||
USER_NOT_FOUND
|
||||
}
|
||||
}
|
||||
|
||||
pub static OBJECT: Object = Object::new("user", &VTABLE);
|
||||
pub static GAMERTAG_OBJECT: Object = Object::new("user gamertag", &GAMERTAG_VTABLE);
|
||||
pub static DEVICE_OBJECT: Object = Object::new("user devices", &DEVICE_VTABLE);
|
||||
|
||||
pub const INTERFACES: &[Interface] = &[
|
||||
(PROVIDER, IID, &OBJECT),
|
||||
(PROVIDER, GAMERTAG_IID, &GAMERTAG_OBJECT),
|
||||
(DEVICE_PROVIDER, DEVICE_IID, &DEVICE_OBJECT),
|
||||
];
|
||||
|
||||
type This = *const Object;
|
||||
extern "system" fn duplicate(_: This, _: Handle, out: *mut Handle) -> HRESULT {
|
||||
put(out, user())
|
||||
}
|
||||
extern "system" fn close(_: This, _: Handle) {}
|
||||
extern "system" fn compare(_: This, a: Handle, b: Handle) -> i32 {
|
||||
i32::from(a != b)
|
||||
}
|
||||
|
||||
/// The async provider for adding a user: done at once, the result is a
|
||||
/// handle.
|
||||
extern "system" fn add_provider(op: u32, data: *const ProviderData) -> HRESULT {
|
||||
const BEGIN: u32 = 0;
|
||||
const GET_RESULT: u32 = 2;
|
||||
// SAFETY: the async runtime passes valid provider data.
|
||||
let data = unsafe { &*data };
|
||||
match op {
|
||||
BEGIN => xasync::XAsyncComplete(data.block, S_OK, size_of::<Handle>()),
|
||||
GET_RESULT => return put(data.buffer.cast::<Handle>(), user()),
|
||||
_ => {}
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Tells our add calls apart from other async calls on the same block.
|
||||
static ADD: u8 = 0;
|
||||
|
||||
/// Any options add the one user, silently.
|
||||
extern "system" fn add_async(_: This, options: u32, block: *mut AsyncBlock) -> HRESULT {
|
||||
tracing::info!(options, "XUserAddAsync: the offline local user");
|
||||
xasync::XAsyncBegin(
|
||||
block,
|
||||
std::ptr::null_mut(),
|
||||
(&raw const ADD).cast(),
|
||||
std::ptr::null(),
|
||||
Some(add_provider),
|
||||
)
|
||||
}
|
||||
extern "system" fn add_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT {
|
||||
xasync::XAsyncGetResult(
|
||||
block,
|
||||
(&raw const ADD).cast(),
|
||||
size_of::<Handle>(),
|
||||
out.cast(),
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
}
|
||||
extern "system" fn get_local_id(_: This, _: Handle, out: *mut u64) -> HRESULT {
|
||||
put(out, LOCAL_ID)
|
||||
}
|
||||
extern "system" fn find_by_local_id(_: This, id: u64, out: *mut Handle) -> HRESULT {
|
||||
found(id == LOCAL_ID, out)
|
||||
}
|
||||
extern "system" fn get_id(_: This, _: Handle, out: *mut u64) -> HRESULT {
|
||||
put(out, XUID)
|
||||
}
|
||||
extern "system" fn find_by_id(_: This, id: u64, out: *mut Handle) -> HRESULT {
|
||||
found(id == XUID, out)
|
||||
}
|
||||
extern "system" fn get_is_guest(_: This, _: Handle, out: *mut bool) -> HRESULT {
|
||||
put(out, false)
|
||||
}
|
||||
/// 0: signed in.
|
||||
extern "system" fn get_state(_: This, _: Handle, out: *mut u32) -> HRESULT {
|
||||
put(out, 0)
|
||||
}
|
||||
/// The same name for every component (classic, modern, suffix, unique).
|
||||
extern "system" fn get_gamertag(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_component: u32,
|
||||
size: usize,
|
||||
buffer: *mut u8,
|
||||
used: *mut usize,
|
||||
) -> HRESULT {
|
||||
put_string(GAMERTAG, size, buffer, used)
|
||||
}
|
||||
/// Granted; deny reason 0 (none).
|
||||
extern "system" fn check_privilege(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_options: u32,
|
||||
_privilege: u32,
|
||||
has: *mut bool,
|
||||
reason: *mut u32,
|
||||
) -> HRESULT {
|
||||
if !reason.is_null() {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { reason.write(0) };
|
||||
}
|
||||
put(has, true)
|
||||
}
|
||||
|
||||
/// The user never changes and no device is ever associated, so these
|
||||
/// callbacks are never called.
|
||||
extern "system" fn register(
|
||||
_: This,
|
||||
_queue: *const c_void,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
out: *mut u64,
|
||||
) -> HRESULT {
|
||||
put(out, token())
|
||||
}
|
||||
extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// No input device belongs to a user.
|
||||
extern "system" fn find_for_device(_: This, _device: *const c_void, _: *mut Handle) -> HRESULT {
|
||||
USER_NOT_FOUND
|
||||
}
|
||||
|
||||
// Unset slots: gamer pictures, token and signature, issue resolution.
|
||||
static VTABLE: Methods<35> = Methods([
|
||||
missing::<0> as *const (), // 0x00 QueryInterface
|
||||
add_ref as *const (), // 0x08 AddRef
|
||||
add_ref as *const (), // 0x10 Release: the object is static
|
||||
duplicate as *const (), // 0x18
|
||||
close as *const (), // 0x20
|
||||
compare as *const (), // 0x28
|
||||
missing::<6> as *const (), // 0x30 maximum users
|
||||
add_async as *const (), // 0x38
|
||||
add_result as *const (), // 0x40
|
||||
get_local_id as *const (), // 0x48
|
||||
find_by_local_id as *const (), // 0x50
|
||||
get_id as *const (), // 0x58
|
||||
find_by_id as *const (), // 0x60
|
||||
get_is_guest as *const (), // 0x68
|
||||
get_state as *const (), // 0x70
|
||||
get_gamertag as *const (), // 0x78 older gamertag slot
|
||||
missing::<16> as *const (), // 0x80 gamer picture: begin
|
||||
missing::<17> as *const (), // 0x88 result size
|
||||
missing::<18> as *const (), // 0x90 result
|
||||
missing::<19> as *const (), // 0x98 age group
|
||||
check_privilege as *const (), // 0xa0
|
||||
missing::<21> as *const (), // 0xa8 resolve privilege with UI: begin
|
||||
missing::<22> as *const (), // 0xb0 result
|
||||
missing::<23> as *const (), // 0xb8 token and signature: begin
|
||||
missing::<24> as *const (), // 0xc0 result size
|
||||
missing::<25> as *const (), // 0xc8 result
|
||||
missing::<26> as *const (), // 0xd0 the same, UTF-16: begin
|
||||
missing::<27> as *const (), // 0xd8 result size
|
||||
missing::<28> as *const (), // 0xe0 result
|
||||
missing::<29> as *const (), // 0xe8 resolve issue with UI: begin
|
||||
missing::<30> as *const (), // 0xf0 result
|
||||
missing::<31> as *const (), // 0xf8 the same, UTF-16: begin
|
||||
missing::<32> as *const (), // 0x100 result
|
||||
register as *const (), // 0x108 change event
|
||||
unregister as *const (), // 0x110
|
||||
]);
|
||||
|
||||
static GAMERTAG_VTABLE: Methods<4> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
get_gamertag as *const (), // 0x18
|
||||
]);
|
||||
|
||||
static DEVICE_VTABLE: Methods<6> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
find_for_device as *const (), // 0x18
|
||||
register as *const (), // 0x20 device association changed
|
||||
unregister as *const (), // 0x28
|
||||
]);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::modules::xasync::E_NOT_SUFFICIENT_BUFFER;
|
||||
use crate::modules::xgameruntime::method as slot;
|
||||
|
||||
#[test]
|
||||
fn startup_adds_the_user_and_reads_its_id() {
|
||||
type Add = extern "system" fn(This, u32, *mut AsyncBlock) -> HRESULT;
|
||||
type AddResult = extern "system" fn(This, *mut AsyncBlock, *mut Handle) -> HRESULT;
|
||||
type GetId = extern "system" fn(This, Handle, *mut u64) -> HRESULT;
|
||||
type Gamertag =
|
||||
extern "system" fn(This, Handle, u32, usize, *mut u8, *mut usize) -> HRESULT;
|
||||
let this: This = &OBJECT;
|
||||
let mut block = AsyncBlock {
|
||||
queue: std::ptr::null(),
|
||||
context: std::ptr::null_mut(),
|
||||
callback: None,
|
||||
internal: [0; 4],
|
||||
};
|
||||
assert_eq!(slot::<Add>(&OBJECT, 0x38)(this, 1, &mut block), S_OK);
|
||||
assert_eq!(xasync::XAsyncGetStatus(&mut block, true), S_OK);
|
||||
let mut handle = std::ptr::null();
|
||||
assert_eq!(
|
||||
slot::<AddResult>(&OBJECT, 0x40)(this, &mut block, &mut handle),
|
||||
S_OK
|
||||
);
|
||||
assert!(!handle.is_null());
|
||||
let mut xuid = 0;
|
||||
assert_eq!(slot::<GetId>(&OBJECT, 0x58)(this, handle, &mut xuid), S_OK);
|
||||
assert_eq!(xuid, XUID);
|
||||
|
||||
let mut name = [0u8; 16];
|
||||
let mut used = 0;
|
||||
let get = slot::<Gamertag>(&GAMERTAG_OBJECT, 0x18);
|
||||
assert_eq!(get(this, handle, 0, 16, name.as_mut_ptr(), &mut used), S_OK);
|
||||
assert_eq!(&name[..used], b"Player\0");
|
||||
assert_eq!(
|
||||
get(this, handle, 0, 2, name.as_mut_ptr(), &mut used),
|
||||
E_NOT_SUFFICIENT_BUFFER
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user