Files
6gbvram---16gb-ram/crates/victory-hle/src/modules/xasync.rs
T
MarvisandClaude Opus 5.5 754619f30e 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]>
2026-11-23 14:42:21 +01:00

960 lines
30 KiB
Rust

//! 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);
}
}