Run Grand Theft Auto VI from first boot into the world

The title now boots through every first-boot and menu screen at its own
30 fps, drawing with translated shaders, with input, sound, saves and
loading served; it reaches the world, where the host GPU path still
fails (see "Not working yet").

Loader and runtime
- Crash reports unwind properly, name C++ throws and host GPU failures,
  carry the title's last debug lines and are appended to crashes.log.
- Thread notices on our own threads, reentrant late DLL loading, exit in
  the console's order, relaunch on a launch-new-game request.
- Offline guard: the title cannot reach the network (sockets, name
  lookups, WinHTTP, the media source resolver); by-name lookups and
  loads follow the import rules.
- Every runtime area the title calls is served (networking hint,
  packages, store, saves, display, UI, speech stubs, user, async pool).
  Saves persist; an update is one rename and survives a kill at any step.
- DirectStorage reads for real: shared worker pool, priorities, zlib and
  BCPack. BCPack is our own decoder; the format's constant tables ship in
  crates/victory-formats/src/bcpack-tables.bin (the asset policy's one
  exception, see docs/asset-policy.md).
- GameInput from XInput pads and the keyboard, with a keyboard stand-in
  pad; console timers (1 ms) for the whole process.
- Audio: XMA2 decoding on the emulated contexts, Opus on the decoder
  queues, the DSP interface as a stub; title memory placed below 2^40.
- Console texture layouts (sizes, tiling, detiling) and the layout
  library's imports.

GPU
- Draws, mesh dispatches and compute dispatches run on the host with
  shaders translated at first use and cached on disk; descriptor heaps,
  views, root signatures, barriers and host texture states; rectangle
  lists; comparison samplers.
- Title memory reaches the host through persistent mirrors that copy
  only pages written since the last copy; shader-written buffers are
  copied back.
- Presentation with frame pacing per event kind; framerate in the window
  caption.

Shaders
- DXIL emission for vertex, pixel, compute and mesh programs from the
  console's native code, with a differential test suite against the PC
  compile. World set: mesh 8,191 of 8,506, vertex/pixel 10,617 of
  12,346, compute 1,643 of 2,539; utility set complete.

Build
- Debugging aids (debug logs, frame capture, stack dumps, scripted keys,
  the host debug layer, the software adapter) exist only with the
  `diagnostics` feature; `[profile.diag]` keeps that build apart.

Not working yet
- In the world the host device is removed within seconds (descriptor
  handling fixes are in, unproven by a surviving run) and frames present
  black.
- 64-bit image atomics, merged geometry stages and the BVH builder's own
  shaders do not translate; reverb is silent.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
MarvisandClaude Fable 5.2 committed 2026-11-23 23:10:01 +01:00
1 parent bc3070991a
commit 2849477415
107 files changed
+42526 -868

No files matched your search

+8 -1
View File
@@ -27,12 +27,12 @@ impl Default for HostPolicy {
"ucrtbase.dll",
"vcruntime140*",
"msvcp140*",
// Off-machine traffic is refused in `modules::net`.
"ws2_32.dll",
"bcrypt.dll",
"crypt32.dll",
"ncrypt.dll",
"winhttp.dll",
"dnsapi.dll",
"sspicli.dll",
"cabinet.dll",
"avrt.dll",
@@ -44,6 +44,13 @@ impl Default for HostPolicy {
"ole32.dll",
"advapi32.dll",
"iphlpapi.dll",
// The title's crash handler writes minidumps with it (loaded by name).
"dbghelp.dll",
// Same APIs as the console's (XAudio2 ordinal 1 is XAudio2Create
// on both); Media Foundation reads local media files.
"xaudio2_9.dll",
"mfplat.dll",
"mfreadwrite.dll",
];
HostPolicy {
allow: allow.iter().map(|s| s.to_string()).collect(),
+5 -1
View File
@@ -18,6 +18,7 @@ pub mod runtime;
pub use host::HostPolicy;
pub use registry::{HleExport, HleModule, registry};
pub use victory_gpu::console;
use victory_loader::{ImportResolver, Provenance, Resolution};
use victory_pe::ImportSymbol;
@@ -101,7 +102,10 @@ mod tests {
Some(Provenance::Host)
);
// Console-only DLLs never pass through.
assert_eq!(r.classify("xmem.dll", &name("XMemAllocDefault")), None);
assert_eq!(
r.classify("xmem.dll", &name("XMemSetAllocationHooks")),
None
);
}
#[cfg(windows)]
+524
View File
@@ -0,0 +1,524 @@
//! The console's audio decoder (`xapu.dll`): Opus packets in, float PCM out.
//!
//! A title connects once for one kind of processing, gets a block of memory
//! for its packets and output, and then queues per-stream commands
//! (activate, process, reset, deactivate) and dequeues one result per
//! command. We decode each command when it is queued, so its result is ready
//! at once; the order of results is the order of commands.
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::alloc::Layout;
use std::collections::VecDeque;
use std::ffi::c_void;
use std::sync::Mutex;
use opus_pure::OpusDecoder;
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
use windows_sys::Win32::System::Threading::{CreateEventW, SetEvent};
use super::xasync::E_INVALIDARG;
use super::xgameruntime::{HRESULT, S_OK};
use crate::{HleModule, hle_export};
const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32;
const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
const QUEUE_FULL: HRESULT = 0x8AC8_1000_u32 as i32;
/// No result yet, which titles poll for.
pub(crate) const PENDING_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32;
const INVALID_COMMAND: HRESULT = 0x8AC8_1002_u32 as i32;
const INVALID_STREAM: HRESULT = 0x8AC8_1003_u32 as i32;
const ALREADY_ACTIVE: HRESULT = 0x8AC8_1005_u32 as i32;
const BAD_PACKET: HRESULT = 0x8AC8_1008_u32 as i32;
/// Processing kinds; only plain decoding is implemented.
const DECODE_OPUS: u32 = 1;
const ACTIVATE: u32 = 1;
const DEACTIVATE: u32 = 2;
const PROCESS: u32 = 3;
const NOTIFY: u32 = 4;
const RESET: u32 = 5;
/// Command option: signal the connection's event when the result is ready.
const SIGNAL: u32 = 1;
/// Connect options.
const DEINTERLEAVED_OUTPUT: u32 = 4;
const RESULT_EVENT: u32 = 8;
/// The longest Opus packet duration at 48 kHz (120 ms).
const MAX_FRAMES: usize = 5760;
#[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: HANDLE,
}
/// What every command starts with, and what its result echoes.
#[repr(C, packed)]
#[derive(Clone, Copy)]
pub struct CommandId {
kind: u32,
stream: u32,
sequence: u32,
options: u32,
context: u64,
}
#[repr(C, packed)]
struct Activate {
id: CommandId,
channels: u32,
init_length: u32,
init: *const c_void,
start_pitch: f32,
processing_length: u32,
processing: *mut c_void,
}
#[repr(C, packed)]
#[derive(Clone, Copy)]
struct Process {
id: CommandId,
pitch_ramp: f32,
target_pitch: f32,
first_frame: u32,
frame_count: u32,
input_length: u32,
input: *const u8,
output_length: u32,
output: *mut u8,
}
#[repr(C, packed)]
#[derive(Clone, Copy)]
pub struct ApuResult {
id: CommandId,
state: u32,
state_data: u64,
usec: u64,
error: HRESULT,
frames: u32,
output_length: u32,
output: *mut u8,
pitch: f32,
input_length: u32,
input: *const u8,
}
// SAFETY: the raw pointers are title addresses carried through, never
// dereferenced after the result is made.
unsafe impl Send for ApuResult {}
pub struct Connection {
memory: *mut u8,
layout: Layout,
event: HANDLE,
options: u32,
per_stream: u32,
state: Mutex<State>,
}
struct State {
streams: Vec<Option<OpusDecoder>>,
/// Results not yet dequeued, per stream.
queued: Vec<u32>,
results: VecDeque<ApuResult>,
commands: u32,
dequeued: u32,
}
fn lock(c: &Connection) -> std::sync::MutexGuard<'_, State> {
c.state.lock().unwrap_or_else(|e| e.into_inner())
}
pub extern "system" fn XApuConnect(
input: *const ConnectInput,
output: *mut ConnectOutput,
handle: *mut *mut Connection,
) -> HRESULT {
if input.is_null() || output.is_null() || handle.is_null() {
return E_INVALIDARG;
}
// SAFETY: checked non-null.
let input = unsafe { &*input };
if !(1..=500).contains(&input.streams)
|| !(1..=16).contains(&input.commands_per_stream)
|| input.memory == 0
{
return E_INVALIDARG;
}
if input.process != DECODE_OPUS {
// shortcut: rate conversion (decode-convert, PCM convert) is not
// implemented; add a resampler if a title connects for it.
tracing::warn!(
process = input.process,
"audio decoder: processing kind not implemented"
);
return E_NOTIMPL;
}
if input.frames_per_output != 0 {
return E_INVALIDARG;
}
let Ok(layout) = Layout::from_size_align(input.memory 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;
}
let event = if input.options & RESULT_EVENT != 0 {
// SAFETY: plain auto-reset event, no name.
unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) }
} else {
std::ptr::null_mut()
};
let streams = input.streams as usize;
tracing::info!(
streams,
memory = input.memory,
options = input.options,
"audio decoder connected"
);
let connection = Box::new(Connection {
memory,
layout,
event,
options: input.options,
per_stream: input.commands_per_stream,
state: Mutex::new(State {
streams: (0..streams).map(|_| None).collect(),
queued: vec![0; streams],
results: VecDeque::new(),
commands: 0,
dequeued: 0,
}),
});
// SAFETY: checked non-null.
unsafe {
output.write(ConnectOutput {
memory: memory.cast(),
result_event: event,
});
handle.write(Box::into_raw(connection));
}
S_OK
}
pub extern "system" fn XApuDisconnect(handle: *mut Connection) -> HRESULT {
if handle.is_null() {
return E_INVALIDARG;
}
// SAFETY: made by `XApuConnect`; disconnected once.
let connection = unsafe { Box::from_raw(handle) };
if !connection.event.is_null() {
// SAFETY: our event.
unsafe { CloseHandle(connection.event) };
}
// SAFETY: allocated in `XApuConnect` with this layout.
unsafe { std::alloc::dealloc(connection.memory, connection.layout) };
S_OK
}
pub extern "system" fn XApuEnqueueCommand(
handle: *mut Connection,
command: *const CommandId,
total: *mut u32,
) -> HRESULT {
if handle.is_null() || command.is_null() {
return E_INVALIDARG;
}
// SAFETY: a connection from `XApuConnect`; every command starts with an id.
let (connection, id) = unsafe { (&*handle, command.read_unaligned()) };
let mut state = lock(connection);
let stream = id.stream as usize;
if stream >= state.streams.len() {
return INVALID_STREAM;
}
if state.queued[stream] >= connection.per_stream {
return QUEUE_FULL;
}
let mut result = ApuResult {
id,
state: 0,
state_data: 0,
usec: 0,
error: S_OK,
frames: 0,
output_length: 0,
output: std::ptr::null_mut(),
pitch: 1.0,
input_length: 0,
input: std::ptr::null(),
};
let decoder = &mut state.streams[stream];
match id.kind {
ACTIVATE => {
// SAFETY: an activate command is this struct.
let channels = unsafe { command.cast::<Activate>().read_unaligned() }.channels;
tracing::debug!(stream, channels, "Opus stream activated");
result.error = if decoder.is_some() {
ALREADY_ACTIVE
} else {
match OpusDecoder::new(48_000, channels as usize) {
Ok(d) if (1..=2).contains(&channels) => {
*decoder = Some(d);
S_OK
}
_ => E_INVALIDARG,
}
};
}
DEACTIVATE => *decoder = None,
RESET => {
if let Some(d) = decoder {
let _ = d.reset_state();
}
}
NOTIFY => {}
PROCESS => {
// SAFETY: a process command is this struct.
let command = unsafe { command.cast::<Process>().read_unaligned() };
match decoder {
Some(d) => process(d, connection.options, &command, &mut result),
None => result.error = INVALID_STREAM,
}
}
_ => return INVALID_COMMAND,
}
state.queued[stream] += 1;
state.commands = state.commands.wrapping_add(1);
state.results.push_back(result);
if !total.is_null() {
// SAFETY: optional out parameter.
unsafe { total.write(state.commands) };
}
if id.options & SIGNAL != 0 && !connection.event.is_null() {
// SAFETY: our event.
unsafe { SetEvent(connection.event) };
}
S_OK
}
/// Decodes one packet into the command's output buffer, keeping the frames
/// from `first_frame` on, at most `frame_count` of them.
fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: &mut ApuResult) {
let channels = decoder.channels();
let (input, input_length) = (command.input, command.input_length);
let (output, output_length) = (command.output, command.output_length);
result.input = input;
result.input_length = input_length;
result.output = output;
if input.is_null() || output.is_null() || input_length == 0 {
result.error = E_INVALIDARG;
return;
}
// SAFETY: the title's packet in its connection memory.
let packet = unsafe { std::slice::from_raw_parts(input, input_length as usize) };
let mut pcm = vec![0f32; MAX_FRAMES * channels];
let decoded = match decoder.decode(packet, MAX_FRAMES, &mut pcm) {
Ok(n) => n,
Err(_) => {
result.error = BAD_PACKET;
return;
}
};
let first = (command.first_frame as usize).min(decoded);
let frames = (decoded - first)
.min(command.frame_count as usize)
.min(output_length as usize / (4 * channels));
let kept = &pcm[first * channels..(first + frames) * channels];
// SAFETY: the title's output buffer holds `output_length` bytes.
let out = unsafe { std::slice::from_raw_parts_mut(output.cast::<f32>(), frames * channels) };
if options & DEINTERLEAVED_OUTPUT != 0 && channels == 2 {
for (i, frame) in kept.as_chunks::<2>().0.iter().enumerate() {
(out[i], out[frames + i]) = (frame[0], frame[1]);
}
} else {
out.copy_from_slice(kept);
}
result.frames = frames as u32;
result.output_length = (frames * channels * 4) as u32;
}
pub extern "system" fn XApuDequeueResult(handle: *mut Connection, out: *mut ApuResult) -> HRESULT {
if handle.is_null() || out.is_null() {
return E_INVALIDARG;
}
// SAFETY: a connection from `XApuConnect`.
let mut state = lock(unsafe { &*handle });
let Some(result) = state.results.pop_front() else {
return PENDING_RESULTS;
};
let stream = result.id.stream as usize;
state.queued[stream] -= 1;
state.dequeued = state.dequeued.wrapping_add(1);
// SAFETY: the title passes room for one result.
unsafe { out.write_unaligned(result) };
S_OK
}
pub extern "system" fn XApuGetResultCount(handle: *mut Connection, total: *mut u32) -> u32 {
if handle.is_null() {
return 0;
}
// SAFETY: a connection from `XApuConnect`.
let state = lock(unsafe { &*handle });
if !total.is_null() {
// SAFETY: optional out parameter.
unsafe { total.write(state.dequeued) };
}
state.results.len() as u32
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "apu",
dlls: &["xapu.dll"],
exports: vec![
hle_export!(XApuConnect),
hle_export!(XApuDisconnect),
hle_export!(XApuEnqueueCommand),
hle_export!(XApuDequeueResult),
hle_export!(XApuGetResultCount),
],
}
}
#[cfg(test)]
mod tests {
use super::*;
use opus_pure::{Application, OpusEncoder};
fn id(kind: u32, stream: u32) -> CommandId {
CommandId {
kind,
stream,
sequence: 7,
options: 0,
context: 0x1234,
}
}
#[test]
fn decodes_opus_as_the_title_drives_it() {
assert_eq!(size_of::<ApuResult>(), 0x50);
// 256 mono/stereo streams, two commands each, as the title connects.
let input = ConnectInput {
process: DECODE_OPUS,
streams: 256,
commands_per_stream: 2,
memory: 0x10_4000,
frames_per_output: 0,
options: 1,
};
let mut output = ConnectOutput {
memory: std::ptr::null_mut(),
result_event: std::ptr::null_mut(),
};
let mut handle = std::ptr::null_mut();
assert_eq!(XApuConnect(&input, &mut output, &mut handle), S_OK);
let base = output.memory.cast::<u8>();
let activate = Activate {
id: id(ACTIVATE, 3),
channels: 2,
init_length: 0,
init: std::ptr::null(),
start_pitch: 1.0,
processing_length: 0,
processing: std::ptr::null_mut(),
};
assert_eq!(
XApuEnqueueCommand(handle, (&raw const activate).cast(), std::ptr::null_mut()),
S_OK
);
// A 20 ms stereo packet of a 440 Hz tone.
let tone: Vec<f32> = (0..960 * 2)
.map(|i| ((i / 2) as f32 * 440.0 * std::f32::consts::TAU / 48_000.0).sin() * 0.5)
.collect();
let mut encoder = OpusEncoder::new(48_000, 2, Application::Audio).unwrap();
let mut packet = [0u8; 1500];
let n = encoder.encode(&tone, 960, &mut packet).unwrap();
// SAFETY: inside the connection memory.
unsafe { std::ptr::copy_nonoverlapping(packet.as_ptr(), base, n) };
let process = Process {
id: id(PROCESS, 3),
pitch_ramp: 0.0,
target_pitch: 1.0,
first_frame: 0,
frame_count: 960,
input_length: n as u32,
input: base,
output_length: 0xf00 * 2,
output: base.wrapping_add(0x14000),
};
let mut total = 0;
assert_eq!(
XApuEnqueueCommand(handle, (&raw const process).cast(), &mut total),
S_OK
);
assert_eq!(total, 2);
// Two results queued for stream 3: its queue is full.
assert_eq!(
XApuEnqueueCommand(handle, (&raw const process).cast(), &mut total),
QUEUE_FULL
);
assert_eq!(XApuGetResultCount(handle, std::ptr::null_mut()), 2);
let mut result = std::mem::MaybeUninit::<ApuResult>::zeroed();
assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK);
// SAFETY: written above.
let first = unsafe { result.assume_init() };
let (kind, error, context) = (first.id.kind, first.error, first.id.context);
assert_eq!((kind, error, context), (ACTIVATE, S_OK, 0x1234));
assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK);
// SAFETY: written above.
let decoded = unsafe { result.assume_init() };
let (kind, error, frames, length) = (
decoded.id.kind,
decoded.error,
decoded.frames,
decoded.output_length,
);
assert_eq!((kind, error, frames, length), (PROCESS, S_OK, 960, 960 * 8));
// SAFETY: the decoder wrote 960 stereo frames there.
let pcm =
unsafe { std::slice::from_raw_parts(base.wrapping_add(0x14000).cast::<f32>(), 1920) };
let energy: f32 = pcm.iter().map(|s| s * s).sum::<f32>() / 1920.0;
assert!(energy > 0.01, "decoded a tone, energy {energy}");
assert_eq!(
XApuDequeueResult(handle, result.as_mut_ptr()),
PENDING_RESULTS
);
let mut dequeued = 0;
assert_eq!(XApuGetResultCount(handle, &mut dequeued), 0);
assert_eq!(dequeued, 2);
// A process on a stream that was never activated fails in its result.
let mut stray = process;
stray.id.stream = 4;
assert_eq!(
XApuEnqueueCommand(handle, (&raw const stray).cast(), &mut total),
S_OK
);
assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK);
// SAFETY: written above.
let error = unsafe { result.assume_init() }.error;
assert_eq!(error, INVALID_STREAM);
assert_eq!(XApuDisconnect(handle), S_OK);
}
}
+722 -114
View File
@@ -1,35 +1,36 @@
//! The console's audio hardware (`AcpHal.dll`, `xapu.dll`), enough for
//! middleware to start and then mix in software:
//! The console's audio hardware (`AcpHal.dll`):
//!
//! * 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.
//! * the XMA decoder: enabled XMA contexts are decoded on a thread of ours
//! into their output rings, like the hardware does.
//!
//! 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.
//! SHAPE's other units (rate conversion, EQ, filters, mixing through
//! flowgraphs) are not emulated, so voices that need them stay silent.
//! Mixed audio leaves through the host's WASAPI, which titles and
//! middleware reach through COM like on PC. fmod's console build sets up
//! the coprocessor inside `System_Create` and waits there for its first
//! command to be acknowledged; Grand Theft Auto VI uses only XMA contexts.
#![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::sync::{Mutex, MutexGuard, OnceLock, RwLock, RwLockReadGuard};
use std::time::Instant;
use super::xasync::E_INVALIDARG;
use super::xgameruntime::{HRESULT, S_OK};
use crate::{HleModule, hle_export};
#[cfg(all(windows, feature = "diagnostics"))]
pub mod capture;
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())
@@ -46,40 +47,110 @@ struct Block {
struct Heap {
/// By host address.
blocks: BTreeMap<usize, Block>,
next_apu: u32,
/// Host address by device address.
by_apu: BTreeMap<u32, usize>,
/// Free device address ranges, start to end, merged with neighbours.
free: BTreeMap<u32, u32>,
/// Set by `ApuCreateHeap` or the first allocation: the heap exists.
created: bool,
}
static HEAP: Mutex<Heap> = Mutex::new(Heap {
blocks: BTreeMap::new(),
next_apu: 0x0001_0000,
by_apu: BTreeMap::new(),
free: BTreeMap::new(),
created: false,
});
/// Device addresses start above 0, which means "none" to titles.
const APU_BASE: u32 = 0x0001_0000;
impl Heap {
/// First fit in the free ranges.
fn take(&mut self, size: u32, align: u32) -> Option<u32> {
if self.free.is_empty() && !self.created {
self.free.insert(APU_BASE, u32::MAX);
}
self.created = true;
let (start, end, apu) = self.free.iter().find_map(|(&start, &end)| {
let apu = start.checked_next_multiple_of(align)?;
(apu.checked_add(size)? <= end).then_some((start, end, apu))
})?;
self.free.remove(&start);
if start < apu {
self.free.insert(start, apu);
}
if apu + size < end {
self.free.insert(apu + size, end);
}
Some(apu)
}
fn give_back(&mut self, mut start: u32, mut end: u32) {
if let Some((&before, &before_end)) = self.free.range(..start).next_back()
&& before_end == start
{
self.free.remove(&before);
start = before;
}
if let Some(after_end) = self.free.remove(&end) {
end = after_end;
}
self.free.insert(start, end);
}
}
/// 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()?)?;
let apu = heap.take(u32::try_from(layout.size()).ok()?, align as u32)?;
// SAFETY: non-zero size.
let ptr = unsafe { std::alloc::alloc_zeroed(layout) };
if ptr.is_null() {
heap.give_back(apu, apu + layout.size() as u32);
return None;
}
heap.next_apu = next;
heap.blocks
.insert(ptr as usize, Block { size, apu, layout });
heap.by_apu.insert(apu, ptr as usize);
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) };
let mut heap = lock(&HEAP);
let Some(block) = heap.blocks.remove(&(ptr as usize)) else {
return;
};
heap.by_apu.remove(&block.apu);
heap.give_back(block.apu, block.apu + block.layout.size() as u32);
drop(heap);
// SAFETY: allocated by `heap_alloc` with this layout.
unsafe { std::alloc::dealloc(ptr, block.layout) };
}
/// Sizes the heap once, before anything is allocated from it. The console
/// reserves both parts up front; we allocate per block, so the sizes only
/// decide whether the call is valid.
// shortcut: the cached and non-cached sizes are not enforced as limits;
// enforce them if a title relies on running out.
pub extern "system" fn ApuCreateHeap(cached: u32, _non_cached: u32) -> HRESULT {
const ALREADY_ALLOCATED: HRESULT = 0x8ACA_0001_u32 as i32;
if cached == 0 {
return E_INVALIDARG;
}
let mut heap = lock(&HEAP);
if heap.created {
return ALREADY_ALLOCATED;
}
heap.created = true;
heap.free.insert(APU_BASE, u32::MAX);
S_OK
}
/// The host address of a device address, null outside the heap.
pub extern "system" fn ApuMapApuAddress(apu: u32) -> *mut c_void {
heap_unmap(apu).map_or(std::ptr::null_mut(), |p| p.cast())
}
/// The device address of any byte of a heap block, 0 elsewhere.
@@ -96,10 +167,22 @@ fn heap_map(ptr: usize) -> u32 {
/// 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)
let (&start, &host) = heap.by_apu.range(..=apu).next_back()?;
let block = &heap.blocks[&host];
(apu < start.saturating_add(block.size.max(1) as u32))
.then(|| (host + (apu - start) as usize) as *mut u8)
}
/// `len` bytes of title memory at a device address, if one heap block holds
/// them all.
fn heap_bytes<'a>(apu: u32, len: usize) -> Option<&'a mut [u8]> {
let heap = lock(&HEAP);
let (&start, &host) = heap.by_apu.range(..=apu).next_back()?;
let offset = (apu - start) as usize;
(offset + len <= heap.blocks[&host].size)
// SAFETY: inside a live heap block, which the title and the audio
// hardware share like on the console.
.then(|| unsafe { std::slice::from_raw_parts_mut((host + offset) as *mut u8, len) })
}
pub extern "system" fn ApuAlloc(
@@ -183,12 +266,16 @@ pub extern "system" fn AcpHalAllocateShapeContexts(contexts: *mut ShapeContexts)
std::ptr::addr_of_mut!((*contexts).apu).write_unaligned(addresses);
}
*allocated = Some(arrays.map(|p| p as usize));
let mut xma = XMA.write().unwrap_or_else(|e| e.into_inner());
xma.array = arrays[4] as usize;
xma.voices = (0..counts[4]).map(|_| Mutex::new(None)).collect();
S_OK
}
pub extern "system" fn AcpHalReleaseShapeContexts() -> HRESULT {
match lock(&CONTEXTS).take() {
Some(arrays) => {
*XMA.write().unwrap_or_else(|e| e.into_inner()) = Xma::EMPTY;
arrays.iter().for_each(|&p| heap_free(p as *mut u8));
S_OK
}
@@ -196,6 +283,410 @@ pub extern "system" fn AcpHalReleaseShapeContexts() -> HRESULT {
}
}
// The XMA decoder.
//
// An XMA context (16 words in the shared context array) names up to two
// input buffers of 2 KiB packets, a ring of 256-byte output blocks the
// hardware fills with 16-bit PCM, and the read offset the title advances
// by command. Words and bit fields, as titles write them:
// 0: input 0 size in packets (0-11), loop count (12-19, 255 forever),
// valid inputs (20-21), output size in blocks (22-26), write block
// (27-31, hardware);
// 1: input 1 size (0-11), loop end subframe (12-13), loop start subframes
// to skip (17-19), subframes to skip at the start (24-26), sample rate
// (27-28: 24, 32, 44.1, 48 kHz), stereo (29), output writable (31);
// 2: read position in bits (0-25), error status (26-30), error (31);
// 3: loop start in bits (0-25); 4: loop end in bits (0-25), current input
// (31); 5, 6: input addresses; 7: output address; 8: overlap buffer;
// 9: read block (0-4).
// Titles read back only the write block, "writable" and the read block,
// and take whatever lies between read and write.
// shortcut: each enabled context decodes from a cold state and the overlap
// buffer is ignored (titles copy it between consecutive contexts of one
// voice); keep decoder state there if a title's seams turn out audible.
use victory_formats::xma;
const ENABLE_XMA: u32 = 5;
const ENABLE_XMAS: u32 = 6;
const DISABLE_XMA: u32 = 7;
const DISABLE_XMAS: u32 = 8;
const ADVANCE_XMA_READ: u32 = 18;
const BLOCK_BYTES: usize = 256;
const SAMPLES_PER_BLOCK: usize = BLOCK_BYTES / 2;
/// Error status: the input ran out.
const INPUT_INVALID: u32 = 4;
struct Voice {
decoder: Option<xma::Decoder>,
pcm: VecDeque<i16>,
/// Samples per channel still to drop (start or loop subframe skips).
skip: usize,
ended: bool,
trace: Trace,
}
/// What a voice did, for the debug log when it is disabled.
struct Trace {
since: Instant,
/// Samples per channel written to the ring.
produced: usize,
/// Blocks the title took (command 18), how often, and how often it
/// found the ring less than full.
taken: usize,
takes: u32,
partial_takes: u32,
frames: u32,
bad_frames: u32,
/// The loudest sample written.
peak: i16,
/// Milliseconds after enabling when the input ran out.
ended_ms: Option<u128>,
}
struct Xma {
/// Host address of the context array.
array: usize,
/// One entry per context, `Some` while enabled. Each has its own lock,
/// so a command for one voice never waits for others to decode (the
/// title sends them from its time-critical mixer thread).
voices: Vec<Mutex<Option<Voice>>>,
}
impl Xma {
const EMPTY: Xma = Xma {
array: 0,
voices: Vec::new(),
};
}
/// Written only when the context arrays are allocated or released.
static XMA: RwLock<Xma> = RwLock::new(Xma::EMPTY);
fn xma() -> RwLockReadGuard<'static, Xma> {
XMA.read().unwrap_or_else(|e| e.into_inner())
}
/// A context's words in title memory.
#[derive(Clone, Copy)]
struct Context(*mut u32);
impl Context {
fn get(self, word: usize) -> u32 {
// SAFETY: inside the context array; the title reads and writes it
// concurrently, like the hardware's.
unsafe { self.0.add(word).read_volatile() }
}
fn set(self, word: usize, value: u32) {
// SAFETY: as above.
unsafe { self.0.add(word).write_volatile(value) }
}
fn field(self, word: usize, shift: u32, bits: u32) -> u32 {
(self.get(word) >> shift) & ((1 << bits) - 1)
}
fn set_field(self, word: usize, shift: u32, bits: u32, value: u32) {
let mask = ((1u32 << bits) - 1) << shift;
self.set(word, (self.get(word) & !mask) | ((value << shift) & mask));
}
fn channels(self) -> usize {
1 + self.field(1, 29, 1) as usize
}
}
impl Xma {
fn context(&self, index: u32) -> Option<Context> {
((index as usize) < self.voices.len() && self.array != 0)
.then(|| Context((self.array + index as usize * 64) as *mut u32))
}
fn enable(&self, index: u32) {
let Some(context) = self.context(index) else {
return;
};
let mut slot = lock(&self.voices[index as usize]);
context.set_field(2, 26, 6, 0);
tracing::debug!(
index,
words = ?(0..10).map(|w| format!("{:08x}", context.get(w))).collect::<Vec<_>>(),
"XMA voice enabled"
);
#[cfg(feature = "diagnostics")]
dump_input(index, context);
*slot = Some(Voice {
decoder: None,
pcm: VecDeque::new(),
skip: context.field(1, 24, 3) as usize * xma::SUBFRAME_SAMPLES,
ended: false,
trace: Trace {
since: Instant::now(),
produced: 0,
taken: 0,
takes: 0,
partial_takes: 0,
frames: 0,
bad_frames: 0,
peak: 0,
ended_ms: None,
},
});
drop(slot);
wake_decoder();
}
fn disable(&self, index: u32) {
let Some(context) = self.context(index) else {
return;
};
let Some(voice) = lock(&self.voices[index as usize]).take() else {
return;
};
let t = &voice.trace;
tracing::debug!(
index,
ms = t.since.elapsed().as_millis(),
produced = t.produced,
taken = t.taken * SAMPLES_PER_BLOCK / context.channels(),
takes = t.takes,
partial_takes = t.partial_takes,
frames = t.frames,
bad_frames = t.bad_frames,
peak = t.peak,
input_ended_ms = ?t.ended_ms,
read_bit = context.field(2, 0, 26),
input_bits = context.field(0, 0, 12) * xma::PACKET_BYTES as u32 * 8,
"XMA voice disabled"
);
}
/// Moves the title's read block on, which frees output space.
fn advance_read(&self, index: u32, blocks: u32) {
let Some(context) = self.context(index) else {
return;
};
// The decoder writes the same words.
let mut slot = lock(&self.voices[index as usize]);
let size = context.field(0, 22, 5).max(1);
let read = (context.field(9, 0, 5) + blocks) % size;
context.set_field(9, 0, 5, read);
if blocks > 0 {
context.set_field(1, 31, 1, 1);
}
if let Some(voice) = &mut *slot {
let t = &mut voice.trace;
t.taken += blocks as usize;
t.takes += 1;
t.partial_takes += u32::from(blocks < size);
}
drop(slot);
wake_decoder();
}
/// Fills every enabled context's output as far as it has room.
fn pump(&self) {
let start = Instant::now();
let mut active = 0;
for index in 0..self.voices.len() as u32 {
if let (Some(context), Some(voice)) =
(self.context(index), &mut *lock(&self.voices[index as usize]))
{
pump(context, voice);
active += 1;
}
}
let took = start.elapsed();
if took.as_millis() >= 4 {
tracing::debug!(active, ms = took.as_millis(), "slow XMA decoding pass");
}
}
}
fn pump(context: Context, voice: &mut Voice) {
let size = context.field(0, 22, 5);
if size == 0 {
return;
}
while context.field(1, 31, 1) == 1 {
if voice.pcm.len() < SAMPLES_PER_BLOCK && !decode(context, voice) {
return;
}
let write = context.field(0, 27, 5);
let address = context.get(7) as usize + write as usize * BLOCK_BYTES;
let Some(out) = heap_bytes(address as u32, BLOCK_BYTES) else {
return;
};
for pair in out.as_chunks_mut::<2>().0 {
let sample = voice.pcm.pop_front().unwrap_or(0);
voice.trace.peak = voice.trace.peak.max(sample.saturating_abs());
pair.copy_from_slice(&sample.to_le_bytes());
}
voice.trace.produced += SAMPLES_PER_BLOCK / context.channels();
let write = (write + 1) % size;
context.set_field(0, 27, 5, write);
if write == context.field(9, 0, 5) {
// Full: nothing more until the title advances its read block.
context.set_field(1, 31, 1, 0);
}
}
}
/// Decodes the next frame of the current input into `voice.pcm`; false
/// when there is nothing left to decode.
fn decode(context: Context, voice: &mut Voice) -> bool {
if voice.ended {
return false;
}
let channels = context.channels();
let mut current = context.field(4, 31, 1);
let valid = context.field(0, 20, 2);
if valid & (1 << current) == 0 {
if valid & (1 << (1 - current)) == 0 {
// Out of input: the overlap tail, then nothing.
if let Some(decoder) = &mut voice.decoder {
let mut tail = Vec::new();
decoder.flush(&mut tail);
voice.pcm.extend(tail);
}
voice.ended = true;
voice.trace.ended_ms = Some(voice.trace.since.elapsed().as_millis());
context.set_field(2, 26, 5, INPUT_INVALID);
context.set_field(2, 31, 1, 1);
return !voice.pcm.is_empty();
}
current = 1 - current;
context.set_field(4, 31, 1, current);
context.set_field(2, 0, 26, 0);
}
let (address, packets) = match current {
0 => (context.get(5), context.field(0, 0, 12)),
_ => (context.get(6), context.field(1, 0, 12)),
};
let Some(data) = heap_bytes(address & !0x7ff, packets as usize * xma::PACKET_BYTES) else {
context.set_field(0, 20 + current, 1, 0);
return true;
};
let mut at = context.field(2, 0, 26) as usize;
if at < 32 {
at = 32 + xma::packet(data, 0).map_or(0, |p| p.first_frame_bit as usize);
}
let Some(frame) = xma::read_frame(data, at) else {
// This input is used up.
context.set_field(0, 20 + current, 1, 0);
return true;
};
let decoder = voice.decoder.get_or_insert_with(|| {
const RATES: [u32; 4] = [24_000, 32_000, 44_100, 48_000];
xma::Decoder::new(channels, RATES[context.field(1, 27, 2) as usize])
});
let mut pcm = Vec::with_capacity(xma::FRAME_SAMPLES * channels);
voice.trace.frames += 1;
if let Err(e) = decoder.decode(&frame.data, frame.bits, &mut pcm) {
voice.trace.bad_frames += 1;
if voice.trace.bad_frames <= 2 {
tracing::debug!(
at,
bits = frame.bits,
head = ?&frame.data[..frame.data.len().min(8)],
%e,
"XMA frame did not decode"
);
}
}
let mut next = frame.next.unwrap_or(0);
let loops = context.field(0, 12, 8);
let loop_end = context.field(4, 0, 26) as usize;
let ends_loop = loop_end != 0
&& (frame.start == loop_end
|| (frame.start < loop_end && frame.next.is_none_or(|n| loop_end < n)));
if loops > 0 && ends_loop {
let keep = (context.field(1, 12, 2) as usize + 1) * xma::SUBFRAME_SAMPLES * channels;
pcm.truncate(keep);
next = context.field(3, 0, 26) as usize;
voice.skip = context.field(1, 17, 3) as usize * xma::SUBFRAME_SAMPLES;
if loops != 255 {
context.set_field(0, 12, 8, loops - 1);
}
}
let skip = (voice.skip * channels).min(pcm.len());
voice.skip -= skip / channels;
voice.pcm.extend(&pcm[skip..]);
if next == 0 {
context.set_field(0, 20 + current, 1, 0);
}
context.set_field(2, 0, 26, next as u32);
true
}
/// `VICTORY_XMA_DUMP=<dir>`: saves the context words (`<n>-<index>.ctx`)
/// and input buffer 0 (`.xma`) of the first 32 voices enabled, to test
/// the decoder on a title's streams outside the title.
#[cfg(feature = "diagnostics")]
fn dump_input(index: u32, context: Context) {
static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let Some(dir) = std::env::var_os("VICTORY_XMA_DUMP") else {
return;
};
let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if n >= 32 {
return;
}
let dir = std::path::PathBuf::from(dir);
let words: Vec<u8> = (0..16).flat_map(|w| context.get(w).to_le_bytes()).collect();
let input = heap_bytes(
context.get(5) & !0x7ff,
context.field(0, 0, 12) as usize * xma::PACKET_BYTES,
);
let _ = std::fs::create_dir_all(&dir);
let _ = std::fs::write(dir.join(format!("{n:02}-{index}.ctx")), words);
let _ = std::fs::write(dir.join(format!("{n:02}-{index}.xma")), input.unwrap_or_default());
}
/// Starts the decoding thread on the first enabled voice, and has it fill
/// rings now: a voice just enabled or read from.
fn wake_decoder() {
static DECODER: OnceLock<std::thread::Thread> = OnceLock::new();
DECODER
.get_or_init(|| {
std::thread::Builder::new()
.name("victory XMA decoder".into())
.spawn(|| {
loop {
xma().pump();
// A 256-byte output block lasts 2.7 ms at 48 kHz mono.
std::thread::park_timeout(std::time::Duration::from_millis(2));
}
})
.map_or_else(|_| std::thread::current(), |h| h.thread().clone())
})
.unpark();
}
/// Runs an XMA command; false for one this does not know.
fn xma_command(command: u32, word: impl Fn(usize) -> Option<u32>) -> bool {
let xma = xma();
match command {
ENABLE_XMA => xma.enable(word(0).unwrap_or(u32::MAX)),
DISABLE_XMA => xma.disable(word(0).unwrap_or(u32::MAX)),
ENABLE_XMAS | DISABLE_XMAS => {
for i in 0..xma.voices.len() as u32 {
if word(i as usize / 32).unwrap_or(0) & (1 << (i % 32)) != 0 {
match command {
ENABLE_XMAS => xma.enable(i),
_ => xma.disable(i),
}
}
}
}
ADVANCE_XMA_READ => xma.advance_read(word(0).unwrap_or(u32::MAX), word(1).unwrap_or(0)),
_ => return false,
}
true
}
// The audio coprocessor.
const LOAD_FLOWGRAPH: u32 = 1;
@@ -223,6 +714,10 @@ struct State {
/// Message kinds the title registered for.
mask: u32,
messages: VecDeque<Message>,
/// Queue size given to `connect`.
capacity: usize,
/// Messages lost to a full queue since the last one queued.
dropped: u32,
since: Instant,
}
@@ -235,15 +730,20 @@ impl State {
(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.
/// Queues a registered message; a full queue drops it and counts it in
/// the next one that fits.
fn post(&mut self, kind: u32, data: &[u8]) {
if self.mask & kind == 0 {
return;
}
if self.messages.len() >= self.capacity {
self.dropped = self.dropped.saturating_add(1);
tracing::debug!(kind, dropped = self.dropped, "coprocessor message dropped");
return;
}
let mut message = Message {
kind,
dropped: 0,
dropped: std::mem::take(&mut self.dropped),
usec: self.usec() as u32,
data: [0; 16],
};
@@ -284,11 +784,13 @@ fn state(this: *mut Acp) -> MutexGuard<'static, State> {
lock(unsafe { &(*this).state })
}
extern "system" fn connect(this: *mut Acp, commands: u32, _messages: u32) -> HRESULT {
extern "system" fn connect(this: *mut Acp, commands: u32, messages: u32) -> HRESULT {
if commands == 0 {
return E_INVALIDARG;
}
state(this).connected = true;
let mut state = state(this);
state.connected = true;
state.capacity = messages as usize;
S_OK
}
@@ -330,6 +832,10 @@ extern "system" fn submit(
let flowgraph = word(1).unwrap_or(0);
state.post(FLOWGRAPH_COMPLETED, &flowgraph.to_le_bytes());
}
_ if xma_command(command, word) => {}
// shortcut: context updates and the other SHAPE units' commands are
// acknowledged but not carried out; add them when a title sends
// them (each kind is logged once above).
_ => {}
}
if id != 0 {
@@ -378,6 +884,8 @@ pub extern "system" fn AcpHalCreate(out: *mut *mut Acp) -> HRESULT {
connected: false,
mask: 0,
messages: VecDeque::new(),
capacity: 0,
dropped: 0,
since: Instant::now(),
}),
});
@@ -386,98 +894,20 @@ pub extern "system" fn AcpHalCreate(out: *mut *mut Acp) -> HRESULT {
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"],
dlls: &["acphal.dll"],
exports: vec![
hle_export!(AcpHalAllocateShapeContexts),
hle_export!(AcpHalReleaseShapeContexts),
hle_export!(AcpHalCreate),
hle_export!(ApuAlloc),
hle_export!(ApuCreateHeap),
hle_export!(ApuFree),
hle_export!(ApuIsVirtualAddressValid),
hle_export!(ApuMapApuAddress),
hle_export!(ApuMapVirtualAddress),
hle_export!(XApuConnect),
hle_export!(XApuEnqueueCommand),
hle_export!(XApuDequeueResult),
hle_export!(XApuDisconnect),
],
}
}
@@ -488,6 +918,7 @@ mod tests {
#[test]
fn heap_maps_every_byte_of_a_block() {
let _serial = lock(&CONTEXT_TESTS);
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));
@@ -500,8 +931,185 @@ mod tests {
assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 6, 1), E_INVALIDARG);
}
/// The context arrays and the heap exist once per process: tests that
/// allocate from them run one at a time (a concurrent allocation could
/// take a freed range a test expects back).
static CONTEXT_TESTS: Mutex<()> = Mutex::new(());
#[test]
fn heap_reuses_freed_addresses() {
let _serial = lock(&CONTEXT_TESTS);
let (mut a, mut b, mut c) = (
std::ptr::null_mut(),
std::ptr::null_mut(),
std::ptr::null_mut(),
);
let (mut apu_a, mut apu_b, mut apu_c) = (0, 0, 0);
assert_eq!(ApuAlloc(&mut a, &mut apu_a, 0x1000, 0x1000, 1), S_OK);
assert_eq!(ApuAlloc(&mut b, &mut apu_b, 0x1000, 0x1000, 1), S_OK);
ApuFree(a);
assert_eq!(ApuAlloc(&mut c, &mut apu_c, 0x800, 0x800, 1), S_OK);
// The freed range is free again, whichever part `c` took.
assert!(
lock(&HEAP)
.free
.iter()
.any(|(&s, &e)| s <= apu_a + 0x800 && apu_a + 0x1000 <= e)
|| apu_c == apu_a
);
assert_eq!(
ApuMapApuAddress(apu_b + 8),
b.cast::<u8>().wrapping_add(8).cast()
);
assert!(ApuMapApuAddress(0).is_null());
assert_eq!(
ApuCreateHeap(64 << 20, 0),
0x8ACA_0001_u32 as i32,
"too late"
);
ApuFree(b);
ApuFree(c);
}
/// Two packets of three silent mono frames each: a fixed one-subframe
/// layout, no transmitted coefficients.
fn silent_stream() -> Vec<u8> {
let mut data = vec![0xffu8; 2 * xma::PACKET_BYTES];
let mut put = |at: usize, value: u32, width: usize| {
for i in 0..width {
let (p, bit) = (at + i, (value >> (width - 1 - i)) & 1);
data[p / 8] = (data[p / 8] & !(0x80 >> (p % 8))) | ((bit as u8) << (7 - p % 8));
}
};
for packet in 0..2 {
let base = packet * xma::PACKET_BYTES * 8;
put(base, 3 << 26, 32);
for frame in 0..3 {
let at = base + 32 + frame * 31;
put(at, 31, 15); // length
put(at + 15, 0b10, 2); // fixed layout, one 512-sample subframe
put(at + 17, 0, 8 + 1 + 3 + 2); // gain, no trim, empty subframe
}
}
data
}
#[test]
fn xma_contexts_decode_into_their_output_rings() {
let _serial = lock(&CONTEXT_TESTS);
let mut request = ShapeContexts {
counts: [0, 0, 0, 0, 4, 0],
arrays: [std::ptr::null_mut(); 6],
apu: [0; 6],
};
assert_eq!(AcpHalAllocateShapeContexts(&mut request), S_OK);
let context = Context(request.arrays[4].cast::<u32>().wrapping_add(16));
let (mut input, mut input_apu) = (std::ptr::null_mut(), 0);
assert_eq!(ApuAlloc(&mut input, &mut input_apu, 0x1000, 0x800, 1), S_OK);
let stream = silent_stream();
// SAFETY: two packets were allocated.
unsafe { std::ptr::copy_nonoverlapping(stream.as_ptr(), input.cast(), stream.len()) };
let (mut output, mut output_apu) = (std::ptr::null_mut(), 0);
assert_eq!(
ApuAlloc(&mut output, &mut output_apu, 0x400, 0x100, 2),
S_OK
);
// SAFETY: the ring was just allocated.
unsafe { output.cast::<u8>().write_bytes(0x55, 0x400) };
// As the title sets one up: two packets, input 0 valid, a ring of
// four blocks, writable, 48 kHz mono, reading from the first frame.
context.set(0, 2 | 1 << 20 | 4 << 22);
context.set(1, 1 << 31 | 3 << 27);
context.set(2, 32);
context.set(5, input_apu);
context.set(7, output_apu);
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, 0x1000, 0x1000), S_OK);
let submit = |command: u32, words: &[u32]| {
assert_eq!(
(m.submit)(acp, command, 0xf1, u32::MAX, words.as_ptr().cast(), 0),
S_OK
);
};
submit(ENABLE_XMA, &[1]);
xma().pump();
// Full: all four blocks written (silence), the write block wrapped
// onto the read block, and the ring no longer writable.
assert_eq!(context.field(0, 27, 5), 0);
assert_eq!(context.field(1, 31, 1), 0);
// SAFETY: the ring.
let ring = unsafe { std::slice::from_raw_parts(output.cast::<u8>(), 0x400) };
assert!(ring.iter().all(|&b| b == 0));
// Read four blocks at a time until the input has run out and the
// ring keeps room (the decoding thread may fill it too).
for _ in 0..20 {
submit(ADVANCE_XMA_READ, &[1, 4]);
xma().pump();
if context.field(2, 31, 1) == 1 && context.field(1, 31, 1) == 1 {
break;
}
}
// Six frames and the flushed tail: 3,328 samples, 26 blocks.
let produced = |x: &Xma| lock(&x.voices[1]).as_ref().map(|v| v.trace.produced);
assert_eq!(produced(&xma()), Some(26 * SAMPLES_PER_BLOCK));
assert_eq!(context.field(0, 20, 2), 0, "input used up");
assert_eq!(context.field(2, 26, 5), INPUT_INVALID);
submit(DISABLE_XMA, &[1]);
assert_eq!(produced(&xma()), None);
(m.release)(acp);
ApuFree(input);
ApuFree(output);
assert_eq!(AcpHalReleaseShapeContexts(), S_OK);
}
#[test]
fn full_message_queues_count_drops() {
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, 16, 2), S_OK);
let mask = COMMAND_COMPLETED;
assert_eq!(
(m.submit)(
acp,
REGISTER_MESSAGES,
0,
u32::MAX,
(&raw const mask).cast(),
0
),
S_OK
);
for id in 1..=4 {
assert_eq!((m.submit)(acp, 12, id, u32::MAX, std::ptr::null(), 0), S_OK);
}
assert_eq!((m.message_count)(acp), 2);
let mut message = Message {
kind: 0,
dropped: 0,
usec: 0,
data: [0; 16],
};
assert!((m.pop_message)(acp, &mut message) && (m.pop_message)(acp, &mut message));
assert_eq!((m.submit)(acp, 12, 5, u32::MAX, std::ptr::null(), 0), S_OK);
assert!((m.pop_message)(acp, &mut message));
let dropped = message.dropped;
assert_eq!(dropped, 2);
(m.release)(acp);
}
#[test]
fn startup_as_fmod_does_it() {
let _serial = lock(&CONTEXT_TESTS);
// Context arrays: rate conversion, DMA and XMA.
let mut request = ShapeContexts {
counts: [0x200, 0, 0, 0x400, 0x200, 0],
@@ -0,0 +1,229 @@
//! Debugging aid: `VICTORY_AUDIO_CAPTURE=<file.wav>` records what the title
//! plays, 48 kHz stereo 16-bit, through process loopback: our own process
//! tree only, never the rest of the host's mix. Stretches where nothing was
//! played are written as silence, so the file keeps real time.
//!
//! The recorder runs in a child copy of this executable: an audio client
//! in the title's process raises that process's timer resolution, which
//! changes how the title's own waits behave.
use std::fs::File;
use std::io::{Seek, SeekFrom, Write};
use std::path::Path;
use std::time::{Duration, Instant};
use windows::Win32::Media::Audio::{
AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY, AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_LOOPBACK,
AUDIOCLIENT_ACTIVATION_PARAMS, AUDIOCLIENT_ACTIVATION_PARAMS_0,
AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK, AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS,
ActivateAudioInterfaceAsync, IActivateAudioInterfaceAsyncOperation,
IActivateAudioInterfaceCompletionHandler, IActivateAudioInterfaceCompletionHandler_Impl,
IAudioCaptureClient, IAudioClient, PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE,
VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, WAVE_FORMAT_PCM, WAVEFORMATEX,
};
use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx};
use windows::Win32::Foundation::WAIT_OBJECT_0;
use windows::Win32::System::Threading::{
OpenProcess, PROCESS_SYNCHRONIZE, Sleep, WaitForSingleObject,
};
use windows::core::{HRESULT, IUnknown, Interface, Ref, implement};
const RATE: u32 = 48_000;
const FRAME_BYTES: usize = 4;
/// Activation completes asynchronously; the recording thread polls for it.
#[implement(IActivateAudioInterfaceCompletionHandler)]
struct Activated;
impl IActivateAudioInterfaceCompletionHandler_Impl for Activated_Impl {
fn ActivateCompleted(
&self,
_: Ref<IActivateAudioInterfaceAsyncOperation>,
) -> windows::core::Result<()> {
Ok(())
}
}
/// Names the process to record, in the recorder's environment.
const TARGET: &str = "VICTORY_AUDIO_CAPTURE_OF";
/// Starts the recorder if `VICTORY_AUDIO_CAPTURE` names a file. With this
/// module's debug log, also logs once a second what a `Sleep(1)` takes in
/// this process (the title's millisecond waits get the same).
pub fn start() {
if tracing::enabled!(tracing::Level::DEBUG) {
let _ = std::thread::Builder::new()
.name("victory timing probe".into())
.spawn(|| {
loop {
std::thread::sleep(Duration::from_secs(1));
let at = Instant::now();
// SAFETY: plain wait.
unsafe { Sleep(1) };
let ms = at.elapsed().as_secs_f32() * 1000.0;
tracing::debug!(ms, "Sleep(1) took");
}
});
}
if std::env::var_os("VICTORY_AUDIO_CAPTURE").is_some()
&& let Err(e) = std::env::current_exe().and_then(|exe| {
std::process::Command::new(exe)
.env(TARGET, std::process::id().to_string())
.spawn()
})
{
tracing::warn!("audio capture not started: {e}");
}
}
/// In the recorder (a child started by [`start`]): records until the
/// target exits and returns true; false in any other process.
pub fn child() -> bool {
let (Some(pid), Some(path)) = (
std::env::var(TARGET).ok().and_then(|p| p.parse().ok()),
std::env::var_os("VICTORY_AUDIO_CAPTURE"),
) else {
return false;
};
if let Err(e) = record(pid, Path::new(&path)) {
tracing::warn!("audio capture stopped: {e}");
}
true
}
fn header(frames: u64) -> [u8; 44] {
let data = u32::try_from(frames * FRAME_BYTES as u64).unwrap_or(u32::MAX - 36);
let mut h = [0u8; 44];
let fields: [(&[u8], usize); 11] = [
(b"RIFF", 0),
(&(36 + data).to_le_bytes(), 4),
(b"WAVEfmt ", 8),
(&16u32.to_le_bytes(), 16),
(&1u16.to_le_bytes(), 20),
(&2u16.to_le_bytes(), 22),
(&RATE.to_le_bytes(), 24),
(&(RATE * FRAME_BYTES as u32).to_le_bytes(), 28),
(&(FRAME_BYTES as u16).to_le_bytes(), 32),
(&16u16.to_le_bytes(), 34),
(b"data", 36),
];
for (bytes, at) in fields {
h[at..at + bytes.len()].copy_from_slice(bytes);
}
h[40..].copy_from_slice(&data.to_le_bytes());
h
}
fn record(pid: u32, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
// SAFETY: COM calls with parameters built here; buffers are used only
// between `GetBuffer` and `ReleaseBuffer`.
unsafe {
CoInitializeEx(None, COINIT_MULTITHREADED).ok()?;
let target = OpenProcess(PROCESS_SYNCHRONIZE, false, pid)?;
let params = AUDIOCLIENT_ACTIVATION_PARAMS {
ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,
Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 {
ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS {
TargetProcessId: pid,
ProcessLoopbackMode: PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE,
},
},
};
/// A `PROPVARIANT` holding a blob (`VT_BLOB`).
#[repr(C)]
struct Blob {
vt: u16,
reserved: [u16; 3],
size: u32,
data: *const AUDIOCLIENT_ACTIVATION_PARAMS,
}
let blob = Blob {
vt: 0x41,
reserved: [0; 3],
size: size_of_val(&params) as u32,
data: &params,
};
let handler: IActivateAudioInterfaceCompletionHandler = Activated.into();
let operation = ActivateAudioInterfaceAsync(
VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK,
&IAudioClient::IID,
Some((&raw const blob).cast()),
&handler,
)?;
let client = loop {
let (mut hr, mut client) = (HRESULT(0), None::<IUnknown>);
// Fails (`E_ILLEGAL_METHOD_CALL`) until activation completes.
if operation.GetActivateResult(&mut hr, &mut client).is_ok() {
hr.ok()?;
break client.ok_or("no audio client")?.cast::<IAudioClient>()?;
}
std::thread::sleep(Duration::from_millis(10));
};
let format = WAVEFORMATEX {
wFormatTag: WAVE_FORMAT_PCM as u16,
nChannels: 2,
nSamplesPerSec: RATE,
nAvgBytesPerSec: RATE * FRAME_BYTES as u32,
nBlockAlign: FRAME_BYTES as u16,
wBitsPerSample: 16,
cbSize: 0,
};
client.Initialize(
AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_STREAMFLAGS_LOOPBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,
10_000_000,
0,
&format,
None,
)?;
let capture: IAudioCaptureClient = client.GetService()?;
let mut file = File::create(path)?;
file.write_all(&header(0))?;
client.Start()?;
tracing::info!(path = %path.display(), "recording the title's audio");
let (mut written, mut first) = (0u64, None);
let mut patched = Instant::now();
loop {
std::thread::sleep(Duration::from_millis(10));
let ended = WaitForSingleObject(target, 0) == WAIT_OBJECT_0;
while capture.GetNextPacketSize()? > 0 {
let (mut data, mut frames, mut flags, mut qpc) = (std::ptr::null_mut(), 0, 0, 0);
capture.GetBuffer(&mut data, &mut frames, &mut flags, None, Some(&mut qpc))?;
// Where this packet belongs, from its time stamp (100 ns).
let at = (qpc - *first.get_or_insert(qpc)) * u64::from(RATE) / 10_000_000;
if at > written + u64::from(RATE / 500) {
tracing::debug!(
ms = (at - written) * 1000 / u64::from(RATE),
"audio capture: nothing played"
);
let silence = vec![0u8; (at - written) as usize * FRAME_BYTES];
file.write_all(&silence)?;
written = at;
}
let bytes = frames as usize * FRAME_BYTES;
if flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 {
file.write_all(&vec![0u8; bytes])?;
} else {
file.write_all(std::slice::from_raw_parts(data, bytes))?;
}
if flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY.0 as u32 != 0 && written > 0 {
tracing::debug!("audio capture: discontinuity");
}
written += u64::from(frames);
capture.ReleaseBuffer(frames)?;
}
if ended || patched.elapsed() >= Duration::from_secs(1) {
// Valid sizes at any time: runs end by being killed.
file.seek(SeekFrom::Start(0))?;
file.write_all(&header(written))?;
file.seek(SeekFrom::End(0))?;
patched = Instant::now();
}
if ended {
return Ok(());
}
}
}
}
+56 -3
View File
@@ -1,23 +1,76 @@
//! `d3d12_xs.dll`: device creation. The device and everything it creates
//! live in `victory-gpu`.
//! `d3d12_xs.dll`: virtual memory setup, device creation, root signature
//! serialization. The device and everything it creates live in
//! `victory-gpu`.
use std::ffi::c_void;
use victory_gpu::device;
use victory_gpu::object::{HRESULT, Iid, Object};
use crate::{HleExport, HleModule};
/// Device creation; first hands the device the title's general allocator
/// (`XMemAlloc`, which honours the title's hooks) for resource memory.
extern "system" fn create_device(
adapter: *const c_void,
parameters: *const u32,
iid: *const Iid,
out: *mut *const Object,
) -> HRESULT {
victory_gpu::resource::use_allocator(super::xmem::XMemAlloc, super::xmem::XMemFree);
victory_gpu::resource::use_page_mapper(super::xmem::map_alias);
#[cfg(windows)]
victory_gpu::on_failure(host_gpu_failed);
device::create(adapter, parameters, iid, out)
}
/// A host GPU failure ends the run like a crash: reported to the crash log,
/// then the process ends as the console ends a title.
#[cfg(windows)]
fn host_gpu_failed(what: &str) -> ! {
use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};
victory_loader::log_crash(&format!("VIctory: host GPU failure: {what}"));
const DXGI_ERROR_DEVICE_REMOVED: u32 = 0x887A_0005;
// SAFETY: ends our own process.
unsafe { TerminateProcess(GetCurrentProcess(), DXGI_ERROR_DEVICE_REMOVED) };
unreachable!("the process has ended")
}
/// Keeps the host's translations of the title's shaders in `dir` (a
/// folder of the cache) across runs.
pub fn use_shader_cache(dir: std::path::PathBuf) {
#[cfg(windows)]
victory_gpu::shader_cache::use_shader_cache(dir);
#[cfg(not(windows))]
let _ = dir;
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "d3d12x",
dlls: &["d3d12_xs.dll"],
exports: vec![
HleExport {
name: "D3D12ConfigureVirtualMemoryX",
address: device::configure_virtual_memory as *const () as usize,
},
HleExport {
name: "D3D12XboxCreateDevice",
address: device::create as *const () as usize,
address: create_device as *const () as usize,
},
HleExport {
name: "D3D12SerializeRootSignature",
address: victory_gpu::root::serialize as *const () as usize,
},
HleExport {
name: "D3D12SerializeVersionedRootSignature",
address: victory_gpu::root::serialize_versioned as *const () as usize,
},
// The AMD upscaler's (Series S).
HleExport {
name: "D3D12CreateRootSignatureDeserializer",
address: victory_gpu::root::create_deserializer as *const () as usize,
},
// A data import: the title reads the id at this address.
HleExport {
name: "IID_ID3D12Device",
+195
View File
@@ -0,0 +1,195 @@
//! The display and what the system shell does for a title: HDR mode, screen
//! timeout deferrals, launching URIs, screenshots.
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, add_ref, missing, put, text,
};
/// HDR mode; asked for with this interface id since 2020.
pub const HDR_PROVIDER: Guid = Guid::new(
0x03f0_fe74,
0xfdd9,
0x4e5c,
[0xb6, 0x30, 0xf9, 0x33, 0x9c, 0x47, 0xac, 0xc5],
);
pub const HDR_IID: Guid = Guid::new(
0x35f0_7670,
0x706e,
0x4bfb,
[0x94, 0x76, 0x09, 0x07, 0x98, 0xc5, 0xeb, 0xf3],
);
/// Launching URIs and screen timeout deferrals; the interface id is the
/// provider's.
pub const SHELL: Guid = Guid::new(
0x1b33_9674,
0x328d,
0x4283,
[0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39],
);
/// Screenshots and clips.
pub const CAPTURE_PROVIDER: Guid = Guid::new(
0xa4f1_aee2,
0x4bf1,
0x4485,
[0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27],
);
/// As Grand Theft Auto VI (2026) asks for it; it calls 0x28 (take a
/// screenshot) with the public API's arguments.
pub const CAPTURE_IID_2026: Guid = Guid::new(
0x22e6_72d7,
0xb4e3,
0x406c,
[0xbd, 0x50, 0x8f, 0x0d, 0x25, 0x23, 0x6f, 0x9e],
);
pub static HDR_OBJECT: Object = Object::new("hdr", &HDR_VTABLE);
pub static SHELL_OBJECT: Object = Object::new("shell", &SHELL_VTABLE);
pub static CAPTURE_OBJECT: Object = Object::new("capture", &CAPTURE_VTABLE);
pub const INTERFACES: &[Interface] = &[
(HDR_PROVIDER, HDR_IID, &HDR_OBJECT),
(SHELL, SHELL, &SHELL_OBJECT),
(CAPTURE_PROVIDER, CAPTURE_IID_2026, &CAPTURE_OBJECT),
];
type This = *const Object;
/// 2: disabled. We present in SDR, so the title must render SDR.
// shortcut: HDR output is not done (see the presentation items in
// `TODO.md`); report enabled, with the host display's luminance, once the
// swap chain can present HDR.
extern "system" fn try_enable_hdr(_: This, preference: u32, _info: *mut c_void) -> u32 {
tracing::info!(preference, "HDR mode: disabled (SDR presentation)");
2
}
/// Nothing launches URIs for the title: no store, browser or console app
/// exists here, and the console's are online services.
extern "system" fn launch_uri(_: This, _user: *const c_void, uri: *const c_char) -> HRESULT {
tracing::info!(uri = text(uri).unwrap_or_default(), "URI not launched");
NOT_SUPPORTED
}
/// A deferral keeps the host display on, as on the console, through a
/// power request; the handle is that request.
#[cfg(windows)]
extern "system" fn acquire_deferral(_: This, out: *mut *mut c_void) -> HRESULT {
use windows_sys::Win32::System::Power::{
PowerCreateRequest, PowerRequestDisplayRequired, PowerSetRequest,
};
use windows_sys::Win32::System::Threading::{
POWER_REQUEST_CONTEXT_SIMPLE_STRING, REASON_CONTEXT,
};
if out.is_null() {
return super::xasync::E_INVALIDARG;
}
let mut reason: Vec<u16> = "Title display deferral\0".encode_utf16().collect();
let mut context = REASON_CONTEXT {
Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING,
..Default::default()
};
context.Reason.SimpleReasonString = reason.as_mut_ptr();
// SAFETY: a valid context; the string is copied by the call.
let request = unsafe { PowerCreateRequest(&context) };
if request as isize == -1 {
return last_error();
}
// SAFETY: the request we just created.
if unsafe { PowerSetRequest(request, PowerRequestDisplayRequired) } == 0 {
let hr = last_error();
// SAFETY: as above; not handed out.
unsafe { windows_sys::Win32::Foundation::CloseHandle(request) };
return hr;
}
put(out, request)
}
#[cfg(windows)]
extern "system" fn close_deferral(_: This, handle: *mut c_void) {
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Power::{PowerClearRequest, PowerRequestDisplayRequired};
if !handle.is_null() {
// SAFETY: a request from `acquire_deferral`.
unsafe {
PowerClearRequest(handle, PowerRequestDisplayRequired);
CloseHandle(handle);
}
}
}
#[cfg(windows)]
fn last_error() -> HRESULT {
// SAFETY: no preconditions.
let code = unsafe { windows_sys::Win32::Foundation::GetLastError() };
(0x8007_0000 | (code & 0xffff)) as i32
}
// shortcut: screenshots fail as if capture were unavailable. Taking one needs
// a hook in the GPU side: the last presented frame read back as BGRA8 (size,
// row pitch, bytes) on request, e.g. `victory_gpu::last_frame() ->
// Option<Frame>`, copied from the back buffer after `PresentX`.
extern "system" fn take_screenshot(_: This, _user: *const c_void, _result: *mut c_void) -> HRESULT {
tracing::info!("screenshot not taken");
NOT_SUPPORTED
}
static HDR_VTABLE: Methods<5> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
missing::<3> as *const (),
try_enable_hdr as *const (), // 0x20
]);
#[cfg(windows)]
static SHELL_VTABLE: Methods<6> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
launch_uri as *const (), // 0x18
acquire_deferral as *const (), // 0x20
close_deferral as *const (), // 0x28
]);
#[cfg(not(windows))]
static SHELL_VTABLE: Methods<4> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
launch_uri as *const (),
]);
static CAPTURE_VTABLE: Methods<6> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
missing::<3> as *const (), // 0x18 diagnostic screenshot
missing::<4> as *const (), // 0x20 diagnostic clip
take_screenshot as *const (), // 0x28
]);
#[cfg(all(test, windows))]
mod tests {
use super::*;
use crate::modules::xgameruntime::{S_OK, method};
#[test]
fn sdr_and_display_deferrals() {
type Hdr = extern "system" fn(This, u32, *mut c_void) -> u32;
assert_eq!(
method::<Hdr>(&HDR_OBJECT, 0x20)(&HDR_OBJECT, 0, std::ptr::null_mut()),
2
);
type Acquire = extern "system" fn(This, *mut *mut c_void) -> HRESULT;
type Close = extern "system" fn(This, *mut c_void);
let mut handle = std::ptr::null_mut();
assert_eq!(
method::<Acquire>(&SHELL_OBJECT, 0x20)(&SHELL_OBJECT, &mut handle),
S_OK
);
assert!(!handle.is_null());
method::<Close>(&SHELL_OBJECT, 0x28)(&SHELL_OBJECT, handle);
}
}
+314
View File
@@ -0,0 +1,314 @@
//! The console's audio DSP (`chad.dll`): streams that convolve blocks of
//! float samples with an impulse response (reverb), or run other block
//! transforms, on a coprocessor.
//!
//! A title connects once with a memory block for the DSP, activates
//! streams, and submits one command per block (gains, an input and an
//! output buffer). Activation hands back a status block whose second word is
//! the ticket of the last completed command and whose fourth is its result;
//! the title checks it one block later and treats a late command as an
//! overrun. Commands complete when submitted here.
//!
//! The transforms themselves are not computed: the hardware takes impulse
//! responses already in its own partitioned frequency-domain layout, which
//! is not known. Outputs are silence, so reverb returns are dry.
// shortcut: no convolution or block transform; outputs are zeros. Needs the
// coprocessor's impulse response and spectrum layouts to do better.
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::c_void;
use std::sync::Mutex;
use super::xasync::E_INVALIDARG;
use super::xgameruntime::{HRESULT, S_OK};
use crate::{HleModule, hle_export};
const E_POINTER: HRESULT = 0x8000_4003_u32 as i32;
const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
const CONVOLUTION: u32 = 1;
/// Option bits that need a stereo stream, and one convolution refuses.
const STEREO_OPTIONS: u32 = 2 | 8;
const NOT_FOR_CONVOLUTION: u32 = 4;
pub struct Dsp {
max_streams: u32,
active: Mutex<u32>,
}
/// What activation describes.
#[repr(C, packed)]
pub struct StreamDesc {
kind: u32,
options: u32,
frames: u32,
channels: u32,
ir_floats: u32,
ir: *const f32,
}
/// The status block a stream's owner polls.
#[repr(C)]
pub struct Status {
submitted: u32,
completed: u32,
reserved: u32,
result: HRESULT,
}
pub struct Stream {
dsp: *mut Dsp,
frames: u32,
channels: u32,
status: Box<Status>,
}
/// One block of work.
#[repr(C)]
pub struct Command {
gains: [f32; 2],
input: *const f32,
output: *mut f32,
reserved: u64,
}
pub extern "system" fn XDspConnectWithMaximumStreamLimit(
base: *mut c_void,
base_length: u32,
ir_seconds: u32,
max_streams: u32,
max_channels: u32,
out: *mut *mut Dsp,
) -> HRESULT {
if base.is_null()
|| !(0x1_0000..=0x1F40_0000).contains(&base_length)
|| ir_seconds > 0x80
|| max_streams > 0x100
|| max_channels > 2
{
return E_INVALIDARG;
}
if out.is_null() {
return E_POINTER;
}
tracing::info!(
base_length,
ir_seconds,
max_streams,
max_channels,
"audio DSP connected"
);
let dsp = Box::new(Dsp {
max_streams,
active: Mutex::new(0),
});
// SAFETY: checked non-null.
unsafe { out.write(Box::into_raw(dsp)) };
S_OK
}
pub extern "system" fn XDspDisconnect(dsp: *mut Dsp) -> HRESULT {
if dsp.is_null() {
return E_INVALIDARG;
}
// SAFETY: made by `XDspConnectWithMaximumStreamLimit`; disconnected
// once, after its streams.
drop(unsafe { Box::from_raw(dsp) });
S_OK
}
fn valid(desc: &StreamDesc) -> bool {
let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels);
let shape = if kind == CONVOLUTION {
(1..=2).contains(&channels)
&& matches!(frames, 0x200 | 0x400)
&& options & NOT_FOR_CONVOLUTION == 0
} else {
channels == 1 && matches!(frames, 0x200 | 0x400 | 0x800)
};
shape && (options & STEREO_OPTIONS == 0 || channels == 2)
}
pub extern "system" fn XDspActivate(
dsp: *mut Dsp,
desc: *const StreamDesc,
status: *mut *const Status,
stream: *mut *mut Stream,
) -> HRESULT {
if status.is_null() || stream.is_null() {
return E_POINTER;
}
if dsp.is_null() || desc.is_null() {
return E_INVALIDARG;
}
// SAFETY: checked non-null; the title passes its description.
let desc = unsafe { &*desc };
if !valid(desc) {
return E_INVALIDARG;
}
let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels);
tracing::debug!(
kind,
options,
frames,
channels,
"audio DSP stream activated"
);
{
// SAFETY: a connection from `XDspConnectWithMaximumStreamLimit`.
let dsp = unsafe { &*dsp };
let mut active = dsp.active.lock().unwrap_or_else(|e| e.into_inner());
if *active >= dsp.max_streams {
return E_OUTOFMEMORY;
}
*active += 1;
}
let new = Box::new(Stream {
dsp,
frames: desc.frames,
channels: desc.channels,
status: Box::new(Status {
submitted: 0,
completed: 0,
reserved: 0,
result: S_OK,
}),
});
// SAFETY: checked non-null.
unsafe {
status.write(&*new.status);
stream.write(Box::into_raw(new));
}
S_OK
}
pub extern "system" fn XDspDeactivate(stream: *mut Stream) -> HRESULT {
if stream.is_null() {
return E_INVALIDARG;
}
// SAFETY: made by `XDspActivate`; deactivated once.
let stream = unsafe { Box::from_raw(stream) };
// SAFETY: the connection outlives its streams.
let dsp = unsafe { &*stream.dsp };
*dsp.active.lock().unwrap_or_else(|e| e.into_inner()) -= 1;
S_OK
}
/// Completes the command at once: its output block is silence.
pub extern "system" fn XDspSubmitCommand(
stream: *mut Stream,
command: *const Command,
ticket: *mut u32,
) -> HRESULT {
if stream.is_null() || command.is_null() {
return E_INVALIDARG;
}
// SAFETY: a stream from `XDspActivate`, the title's command.
let (stream, command) = unsafe { (&mut *stream, &*command) };
if !command.output.is_null() {
let samples = (stream.frames * stream.channels) as usize;
// SAFETY: the title's output buffer holds one block of the stream.
unsafe { std::ptr::write_bytes(command.output, 0, samples) };
}
let status = &mut *stream.status;
let next = status.submitted.wrapping_add(1);
// SAFETY: the status block is read by title code on other threads.
unsafe {
std::ptr::write_volatile(&mut status.submitted, next);
std::ptr::write_volatile(&mut status.result, S_OK);
std::ptr::write_volatile(&mut status.completed, next);
}
if !ticket.is_null() {
// SAFETY: optional out parameter.
unsafe { ticket.write(next) };
}
S_OK
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "dsp",
dlls: &["chad.dll"],
exports: vec![
hle_export!(XDspConnectWithMaximumStreamLimit),
hle_export!(XDspDisconnect),
hle_export!(XDspActivate),
hle_export!(XDspDeactivate),
hle_export!(XDspSubmitCommand),
],
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn convolution_stream_as_the_title_drives_it() {
let mut base = vec![0u8; 0x10_0000];
let mut dsp = std::ptr::null_mut();
assert_eq!(
XDspConnectWithMaximumStreamLimit(
base.as_mut_ptr().cast(),
0x10_0000,
24,
0x80,
1,
&mut dsp
),
S_OK
);
let ir = vec![0f32; 0x800];
// Stereo convolution with option 2, as the title asks for.
let desc = StreamDesc {
kind: CONVOLUTION,
options: 2,
frames: 0x400,
channels: 2,
ir_floats: 0x800,
ir: ir.as_ptr(),
};
let (mut status, mut stream) = (std::ptr::null(), std::ptr::null_mut());
assert_eq!(XDspActivate(dsp, &desc, &mut status, &mut stream), S_OK);
let mut output = vec![1f32; 0x800];
let input = vec![0.5f32; 0x800];
let command = Command {
gains: [1.0, 1.0],
input: input.as_ptr(),
output: output.as_mut_ptr(),
reserved: 0,
};
let mut ticket = 0;
assert_eq!(XDspSubmitCommand(stream, &command, &mut ticket), S_OK);
// SAFETY: the stream's status block.
let (completed, result) = unsafe { ((*status).completed, (*status).result) };
assert_eq!((completed, result), (ticket, S_OK));
assert!(output.iter().all(|&s| s == 0.0));
assert_eq!(XDspDeactivate(stream), S_OK);
// Mono streams refuse stereo options; transforms are mono only.
let bad = StreamDesc {
channels: 1,
..desc
};
assert_eq!(
XDspActivate(dsp, &bad, &mut status, &mut stream),
E_INVALIDARG
);
let transform = StreamDesc {
kind: 2,
options: 0,
channels: 1,
ir_floats: 0,
ir: std::ptr::null(),
..desc
};
assert_eq!(
XDspActivate(dsp, &transform, &mut status, &mut stream),
S_OK
);
assert_eq!(XDspDeactivate(stream), S_OK);
assert_eq!(XDspDisconnect(dsp), S_OK);
}
}
File diff suppressed because it is too large. Load diff
+300 -18
View File
@@ -33,6 +33,7 @@ macro_rules! host {
unsafe { std::mem::transmute::<usize, $ty>(address) }
}};
}
pub(crate) use host;
/// Mounted drives: upper-case letter and host root (UTF-16, no trailing
/// separator, no NUL).
@@ -45,10 +46,7 @@ fn drives() -> MutexGuard<'static, Vec<(u16, Vec<u16>)>> {
/// 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 wide = root_wide(root);
let mut drives = drives();
if let Some(&(letter, _)) = drives.iter().find(|(_, r)| *r == wide) {
return char::from_u32(letter.into());
@@ -63,15 +61,81 @@ pub fn mount(root: &Path) -> Option<char> {
Some(letter.into())
}
/// Gives the host folder `root` a drive letter the console fixes (titles
/// open their package as `G:\..` and temporary files as `T:\..`). A host
/// drive of that letter is hidden from the title.
pub fn mount_at(letter: char, root: &Path) {
let letter = letter.to_ascii_uppercase();
let Some(index) = u32::from(letter)
.checked_sub(u32::from('A'))
.filter(|i| *i < 26)
else {
return;
};
// SAFETY: no arguments.
let hides_host_drive = unsafe { GetLogicalDrives() } >> index & 1 != 0;
tracing::info!(drive = %letter, root = %root.display(), hides_host_drive, "virtual drive");
let mut drives = drives();
drives.retain(|(l, _)| u32::from(*l) != u32::from(letter));
drives.push((letter as u16, root_wide(root)));
}
/// `root` as UTF-16, absolute, without trailing separators (a drive root
/// keeps its own).
fn root_wide(root: &Path) -> Vec<u16> {
let root = std::path::absolute(root).unwrap_or_else(|_| root.to_owned());
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();
}
wide
}
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];
/// Host paths from this length on take the `\\?\` form, which lifts the
/// host's MAX_PATH limit (248 characters for a directory, 260 for a file).
const LONG: usize = 248;
/// `root` and the title's `tail` as a `\\?\` path. That form turns off the
/// host's own clean-up, so `/` becomes `\` and `.` and `..` are resolved
/// here (`..` stops at the root).
fn verbatim(root: &[u16], tail: &[u16]) -> Vec<u16> {
let backslash = u16::from(b'\\');
let mut out = if root.starts_with(&VERBATIM) {
root.to_vec()
} else if let Some(unc) = root.strip_prefix(&[backslash; 2][..]) {
let mut out = VERBATIM.to_vec();
out.extend("UNC\\".encode_utf16());
out.extend_from_slice(unc);
out
} else {
[&VERBATIM[..], root].concat()
};
while out.last() == Some(&backslash) {
out.pop();
}
let dot = u16::from(b'.');
let mut parts: Vec<&[u16]> = Vec::new();
for part in tail.split(|c| SEPARATORS.contains(c)) {
match part {
[] => {}
[d] if *d == dot => {}
[d, e] if [*d, *e] == [dot; 2] => drop(parts.pop()),
_ => parts.push(part),
}
}
for part in parts {
out.push(backslash);
out.extend_from_slice(part);
}
out
}
/// 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>> {
pub(crate) fn translate(path: &[u16]) -> Option<Vec<u16>> {
let (prefix, rest) = match path.strip_prefix(&VERBATIM[..]) {
Some(rest) => (&VERBATIM[..], rest),
None => (&[][..], path),
@@ -87,6 +151,11 @@ fn translate(path: &[u16]) -> Option<Vec<u16>> {
let drives = drives();
let (_, root) = drives.iter().find(|(l, _)| *l == letter)?;
let tail = &rest[2..];
if prefix.is_empty() && root.len() + tail.len() >= LONG {
let mut out = verbatim(root, tail);
out.push(0);
return Some(out);
}
let mut out = prefix.to_vec();
out.extend_from_slice(root);
// `X:` and `X:name` are relative to the root.
@@ -124,7 +193,18 @@ fn wide(path: *const u16) -> Wide {
let len = (0..).take_while(|&i| *path.add(i) != 0).count();
std::slice::from_raw_parts(path, len)
};
Wide(path, translate(path_slice))
let host = translate(path_slice);
trace(path_slice, host.as_deref());
Wide(path, host)
}
/// Every title path at debug level, with the host path if rewritten.
fn trace(path: &[u16], host: Option<&[u16]>) {
tracing::debug!(
path = %String::from_utf16_lossy(path),
host = host.map(|h| String::from_utf16_lossy(&h[..h.len() - 1])),
"title path"
);
}
/// A narrow path (ANSI code page, as the host decodes it) on a virtual
@@ -138,7 +218,10 @@ fn narrow(path: *const c_char) -> Option<Vec<u16>> {
// 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,
_ => {
tracing::debug!(path = %String::from_utf8_lossy(bytes), "title path");
return None;
}
}
let len = i32::try_from(bytes.len()).ok()?;
// SAFETY: sizing call, then a call with room for `n` units.
@@ -148,7 +231,9 @@ fn narrow(path: *const c_char) -> Option<Vec<u16>> {
MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, wide.as_mut_ptr(), n);
wide
};
translate(&wide)
let host = translate(&wide);
trace(&wide, host.as_deref());
host
}
/// An ASCII mode string (`"rb"`, `"w, ccs=UTF-8"`) for a wide CRT call.
@@ -220,6 +305,24 @@ pub extern "system" fn CreateFileA(
}
}
/// Used by Bink.
pub extern "system" fn CreateFile2(
path: *const u16,
access: u32,
share: u32,
disposition: u32,
params: *const c_void,
) -> Handle {
let p = wide(path);
host!("kernel32.dll", "CreateFile2": extern "system" fn(*const u16, u32, u32, u32, *const c_void) -> Handle)(
p.ptr(),
access,
share,
disposition,
params,
)
}
pub extern "system" fn DeleteFileA(path: *const c_char) -> i32 {
match narrow(path) {
Some(p) => {
@@ -231,6 +334,35 @@ pub extern "system" fn DeleteFileA(path: *const c_char) -> i32 {
}
}
pub extern "system" fn DeleteFileW(path: *const u16) -> i32 {
let p = wide(path);
host!("kernel32.dll", "DeleteFileW": extern "system" fn(*const u16) -> i32)(p.ptr())
}
pub extern "system" fn RemoveDirectoryW(path: *const u16) -> i32 {
let p = wide(path);
host!("kernel32.dll", "RemoveDirectoryW": extern "system" fn(*const u16) -> i32)(p.ptr())
}
pub extern "system" fn SetFileAttributesW(path: *const u16, attributes: u32) -> i32 {
let p = wide(path);
host!("kernel32.dll", "SetFileAttributesW": extern "system" fn(*const u16, u32) -> i32)(
p.ptr(),
attributes,
)
}
pub extern "system" fn GetFileAttributesA(path: *const c_char) -> u32 {
match narrow(path) {
Some(p) => GetFileAttributesW(p.as_ptr()),
None => {
host!("kernel32.dll", "GetFileAttributesA": extern "system" fn(*const c_char) -> u32)(
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)(
@@ -252,6 +384,11 @@ pub extern "system" fn GetFileAttributesExW(
)
}
pub extern "system" fn GetFileAttributesW(path: *const u16) -> u32 {
let p = wide(path);
host!("kernel32.dll", "GetFileAttributesW": extern "system" fn(*const u16) -> u32)(p.ptr())
}
pub extern "system" fn GetDiskFreeSpaceExW(
path: *const u16,
available: *mut u64,
@@ -369,6 +506,34 @@ pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> Fi
)
}
// Kernel reads into title memory. The GPU side leaves blocks of title GPU
// buffers read-only to see the title's next write, and the kernel's writes
// fail there instead of faulting into its handler; Grand Theft Auto VI's
// synchronous reads (title+0x313fc0) read straight into 4 KiB-aligned
// destinations and retry a failed `ReadFile` forever. So the destination
// is opened first.
pub extern "system" fn ReadFile(
file: *mut c_void,
buffer: *mut u8,
len: u32,
read: *mut u32,
overlapped: *mut c_void,
) -> i32 {
victory_gpu::kernel_will_write(buffer as usize, len as usize);
host!("kernel32.dll", "ReadFile": extern "system" fn(*mut c_void, *mut u8, u32, *mut u32, *mut c_void) -> i32)(
file, buffer, len, read, overlapped,
)
}
/// The host CRT reads large requests straight into the caller's buffer.
pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File) -> usize {
victory_gpu::kernel_will_write(buffer as usize, size.saturating_mul(count));
host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize)(
buffer, size, count, stream,
)
}
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()),
@@ -391,6 +556,31 @@ pub extern "C" fn fopen_s(out: *mut File, path: *const c_char, mode: *const c_ch
}
}
/// `_open(path, flags[, mode])` is variadic; on x64 the optional integer
/// travels in the same register either way, so it is passed on as is.
pub extern "C" fn _open(path: *const c_char, flags: i32, mode: i32) -> i32 {
match narrow(path) {
Some(p) => host!("ucrtbase.dll", "_wopen": extern "C" fn(*const u16, i32, i32) -> i32)(
p.as_ptr(),
flags,
mode,
),
None => host!("ucrtbase.dll", "_open": extern "C" fn(*const c_char, i32, i32) -> i32)(
path, flags, mode,
),
}
}
/// See [`_open`]; used by libHttpClient.
pub extern "C" fn _wopen(path: *const u16, flags: i32, mode: i32) -> i32 {
let p = wide(path);
host!("ucrtbase.dll", "_wopen": extern "C" fn(*const u16, i32, i32) -> i32)(
p.ptr(),
flags,
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)
@@ -435,17 +625,22 @@ pub extern "C" fn _wutime64(path: *const u16, times: *mut c_void) -> i32 {
// The C++ library: `std::basic_filebuf::open` goes through `_Fiopen`.
const FIOPEN: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z";
const FIOPEN_WIDE: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z";
/// `_Fiopen(const wchar_t* path, ios_base::openmode, int protection)`.
extern "C" fn fiopen_wide(path: *const u16, mode: i32, protection: i32) -> File {
let p = wide(path);
host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)(
p.ptr(),
mode,
protection,
)
}
/// `_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,
)
}
Some(p) => fiopen_wide(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,
@@ -469,10 +664,18 @@ pub(crate) fn module() -> HleModule {
"msvcp140.dll",
],
exports: vec![
hle_export!(ReadFile),
hle_export!(fread),
hle_export!(CreateFileW),
hle_export!(CreateFileA),
hle_export!(CreateFile2),
hle_export!(DeleteFileA),
hle_export!(DeleteFileW),
hle_export!(RemoveDirectoryW),
hle_export!(SetFileAttributesW),
hle_export!(GetFileAttributesA),
hle_export!(CreateDirectoryW),
hle_export!(GetFileAttributesW),
hle_export!(GetFileAttributesExW),
hle_export!(GetDiskFreeSpaceExW),
hle_export!(GetDiskFreeSpaceW),
@@ -485,6 +688,8 @@ pub(crate) fn module() -> HleModule {
hle_export!(_wfsopen),
hle_export!(fopen),
hle_export!(fopen_s),
hle_export!(_open),
hle_export!(_wopen),
hle_export!(_wstat64),
hle_export!(_stat64i32),
hle_export!(remove),
@@ -494,6 +699,10 @@ pub(crate) fn module() -> HleModule {
name: FIOPEN,
address: fiopen as *const () as usize,
},
HleExport {
name: FIOPEN_WIDE,
address: fiopen_wide as *const () as usize,
},
],
}
}
@@ -506,6 +715,19 @@ mod tests {
s.encode_utf16().chain([0]).collect()
}
#[test]
fn kernel_reads_reach_the_buffer() {
use std::os::windows::io::AsRawHandle;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("data.bin");
std::fs::write(&path, b"0123456789").unwrap();
let file = std::fs::File::open(&path).unwrap();
let (mut out, mut n) = ([0u8; 10], 0);
let handle = file.as_raw_handle().cast();
assert_ne!(ReadFile(handle, out.as_mut_ptr(), 10, &mut n, std::ptr::null_mut()), 0);
assert_eq!((&out, n), (b"0123456789", 10));
}
fn text(v: &[u16]) -> String {
String::from_utf16_lossy(&v[..v.len() - 1])
}
@@ -535,6 +757,45 @@ mod tests {
assert_eq!(tr(r"C:\Windows".into()), None);
assert_eq!(tr("relative/path".into()), None);
assert_eq!(tr(String::new()), None);
// Fixed letters, as the console's package drive; a later mount of
// the same letter replaces the earlier one.
let package = tempfile::tempdir().unwrap();
mount_at('g', dir.path());
mount_at('G', package.path());
assert_eq!(
tr(r"G:\appdata0.rpf".into()),
Some(format!(r"{}\appdata0.rpf", package.path().display()))
);
assert_ne!(mount(dir.path()), Some('G'), "free letters skip fixed ones");
// Long ones take the `\\?\` form, cleaned up as the host would.
let long = "d".repeat(250);
assert_eq!(
tr(format!(r"G:/a/./b/../{long}//f")),
Some(format!(r"\\?\{}\a\{long}\f", package.path().display()))
);
assert_eq!(
verbatim(&w(r"\\server\share\")[..15], &w("/x/../../y")[..10]),
w(r"\\?\UNC\server\share\y")[..22].to_vec()
);
}
#[test]
fn long_title_paths_work_on_the_host() {
let dir = tempfile::tempdir().unwrap();
let letter = mount(dir.path()).unwrap();
let deep = format!("{letter}:/{}/{}", "a".repeat(200), "b".repeat(100));
let null = std::ptr::null_mut();
let first = w(&deep[..203]);
assert_ne!(CreateDirectoryW(first.as_ptr(), null), 0);
assert_ne!(CreateDirectoryW(w(&deep).as_ptr(), null), 0);
let file = format!("{deep}/../{}/f.txt", "b".repeat(100));
let f = _wfopen(w(&file).as_ptr(), w("wb").as_ptr());
assert!(!f.is_null(), "{file}");
host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32)(f);
assert_ne!(DeleteFileW(w(&format!("{deep}/f.txt")).as_ptr()), 0);
assert_ne!(RemoveDirectoryW(w(&deep).as_ptr()), 0);
}
#[test]
@@ -576,6 +837,27 @@ mod tests {
assert_eq!(remove(path.as_ptr().cast()), 0);
assert!(!dir.path().join("stream.txt").exists());
let f = fiopen_wide(w(&format!("{letter}:/wide.txt")).as_ptr(), OUT, 0x40);
assert!(!f.is_null());
fclose(f);
assert!(dir.path().join("wide.txt").is_file());
const OPEN_EXISTING: u32 = 3;
let path = w(&format!(r"{letter}:\created.bin"));
let h = CreateFile2(path.as_ptr(), GENERIC_WRITE, 0, OPEN_EXISTING, null);
assert_ne!(h as isize, -1);
close(h);
const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX;
assert_ne!(GetFileAttributesW(path.as_ptr()), INVALID_FILE_ATTRIBUTES);
const O_WRONLY: i32 = 1;
const O_CREAT: i32 = 0x100;
const S_IWRITE: i32 = 0x80;
let path = format!("{letter}:/low.bin\0");
let fd = _open(path.as_ptr().cast(), O_WRONLY | O_CREAT, S_IWRITE);
assert!(fd >= 0);
host!("ucrtbase.dll", "_close": extern "C" fn(i32) -> i32)(fd);
assert!(dir.path().join("low.bin").is_file());
// Other paths pass through untouched.
let host_path = format!("{}\0", dir.path().join("plain.txt").display());
File diff suppressed because it is too large. Load diff
+159 -16
View File
@@ -146,8 +146,14 @@ pub extern "system" fn LoadLibraryW(name: *const u16) -> *mut c_void {
/// 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 {
// `NULL` is the process's exe, which for the title is its own image.
let module = if module.is_null() {
runtime::main_image().unwrap_or(0) as *mut c_void
} else {
module
};
let Some(m) = registry().iter().find(|m| handle(m) == module) else {
return host::get_proc_address(module, name);
return host_override(module, name).unwrap_or_else(|| host::get_proc_address(module, name));
};
// Values below 0x10000 are ordinals; we export by name only.
if (name as usize) < 0x1_0000 {
@@ -169,6 +175,25 @@ pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> *
}
}
/// What a host module's `name` (or ordinal) is bound to at import binding
/// when we override it: a title that looks a function up by name must not
/// get past our overrides (the network guard, path rewriting).
fn host_override(module: *mut c_void, name: *const u8) -> Option<*mut c_void> {
if module.is_null() || runtime::image_path(module as usize).is_some() {
return None;
}
let symbol = if (name as usize) < 0x1_0000 {
format!("#{}", name as usize)
} else {
narrow(name)
};
let mut path = [0u16; 260];
let len = host::get_module_file_name_w(module, path.as_mut_ptr(), path.len() as u32) as usize;
let path = String::from_utf16_lossy(&path[..len.min(path.len())]);
let file = path.rsplit('\\').next()?;
crate::registry::lookup(file, &symbol).map(|address| address as *mut c_void)
}
/// Our pseudo modules and the title's images stay loaded: `LoadLibrary`
/// took no reference on them, so the host's count must not drop.
pub extern "system" fn FreeLibrary(module: *mut c_void) -> i32 {
@@ -189,14 +214,18 @@ pub extern "system" fn DisableThreadLibraryCalls(module: *mut c_void) -> i32 {
/// 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() {
tracing::info!(target: "title", "{}", narrow(text).trim_end());
let text = narrow(text);
host::note_title_output(text.trim());
tracing::info!(target: "title", "{}", text.trim_end());
}
}
/// See [`OutputDebugStringA`].
pub extern "system" fn OutputDebugStringW(text: *const u16) {
if !text.is_null() {
tracing::info!(target: "title", "{}", wide(text).trim_end());
let text = wide(text);
host::note_title_output(text.trim());
tracing::info!(target: "title", "{}", text.trim_end());
}
}
@@ -226,6 +255,28 @@ pub extern "C" fn _invalid_parameter_noinfo_noreturn() -> ! {
host::abort()
}
/// The title's unhandled-exception filter. Ours stands in front of it and
/// reports the crash first; the title still gets its own back.
static TITLE_FILTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
pub extern "system" fn SetUnhandledExceptionFilter(filter: usize) -> usize {
host::set_unhandled_exception_filter(report_unhandled);
TITLE_FILTER.swap(filter, std::sync::atomic::Ordering::AcqRel)
}
extern "system" fn report_unhandled(info: *const c_void) -> i32 {
host::report_unhandled(info);
match TITLE_FILTER.load(std::sync::atomic::Ordering::Acquire) {
0 => 0, // EXCEPTION_CONTINUE_SEARCH
filter => {
type Filter = extern "system" fn(*const c_void) -> i32;
// SAFETY: the title registered this filter.
let filter: Filter = unsafe { std::mem::transmute(filter) };
filter(info)
}
}
}
/// 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 {
@@ -240,7 +291,9 @@ fn handle(m: &HleModule) -> *mut c_void {
}
/// The title's images and our console modules by name; `None` leaves the
/// name to the host. With `load`, a title DLL not mapped yet is mapped now.
/// name to the host, which only DLLs `HostPolicy` passes through get (as at
/// import binding); others fail. With `load`, a title DLL not mapped yet is
/// mapped now.
fn find_module(path: &str, load: bool) -> Option<*mut c_void> {
let file = path.rsplit(['\\', '/']).next().unwrap_or(path);
// As the Windows loader does, a name without extension means a DLL.
@@ -249,29 +302,49 @@ fn find_module(path: &str, load: bool) -> Option<*mut c_void> {
} else {
format!("{file}.dll")
};
// Loads go through the title DLL loader first: it waits for a DLL that
// another thread is still initialising, as the Windows loader lock does.
if load {
match runtime::load_title_dll(&file) {
Ok(Some(base)) => return Some(base as *mut c_void),
Ok(None) => {}
// Not the host: it would load the unpatched DLL from the title's folder.
Err(error) => {
tracing::error!(dll = file, %error, "mapping a title DLL failed");
host::set_last_error(ERROR_MOD_NOT_FOUND);
return Some(std::ptr::null_mut());
}
}
}
if let Some(base) = runtime::image_named(&file) {
return Some(base as *mut c_void);
}
// DLLs the host has too are real host modules, whatever `--strict` says.
if !HostPolicy::default().allows(&file)
&& let Some(m) = registry().iter().find(|m| m.serves(&file))
{
let host_dll = HostPolicy::default().allows(&file);
if !host_dll && let Some(m) = registry().iter().find(|m| m.serves(&file)) {
if load {
tracing::info!(dll = file, "loaded as a pseudo module");
}
return Some(handle(m));
}
if !load {
if host_dll {
return None;
}
match runtime::load_title_dll(&file) {
Ok(base) => base.map(|b| b as *mut c_void),
// Not the host: it would load the unpatched DLL from the title's folder.
Err(error) => {
tracing::error!(dll = file, %error, "mapping a title DLL failed");
host::set_last_error(ERROR_MOD_NOT_FOUND);
Some(std::ptr::null_mut())
}
// Any other host DLL (wininet, urlmon, ...) is beyond what we guard, and
// the console does not have it.
refuse(&file);
host::set_last_error(ERROR_MOD_NOT_FOUND);
Some(std::ptr::null_mut())
}
/// Logs a DLL name the title is refused, once.
fn refuse(file: &str) {
static REFUSED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
let file = file.to_ascii_lowercase();
let mut refused = REFUSED.lock().unwrap_or_else(|e| e.into_inner());
if !refused.contains(&file) {
tracing::warn!(dll = file, "a host DLL outside the host policy: refused");
refused.push(file);
}
}
@@ -286,6 +359,7 @@ pub(crate) fn module() -> HleModule {
"api-ms-win-core-libraryloader-*",
"api-ms-win-core-processthreads-*",
"api-ms-win-core-debug-*",
"api-ms-win-core-errorhandling-*",
"api-ms-win-crt-runtime-*",
],
exports: vec![
@@ -307,10 +381,17 @@ pub(crate) fn module() -> HleModule {
hle_export!(terminate),
hle_export!(_invalid_parameter_noinfo_noreturn),
hle_export!(TerminateProcess),
hle_export!(SetUnhandledExceptionFilter),
],
}
}
/// The return addresses above the caller, as `module+rva`, for logs.
#[cfg(feature = "diagnostics")]
pub(crate) fn callers() -> String {
host::callers()
}
#[cfg(windows)]
mod host {
use std::ffi::c_void;
@@ -405,6 +486,27 @@ mod host {
unsafe { TerminateProcess(process, code) }
}
pub(super) fn set_unhandled_exception_filter(filter: extern "system" fn(*const c_void) -> i32) {
// SAFETY: our filter takes the exception pointers as an opaque pointer.
unsafe {
windows_sys::Win32::System::Diagnostics::Debug::SetUnhandledExceptionFilter(
std::mem::transmute::<
extern "system" fn(*const c_void) -> i32,
windows_sys::Win32::System::Diagnostics::Debug::LPTOP_LEVEL_EXCEPTION_FILTER,
>(filter),
)
};
}
pub(super) fn report_unhandled(info: *const c_void) {
// SAFETY: the system's exception pointers, passed to the filter.
unsafe { victory_loader::report_unhandled(info.cast()) };
}
pub(super) fn note_title_output(line: &str) {
victory_loader::note_title_output(line);
}
/// Our caller's callers, as `module+rva`.
pub(super) fn callers() -> String {
let mut frames = [std::ptr::null_mut(); 12];
@@ -479,6 +581,12 @@ mod host {
std::process::exit(code as i32)
}
pub(super) fn set_unhandled_exception_filter(_: extern "system" fn(*const c_void) -> i32) {}
pub(super) fn report_unhandled(_: *const c_void) {}
pub(super) fn note_title_output(_: &str) {}
pub(super) fn callers() -> String {
String::new()
}
@@ -511,6 +619,41 @@ mod tests {
text.encode_utf16().chain(Some(0)).collect()
}
#[cfg(windows)]
#[test]
fn host_lookups_by_name_get_our_overrides() {
let kernel32 = GetModuleHandleW(w("kernel32.dll").as_ptr());
assert!(!kernel32.is_null());
let ours = crate::registry::lookup("kernel32.dll", "CreateFileW").unwrap();
assert_eq!(
GetProcAddress(kernel32, c"CreateFileW".as_ptr().cast()) as usize,
ours
);
// A plain name stays the host's.
let host = host::get_proc_address(kernel32, c"GetTickCount".as_ptr().cast());
assert!(!host.is_null());
assert_eq!(
GetProcAddress(kernel32, c"GetTickCount".as_ptr().cast()),
host
);
// Host DLLs outside the host policy do not exist for the title.
assert!(LoadLibraryW(w("wininet.dll").as_ptr()).is_null());
assert!(LoadLibraryA(c"C:\\Windows\\System32\\urlmon".as_ptr().cast()).is_null());
assert!(GetModuleHandleW(w("WININET.DLL").as_ptr()).is_null());
assert_eq!(
// SAFETY: reads this thread's last error.
unsafe { windows_sys::Win32::Foundation::GetLastError() },
ERROR_MOD_NOT_FOUND
);
assert!(!LoadLibraryW(w("kernel32").as_ptr()).is_null());
// By ordinal too (ws2_32 #4 is `connect`).
let ws2 = LoadLibraryW(w("ws2_32.dll").as_ptr());
assert_eq!(
GetProcAddress(ws2, 4 as *const u8) as usize,
crate::registry::lookup("ws2_32.dll", "connect").unwrap()
);
}
#[test]
fn title_dlls_and_pseudo_modules_are_found_by_name() {
let base = 0x7100_0000_0000usize;
+143 -19
View File
@@ -1,7 +1,8 @@
//! 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.
//! quitting it or launching a new game 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; a new launch then starts
//! `victory` again, which waits for this process to be gone.
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
#![allow(clippy::too_many_arguments)]
@@ -11,7 +12,7 @@ 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::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, RECT, 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};
@@ -72,7 +73,8 @@ pub extern "system" fn CreateWindowExW(
instance: HINSTANCE,
param: *const c_void,
) -> HWND {
// SAFETY: the title's own arguments, forwarded.
let (x, y, width, height) = fit(parent, x, y, width, height);
// SAFETY: the title's own arguments, forwarded (the size fitted).
let hwnd = unsafe {
wm::CreateWindowExW(
ex_style, class, name, style, x, y, width, height, parent, menu, instance, param,
@@ -97,7 +99,8 @@ pub extern "system" fn CreateWindowExA(
instance: HINSTANCE,
param: *const c_void,
) -> HWND {
// SAFETY: the title's own arguments, forwarded.
let (x, y, width, height) = fit(parent, x, y, width, height);
// SAFETY: the title's own arguments, forwarded (the size fitted).
let hwnd = unsafe {
wm::CreateWindowExA(
ex_style, class, name, style, x, y, width, height, parent, menu, instance, param,
@@ -107,6 +110,44 @@ pub extern "system" fn CreateWindowExA(
hwnd
}
/// A console title sizes its window to its render target (Grand Theft
/// Auto VI: 3840x2160 on a Series X), which can exceed the host's screen.
/// A top-level window larger than the work area is shrunk to fit, keeping
/// its proportions, and centred; what it shows is scaled to it (the swap
/// chain stretches).
fn fit(parent: HWND, x: i32, y: i32, width: i32, height: i32) -> (i32, i32, i32, i32) {
let mut area = RECT::default();
// SAFETY: `area` receives the primary monitor's work area.
let known =
unsafe { wm::SystemParametersInfoW(wm::SPI_GETWORKAREA, 0, (&raw mut area).cast(), 0) };
let fitted = fit_into(&area, width, height);
if !parent.is_null() || known == 0 || fitted == (width, height) {
return (x, y, width, height);
}
tracing::info!(width, height, to = ?fitted, "title window fitted to the screen");
let (w, h) = fitted;
let left = area.left + (area.right - area.left - w) / 2;
let top = area.top + (area.bottom - area.top - h) / 2;
(left, top, w, h)
}
/// `width` x `height` scaled down to fit `area`, or unchanged if it fits
/// (or is `CW_USEDEFAULT`).
fn fit_into(area: &RECT, width: i32, height: i32) -> (i32, i32) {
let (aw, ah) = (area.right - area.left, area.bottom - area.top);
if width <= 0 || height <= 0 || aw <= 0 || ah <= 0 || (width <= aw && height <= ah) {
return (width, height);
}
let scale = f64::min(
f64::from(aw) / f64::from(width),
f64::from(ah) / f64::from(height),
);
(
(f64::from(width) * scale) as i32,
(f64::from(height) * scale) as i32,
)
}
/// Puts our procedure in front of the title's.
fn hook(hwnd: HWND) {
if hwnd.is_null() {
@@ -130,7 +171,7 @@ extern "system" fn window_proc(
// 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();
end_title("window closed", Box::new(|| {}));
return 0;
}
// SAFETY: the procedure `hook` stored, called the way the system would.
@@ -144,30 +185,97 @@ extern "system" fn window_proc(
}
}
/// 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) {
/// Suspends the title as the console does when it ends it, runs `then`
/// (once), then ends the process. Returns at once; later calls do nothing.
pub(crate) fn end_title(why: &'static str, then: Box<dyn FnOnce() + Send>) {
static ENDING: AtomicBool = AtomicBool::new(false);
if ENDING.swap(true, Ordering::SeqCst) {
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.
tracing::info!(routines = suspend.len(), "{why}: suspending the title");
// Whoever comes first (the routines or the deadline) runs `then`; the
// other waits for it, so the process never ends halfway through.
let then = std::sync::Arc::new(Mutex::new(Some(then)));
let finish = move |how: &str| {
let mut then = then.lock().unwrap_or_else(|e| e.into_inner());
tracing::info!("{how}; ending the title");
if let Some(then) = then.take() {
then();
}
end();
};
let late = finish.clone();
// Not on the calling thread: titles hand the suspend to their window
// 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();
finish("title suspended");
});
std::thread::spawn(|| {
std::thread::spawn(move || {
std::thread::sleep(SUSPEND_DEADLINE);
tracing::warn!("title did not finish suspending in time; ending it");
end();
late("title did not finish suspending in time");
});
}
/// Set in the environment of a relaunched `victory`: an inherited handle
/// of the process it replaces.
const RELAUNCHED_FROM: &str = "VICTORY_RELAUNCHED_FROM";
/// Starts `victory` again with `args` (after the title has suspended); the
/// new process waits until this one has ended.
pub(crate) fn relaunch(args: Vec<std::ffi::OsString>) {
use windows_sys::Win32::Foundation::{DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE};
let mut me: HANDLE = std::ptr::null_mut();
// SAFETY: an inheritable duplicate of our own process handle.
let duplicated = unsafe {
DuplicateHandle(
GetCurrentProcess(),
GetCurrentProcess(),
GetCurrentProcess(),
&mut me,
0,
1,
DUPLICATE_SAME_ACCESS,
)
} != 0;
let spawned = std::env::current_exe().and_then(|exe| {
let mut command = std::process::Command::new(exe);
command.args(&args);
if duplicated {
command.env(RELAUNCHED_FROM, (me as usize).to_string());
}
command.spawn()
});
match spawned {
Ok(child) => tracing::info!(pid = child.id(), ?args, "relaunched"),
Err(e) => tracing::warn!(%e, "relaunch failed; the title just ends"),
}
}
/// In a relaunched `victory`: waits (30 s at most) for the process it
/// replaces to be gone, so the two never share the title's files.
pub fn wait_for_previous() {
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
use windows_sys::Win32::System::Threading::WaitForSingleObject;
let Some(handle) = std::env::var(RELAUNCHED_FROM)
.ok()
.and_then(|h| h.parse::<usize>().ok())
else {
return;
};
// SAFETY: removing our own variable before any other thread reads it.
unsafe { std::env::remove_var(RELAUNCHED_FROM) };
let handle = handle as HANDLE;
// SAFETY: the inherited process handle the previous process gave us.
unsafe {
WaitForSingleObject(handle, 30_000);
CloseHandle(handle);
}
}
fn end() {
// SAFETY: ends this process, as the console ends a suspended title.
unsafe { TerminateProcess(GetCurrentProcess(), 0) };
@@ -211,6 +319,22 @@ mod tests {
assert_eq!(left, [b]);
}
#[test]
fn oversized_windows_shrink_to_the_screen() {
let area = RECT {
left: 0,
top: 0,
right: 1920,
bottom: 1040,
};
assert_eq!(fit_into(&area, 3840, 2160), (1848, 1040));
assert_eq!(fit_into(&area, 1280, 720), (1280, 720));
assert_eq!(
fit_into(&area, wm::CW_USEDEFAULT, 0),
(wm::CW_USEDEFAULT, 0)
);
}
#[test]
fn hooked_windows_still_reach_the_title_procedure() {
let null = std::ptr::null_mut();
+531
View File
@@ -0,0 +1,531 @@
//! Media Foundation is the host's (`mfplat.dll` passes through), except for
//! the source resolver: the host's would fetch `http`, `rtsp` and other
//! URLs over the network, past `modules::net`. Titles get a proxy that
//! opens local files only, with paths on our virtual drives rewritten to
//! their host folders, and forwards everything else to the host's resolver.
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::collections::HashSet;
use std::ffi::c_void;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Mutex, OnceLock};
use super::files;
use super::xgameruntime::{HRESULT, S_OK};
use crate::{HleModule, hle_export};
const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32;
const E_POINTER: HRESULT = 0x8000_4003_u32 as i32;
/// What Media Foundation answers for a URL scheme it has no handler for.
const UNSUPPORTED_SCHEME: HRESULT = 0xC00D_36C3_u32 as i32;
const IID_IUNKNOWN: [u8; 16] = guid(0x0000_0000, 0x0000, 0x0000, [0xC0, 0, 0, 0, 0, 0, 0, 0x46]);
const IID_RESOLVER: [u8; 16] = guid(
0xFBE5_A32D,
0xA497,
0x4B61,
[0xBB, 0x85, 0x97, 0xB1, 0xA8, 0x48, 0xA6, 0xE3],
);
const fn guid(a: u32, b: u16, c: u16, d: [u8; 8]) -> [u8; 16] {
let (a, b, c) = (a.to_le_bytes(), b.to_le_bytes(), c.to_le_bytes());
[
a[0], a[1], a[2], a[3], b[0], b[1], c[0], c[1], d[0], d[1], d[2], d[3], d[4], d[5], d[6],
d[7],
]
}
// The URL rule.
/// Where a resolver may read `url` from: `Ok` with the NUL-terminated
/// string to hand to the host, or `Err((scheme, host))` for anything that
/// is not a local file.
fn local(url: &[u16]) -> Result<Vec<u16>, (String, String)> {
let text = String::from_utf16_lossy(url);
let drive = |s: &str| {
let b = s.as_bytes();
b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':'
};
let host_of = |rest: &str| rest.split(['/', '\\']).next().unwrap_or("").to_string();
let path = if let Some(rest) = text.strip_prefix(r"\\?\") {
if !drive(rest) {
return Err(("unc".into(), host_of(rest.trim_start_matches("UNC\\"))));
}
text.clone()
} else if let Some(rest) = text.strip_prefix(r"\\").or_else(|| text.strip_prefix("//")) {
return Err(("unc".into(), host_of(rest)));
} else if drive(&text) {
text.clone()
} else if let Some((scheme, rest)) = text.split_once(':').filter(|(s, _)| {
s.len() > 1
&& s.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"+-.".contains(&c))
}) {
let scheme = scheme.to_ascii_lowercase();
let authority = rest.strip_prefix("//");
if scheme != "file" {
return Err((scheme, authority.map(host_of).unwrap_or_default()));
}
let path = match authority {
Some(rest) => {
let host = host_of(rest);
if !host.is_empty() && !host.eq_ignore_ascii_case("localhost") {
return Err((scheme, host));
}
&rest[host.len()..]
}
None => rest,
};
let path = percent_decode(path.trim_start_matches(['/', '\\'])).replace('/', "\\");
if !drive(&path) {
// A local file without a drive: the host resolves it as is.
return Ok(with_nul(url));
}
path
} else {
// A relative path.
return Ok(with_nul(url));
};
let wide: Vec<u16> = path.encode_utf16().collect();
Ok(files::translate(&wide).unwrap_or_else(|| with_nul(&wide)))
}
fn with_nul(s: &[u16]) -> Vec<u16> {
s.iter().copied().chain([0]).collect()
}
fn percent_decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
let hex = b
.get(i + 1..i + 3)
.and_then(|h| std::str::from_utf8(h).ok());
match (b[i], hex.and_then(|h| u8::from_str_radix(h, 16).ok())) {
(b'%', Some(v)) => {
out.push(v);
i += 3;
}
(c, _) => {
out.push(c);
i += 1;
}
}
}
String::from_utf8_lossy(&out).into_owned()
}
/// The URL to give the host, or the refusal (logged once per scheme and
/// host).
fn checked(url: *const u16) -> Result<Vec<u16>, HRESULT> {
if url.is_null() {
return Err(E_POINTER);
}
// SAFETY: a NUL-terminated wide string from the title.
let len = (0..)
.take_while(|&i| unsafe { url.add(i).read() } != 0)
.count();
// SAFETY: as above, `len` characters before the NUL.
let wide = unsafe { std::slice::from_raw_parts(url, len) };
local(wide).map_err(|(scheme, host)| {
static REFUSED: Mutex<Option<HashSet<(String, String)>>> = Mutex::new(None);
let mut refused = REFUSED.lock().unwrap_or_else(|e| e.into_inner());
if refused
.get_or_insert_with(HashSet::new)
.insert((scheme.clone(), host.clone()))
{
tracing::warn!(
scheme,
host,
"media: refused a URL that is not a local file"
);
}
UNSUPPORTED_SCHEME
})
}
// The proxy resolver.
/// The host's resolver, called through its method table.
#[repr(C)]
struct Host {
vtable: *const usize,
}
impl Host {
/// Method `n` of the host object, typed by the caller.
unsafe fn method<F: Copy>(this: *mut Host, n: usize) -> F {
// SAFETY: the caller names the slot's real signature; `this` is the
// host's live resolver.
unsafe { std::mem::transmute_copy(&*(*this).vtable.add(n)) }
}
}
#[repr(C)]
pub struct Resolver {
vtable: &'static Methods,
host: *mut Host,
refs: AtomicU32,
}
type Unknown = *mut c_void;
#[repr(C)]
struct Methods {
query_interface:
extern "system" fn(*mut Resolver, *const [u8; 16], *mut *mut c_void) -> HRESULT,
add_ref: extern "system" fn(*mut Resolver) -> u32,
release: extern "system" fn(*mut Resolver) -> u32,
create_from_url: extern "system" fn(
*mut Resolver,
*const u16,
u32,
Unknown,
*mut u32,
*mut Unknown,
) -> HRESULT,
create_from_stream: extern "system" fn(
*mut Resolver,
Unknown,
*const u16,
u32,
Unknown,
*mut u32,
*mut Unknown,
) -> HRESULT,
begin_from_url: extern "system" fn(
*mut Resolver,
*const u16,
u32,
Unknown,
*mut Unknown,
Unknown,
Unknown,
) -> HRESULT,
end_from_url: extern "system" fn(*mut Resolver, Unknown, *mut u32, *mut Unknown) -> HRESULT,
begin_from_stream: extern "system" fn(
*mut Resolver,
Unknown,
*const u16,
u32,
Unknown,
*mut Unknown,
Unknown,
Unknown,
) -> HRESULT,
end_from_stream: extern "system" fn(*mut Resolver, Unknown, *mut u32, *mut Unknown) -> HRESULT,
cancel: extern "system" fn(*mut Resolver, Unknown) -> HRESULT,
}
static METHODS: Methods = Methods {
query_interface,
add_ref,
release,
create_from_url,
create_from_stream,
begin_from_url,
end_from_url,
begin_from_stream,
end_from_stream,
cancel,
};
fn host(this: *mut Resolver) -> *mut Host {
// SAFETY: title code calls methods on a proxy we made, alive until its
// last release.
unsafe { (*this).host }
}
/// Only the resolver's own interfaces: anything else could hand out the
/// host object unguarded.
extern "system" fn query_interface(
this: *mut Resolver,
iid: *const [u8; 16],
out: *mut *mut c_void,
) -> HRESULT {
if iid.is_null() || out.is_null() {
return E_POINTER;
}
// SAFETY: checked non-null.
let iid = unsafe { *iid };
let found = iid == IID_IUNKNOWN || iid == IID_RESOLVER;
// SAFETY: checked non-null.
unsafe {
out.write(if found {
this.cast()
} else {
std::ptr::null_mut()
})
};
if !found {
return E_NOINTERFACE;
}
add_ref(this);
S_OK
}
extern "system" fn add_ref(this: *mut Resolver) -> u32 {
// SAFETY: as in `host`.
unsafe { (*this).refs.fetch_add(1, Ordering::Relaxed) + 1 }
}
extern "system" fn release(this: *mut Resolver) -> u32 {
// SAFETY: as in `host`.
let left = unsafe { (*this).refs.fetch_sub(1, Ordering::AcqRel) } - 1;
if left == 0 {
// SAFETY: made by `MFCreateSourceResolver`; this was the last
// reference, to the proxy and to the host object it holds.
let proxy = unsafe { Box::from_raw(this) };
// SAFETY: slot 2 is `Release`.
let release: extern "system" fn(*mut Host) -> u32 = unsafe { Host::method(proxy.host, 2) };
release(proxy.host);
}
left
}
extern "system" fn create_from_url(
this: *mut Resolver,
url: *const u16,
flags: u32,
props: Unknown,
kind: *mut u32,
object: *mut Unknown,
) -> HRESULT {
let url = match checked(url) {
Ok(url) => url,
Err(error) => {
if !object.is_null() {
// SAFETY: the title's out parameter.
unsafe { object.write(std::ptr::null_mut()) };
}
return error;
}
};
let host = host(this);
// SAFETY: slot 3 is `CreateObjectFromURL`.
let f: extern "system" fn(
*mut Host,
*const u16,
u32,
Unknown,
*mut u32,
*mut Unknown,
) -> HRESULT = unsafe { Host::method(host, 3) };
f(host, url.as_ptr(), flags, props, kind, object)
}
extern "system" fn begin_from_url(
this: *mut Resolver,
url: *const u16,
flags: u32,
props: Unknown,
cookie: *mut Unknown,
callback: Unknown,
state: Unknown,
) -> HRESULT {
let url = match checked(url) {
Ok(url) => url,
Err(error) => return error,
};
let host = host(this);
// SAFETY: slot 5 is `BeginCreateObjectFromURL`.
let f: extern "system" fn(
*mut Host,
*const u16,
u32,
Unknown,
*mut Unknown,
Unknown,
Unknown,
) -> HRESULT = unsafe { Host::method(host, 5) };
f(host, url.as_ptr(), flags, props, cookie, callback, state)
}
extern "system" fn create_from_stream(
this: *mut Resolver,
stream: Unknown,
url: *const u16,
flags: u32,
props: Unknown,
kind: *mut u32,
object: *mut Unknown,
) -> HRESULT {
let host = host(this);
// SAFETY: slot 4 is `CreateObjectFromByteStream`; the URL is only a
// hint for picking a handler.
let f: extern "system" fn(
*mut Host,
Unknown,
*const u16,
u32,
Unknown,
*mut u32,
*mut Unknown,
) -> HRESULT = unsafe { Host::method(host, 4) };
f(host, stream, url, flags, props, kind, object)
}
extern "system" fn end_from_url(
this: *mut Resolver,
result: Unknown,
kind: *mut u32,
object: *mut Unknown,
) -> HRESULT {
let host = host(this);
// SAFETY: slot 6 is `EndCreateObjectFromURL`.
let f: extern "system" fn(*mut Host, Unknown, *mut u32, *mut Unknown) -> HRESULT =
unsafe { Host::method(host, 6) };
f(host, result, kind, object)
}
#[allow(clippy::too_many_arguments)]
extern "system" fn begin_from_stream(
this: *mut Resolver,
stream: Unknown,
url: *const u16,
flags: u32,
props: Unknown,
cookie: *mut Unknown,
callback: Unknown,
state: Unknown,
) -> HRESULT {
let host = host(this);
// SAFETY: slot 7 is `BeginCreateObjectFromByteStream`.
let f: extern "system" fn(
*mut Host,
Unknown,
*const u16,
u32,
Unknown,
*mut Unknown,
Unknown,
Unknown,
) -> HRESULT = unsafe { Host::method(host, 7) };
f(host, stream, url, flags, props, cookie, callback, state)
}
extern "system" fn end_from_stream(
this: *mut Resolver,
result: Unknown,
kind: *mut u32,
object: *mut Unknown,
) -> HRESULT {
let host = host(this);
// SAFETY: slot 8 is `EndCreateObjectFromByteStream`.
let f: extern "system" fn(*mut Host, Unknown, *mut u32, *mut Unknown) -> HRESULT =
unsafe { Host::method(host, 8) };
f(host, result, kind, object)
}
extern "system" fn cancel(this: *mut Resolver, cookie: Unknown) -> HRESULT {
let host = host(this);
// SAFETY: slot 9 is `CancelObjectCreation`.
let f: extern "system" fn(*mut Host, Unknown) -> HRESULT = unsafe { Host::method(host, 9) };
f(host, cookie)
}
/// The host's resolver behind our proxy.
pub extern "system" fn MFCreateSourceResolver(out: *mut *mut Resolver) -> HRESULT {
if out.is_null() {
return E_POINTER;
}
static CREATE: OnceLock<Option<usize>> = OnceLock::new();
let Some(create) =
*CREATE.get_or_init(|| crate::host::function("mfplat.dll", "MFCreateSourceResolver"))
else {
return UNSUPPORTED_SCHEME;
};
// SAFETY: the host's `MFCreateSourceResolver(IMFSourceResolver**)`.
let create: extern "system" fn(*mut *mut Host) -> HRESULT =
unsafe { std::mem::transmute(create) };
let mut host = std::ptr::null_mut();
let hr = create(&mut host);
if hr < 0 || host.is_null() {
return hr;
}
let proxy = Box::new(Resolver {
vtable: &METHODS,
host,
refs: AtomicU32::new(1),
});
// SAFETY: checked non-null.
unsafe { out.write(Box::into_raw(proxy)) };
S_OK
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "media",
dlls: &["mfplat.dll"],
exports: vec![hle_export!(MFCreateSourceResolver)],
}
}
#[cfg(test)]
mod tests {
use super::*;
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().collect()
}
fn text(v: &[u16]) -> String {
String::from_utf16_lossy(v.strip_suffix(&[0]).unwrap_or(v))
}
#[test]
fn only_local_files_reach_the_host() {
// Network schemes and shares are refused, naming scheme and host.
let refused = |url: &str| local(&wide(url)).unwrap_err();
assert_eq!(
refused("https://cdn.example.com/a.mp4"),
("https".into(), "cdn.example.com".into())
);
assert_eq!(refused("RTSP://10.0.0.1:554/x").0, "rtsp");
assert_eq!(refused("mms://h/x").0, "mms");
assert_eq!(
refused(r"\\server\share\a.mp4"),
("unc".into(), "server".into())
);
assert_eq!(
refused("file://server/share/a.mp4"),
("file".into(), "server".into())
);
// A path on a virtual drive goes to its host folder, also as a
// `file:` URL; other local files pass as they are.
// Checked by opening the files: `files` may spell the host root
// differently (absolute, `\\?\` for long paths) from the temp dir.
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("movies")).unwrap();
std::fs::write(dir.path().join("movies").join("intro.mp4"), b"1").unwrap();
std::fs::write(dir.path().join("movies").join("intro a.mp4"), b"2").unwrap();
let letter = files::mount(dir.path()).expect("a free drive letter");
let host = text(&local(&wide(&format!(r"{letter}:\movies\intro.mp4"))).unwrap());
assert_eq!(
std::fs::read(&host).ok().as_deref(),
Some(&b"1"[..]),
"{host}"
);
let from_url =
text(&local(&wide(&format!("file:///{letter}:/movies/intro%20a.mp4"))).unwrap());
assert_eq!(
std::fs::read(&from_url).ok().as_deref(),
Some(&b"2"[..]),
"{from_url}"
);
assert_eq!(
text(&local(&wide("file:///C:/Windows/a.wav")).unwrap()),
r"C:\Windows\a.wav"
);
assert_eq!(text(&local(&wide("clip.mp4")).unwrap()), "clip.mp4");
}
#[test]
fn interface_ids_are_the_resolvers() {
assert_eq!(&IID_IUNKNOWN[8..], &[0xC0, 0, 0, 0, 0, 0, 0, 0x46]);
assert_eq!(&IID_RESOLVER[..4], &[0x2D, 0xA3, 0xE5, 0xFB]);
}
}
+29
View File
@@ -8,20 +8,37 @@
//! `file` (package paths), `thread` (TLS callbacks for title threads),
//! `xaudio2`, `xstore` stubs.
#[cfg(windows)]
pub mod apu;
pub mod audio;
pub mod d3d12x;
pub mod display;
pub mod dsp;
#[cfg(windows)]
pub mod dstorage;
#[cfg(windows)]
pub mod files;
pub mod gameinput;
pub mod kernel;
#[cfg(windows)]
pub mod lifecycle;
#[cfg(windows)]
pub mod media;
#[cfg(windows)]
pub mod net;
pub mod speech;
pub mod storage;
pub mod xasync;
pub mod xg;
pub mod xgame;
pub mod xgameruntime;
pub mod xgamesave;
pub mod xgameui;
#[cfg(windows)]
pub mod xmem;
pub mod xnetworking;
pub mod xpackage;
pub mod xstore;
pub mod xsystem;
pub mod xuser;
@@ -34,12 +51,24 @@ pub(crate) fn all() -> Vec<HleModule> {
gameinput::module(),
d3d12x::module(),
audio::module(),
dsp::module(),
xg::module(),
];
#[cfg(windows)]
all.push(apu::module());
#[cfg(windows)]
all.push(media::module());
#[cfg(windows)]
all.push(dstorage::module());
#[cfg(windows)]
all.push(files::module());
#[cfg(windows)]
all.push(lifecycle::module());
#[cfg(windows)]
all.push(net::module());
#[cfg(windows)]
all.push(xmem::module());
#[cfg(windows)]
all.push(xsystem::module());
all
}
File diff suppressed because it is too large. Load diff
+151
View File
@@ -0,0 +1,151 @@
//! Accessibility: speech synthesis for the title's narration. No voice is
//! installed here, and every stream is valid WAVE audio of no length, so
//! narration is silent.
// shortcut: silent speech. The host's engine (SAPI through COM, or WinRT
// speech synthesis) needs COM bindings this crate has only in diagnostics
// builds, plus voice enumeration and SSML the title sends (slot 0xa8); the
// title then plays the empty stream and goes on.
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text,
};
/// Closed captions, high contrast, speech to text and synthesis.
pub const PROVIDER: Guid = Guid::new(
0x3e24_1977,
0x6237,
0x41e9,
[0x85, 0x59, 0x10, 0x2c, 0x2d, 0x99, 0x83, 0xf1],
);
/// Unchanged since 2020.
pub const IID: Guid = Guid::new(
0xd722_b373,
0x8c4d,
0x4692,
[0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d],
);
pub static OBJECT: Object = Object::new("accessibility", &VTABLE);
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT)];
/// A WAVE file of 16 kHz mono 16-bit PCM with no samples: RIFF size 36,
/// a 16-byte format chunk (PCM, 1 channel, 16,000 Hz, 32,000 bytes/s,
/// block 2, 16 bits), an empty data chunk.
const SILENCE: [u8; 44] =
*b"RIFF\x24\0\0\0WAVEfmt \x10\0\0\0\x01\0\x01\0\x80\x3e\0\0\0\x7d\0\0\x02\0\x10\0data\0\0\0\0";
/// Synthesizers and streams hold nothing, so their handles are fixed
/// addresses and closing them is free.
static SYNTHESIZER: u8 = 0;
static STREAM: u8 = 0;
type This = *const Object;
/// No voice is installed, so the callback never runs.
extern "system" fn enumerate_voices(
_: This,
_context: *mut c_void,
_callback: *const c_void,
) -> HRESULT {
S_OK
}
extern "system" fn create(_: This, out: *mut *const u8) -> HRESULT {
put(out, &raw const SYNTHESIZER)
}
extern "system" fn close(_: This, _: *const u8) -> HRESULT {
S_OK
}
extern "system" fn set_default_voice(_: This, _: *const u8) -> HRESULT {
S_OK
}
extern "system" fn set_custom_voice(_: This, _: *const u8, _voice: *const c_char) -> HRESULT {
S_OK
}
extern "system" fn create_stream(
_: This,
_: *const u8,
words: *const c_char,
out: *mut *const u8,
) -> HRESULT {
tracing::debug!(text = text(words).unwrap_or_default(), "speech (silent)");
put(out, &raw const STREAM)
}
extern "system" fn stream_size(_: This, _: *const u8, out: *mut usize) -> HRESULT {
put(out, SILENCE.len())
}
extern "system" fn stream_data(
_: This,
_: *const u8,
size: usize,
buffer: *mut u8,
used: *mut usize,
) -> HRESULT {
if buffer.is_null() || size < SILENCE.len() {
return super::xasync::E_NOT_SUFFICIENT_BUFFER;
}
// SAFETY: the buffer holds `size` bytes, checked above.
unsafe { buffer.copy_from_nonoverlapping(SILENCE.as_ptr(), SILENCE.len()) };
if !used.is_null() {
// SAFETY: checked non-null.
unsafe { used.write(SILENCE.len()) };
}
S_OK
}
static VTABLE: Methods<22> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
missing::<3> as *const (), // 0x18 closed captions
missing::<4> as *const (), // 0x20
missing::<5> as *const (), // 0x28 high contrast
missing::<6> as *const (), // 0x30 speech to text
missing::<7> as *const (), // 0x38
enumerate_voices as *const (), // 0x40
create as *const (), // 0x48
close as *const (), // 0x50
set_default_voice as *const (), // 0x58
set_custom_voice as *const (), // 0x60
create_stream as *const (), // 0x68 from text
close as *const (), // 0x70 a stream
stream_size as *const (), // 0x78
stream_data as *const (), // 0x80
missing::<17> as *const (), // 0x88 speech to text
missing::<18> as *const (), // 0x90
missing::<19> as *const (), // 0x98
missing::<20> as *const (), // 0xa0
create_stream as *const (), // 0xa8 from SSML
]);
#[cfg(test)]
mod tests {
use super::*;
use crate::modules::xgameruntime::method;
#[test]
fn streams_are_empty_wave_files() {
let this: This = &OBJECT;
type Create = extern "system" fn(This, *mut *const u8) -> HRESULT;
type Stream = extern "system" fn(This, *const u8, *const c_char, *mut *const u8) -> HRESULT;
type Size = extern "system" fn(This, *const u8, *mut usize) -> HRESULT;
type Data = extern "system" fn(This, *const u8, usize, *mut u8, *mut usize) -> HRESULT;
let (mut synth, mut stream, mut size) = (std::ptr::null(), std::ptr::null(), 0);
assert_eq!(method::<Create>(&OBJECT, 0x48)(this, &mut synth), S_OK);
let say = method::<Stream>(&OBJECT, 0x68);
assert_eq!(say(this, synth, c"Hello".as_ptr(), &mut stream), S_OK);
assert_eq!(method::<Size>(&OBJECT, 0x78)(this, stream, &mut size), S_OK);
let mut wav = vec![0u8; size];
let mut used = 0;
let data = method::<Data>(&OBJECT, 0x80);
assert_eq!(data(this, stream, size, wav.as_mut_ptr(), &mut used), S_OK);
assert_eq!(
(&wav[..4], &wav[8..16], &wav[36..40]),
(&b"RIFF"[..], &b"WAVEfmt "[..], &b"data"[..])
);
assert_eq!(u32::from_le_bytes(wav[24..28].try_into().unwrap()), 16_000);
assert_eq!(used, 44);
}
}
+38 -4
View File
@@ -26,8 +26,17 @@ pub const IID: Guid = Guid::new(
[0x8b, 0x27, 0x95, 0xfc, 0x02, 0xd0, 0xf7, 0x5d],
);
/// As Grand Theft Auto VI (2026) asks for it; it calls 0x20 (path) and 0x28
/// (space) with the same arguments.
pub const IID_2026: Guid = Guid::new(
0x41a4_e10c,
0x5a7e,
0x41d9,
[0x8c, 0x37, 0x37, 0xbd, 0xe6, 0x2a, 0x07, 0xd6],
);
pub static OBJECT: Object = Object::new("persistent local storage", &VTABLE);
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT)];
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT), (PROVIDER, IID_2026, &OBJECT)];
type This = *const Object;
@@ -87,14 +96,38 @@ fn used_bytes(dir: &Path) -> u64 {
.sum()
}
/// What the host disk under `dir` has free (unlimited if unknown).
pub(crate) fn disk_free(dir: &Path) -> u64 {
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
let wide: Vec<u16> = dir.as_os_str().encode_wide().chain([0]).collect();
let mut free = 0;
let null = std::ptr::null_mut();
// SAFETY: a NUL-terminated path and a valid output.
let ok = unsafe {
windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW(
wide.as_ptr(),
&mut free,
null,
null,
)
};
if ok != 0 {
return free;
}
}
let _ = dir;
u64::MAX
}
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,
// Writable now: the quota's rest, as far as the host disk allows.
available_free: free.min(disk_free(&title.storage)),
total_free: free,
used,
total: title.storage_bytes,
@@ -153,6 +186,7 @@ mod tests {
id: 1,
storage: dir.path().to_owned(),
storage_bytes: 1000,
..Default::default()
});
// The path is a drive root, never the host folder.
+265 -13
View File
@@ -100,13 +100,15 @@ impl Port {
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.
// The worker ends once it holds the last reference (every queue
// using the port is closed) and nothing is left to run.
let worker = port.clone();
std::thread::spawn(move || {
loop {
if let Some(task) = worker.take(INFINITE) {
task.run(false);
match worker.take(1000) {
Some(task) => task.run(false),
None if Arc::strong_count(&worker) == 1 => break,
None => {}
}
}
});
@@ -117,9 +119,7 @@ impl 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::ThreadPool => POOL.submit(task),
Mode::Manual | Mode::Serialized => {
lock(&self.tasks).push_back(task);
self.ready.notify_one();
@@ -145,6 +145,49 @@ impl Port {
}
}
/// The thread pool behind thread-pool ports: idle workers are reused, and a
/// new one starts whenever more tasks wait than workers idle, so a callback
/// that blocks on another never starves it. Workers stay for reuse.
struct Pool {
/// Queued tasks and the number of idle workers.
state: Mutex<(VecDeque<Task>, usize)>,
ready: Condvar,
}
static POOL: Pool = Pool {
state: Mutex::new((VecDeque::new(), 0)),
ready: Condvar::new(),
};
impl Pool {
fn submit(&'static self, task: Task) {
let mut state = lock(&self.state);
state.0.push_back(task);
if state.0.len() > state.1 {
std::thread::spawn(move || self.work());
} else {
self.ready.notify_one();
}
}
fn work(&self) {
let mut state = lock(&self.state);
loop {
while state.0.is_empty() {
state.1 += 1;
state = self.ready.wait(state).unwrap_or_else(|e| e.into_inner());
state.1 -= 1;
}
let task = state.0.pop_front();
drop(state);
if let Some(task) = task {
task.run(false);
}
state = lock(&self.state);
}
}
}
/// A queue handle is `Arc::into_raw` of this; duplicating and closing a
/// handle add and drop a reference.
pub struct Queue {
@@ -641,16 +684,167 @@ pub fn XAsyncGetResult(
/// 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 {
finished_with(
block,
identity,
if hr < 0 { Err(hr) } else { Ok(Vec::new()) },
)
}
/// Like [`finished`], with the bytes `XAsyncGetResult` hands out for
/// `identity` (an error has none).
pub fn finished_with(
block: *mut AsyncBlock,
identity: *const c_void,
result: Result<Vec<u8>, HRESULT>,
) -> HRESULT {
type Data = Result<Vec<u8>, HRESULT>;
extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT {
// SAFETY: the runtime passes valid provider data.
// SAFETY: the runtime passes valid provider data; the context is the
// boxed result until cleanup frees it.
let data = unsafe { &*data };
if op == OP_BEGIN {
XAsyncComplete(data.block, data.context as usize as u32 as i32, 0);
let result = data.context.cast::<Data>();
match op {
// SAFETY: boxed in `finished_with`; nothing runs after cleanup.
OP_CLEANUP => drop(unsafe { Box::from_raw(result) }),
OP_BEGIN => {
// SAFETY: as above. Copied out: completing may clean up.
let (hr, len) = match unsafe { &*result } {
Ok(bytes) => (S_OK, bytes.len()),
Err(hr) => (*hr, 0),
};
XAsyncComplete(data.block, hr, len);
}
// SAFETY: as above; the runtime checked the buffer's size.
OP_GET_RESULT => unsafe {
if let Ok(bytes) = &*result {
data.buffer
.cast::<u8>()
.copy_from(bytes.as_ptr(), bytes.len());
}
},
_ => {}
}
S_OK
}
let context = hr as u32 as usize as *mut c_void;
XAsyncBegin(block, context, identity, std::ptr::null(), Some(provider))
let context = Box::into_raw(Box::new(result));
let hr = XAsyncBegin(
block,
context.cast(),
identity,
std::ptr::null(),
Some(provider),
);
if hr < 0 {
// Refused before the call existed, so no cleanup will come.
// SAFETY: still ours.
drop(unsafe { Box::from_raw(context) });
}
hr
}
/// Like [`finished_with`], but the result comes from `work`, run on a
/// thread of ours; the call stays pending until it returns (a dialog, say).
pub fn pending_with(
block: *mut AsyncBlock,
identity: *const c_void,
work: impl FnOnce() -> Result<Vec<u8>, HRESULT> + Send + 'static,
) -> HRESULT {
type Data = Mutex<(Option<Box<dyn FnOnce() -> Result<Vec<u8>, HRESULT> + Send>>, Vec<u8>)>;
extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT {
// SAFETY: the runtime passes valid provider data; the context is the
// boxed state until cleanup frees it.
let data = unsafe { &*data };
let state = data.context.cast::<Data>();
match op {
// SAFETY: boxed in `pending_with`; nothing runs after cleanup.
OP_CLEANUP => drop(unsafe { Box::from_raw(state) }),
OP_BEGIN => {
// SAFETY: as above; cleanup waits for completion.
let work = unsafe { &*state }.lock().unwrap_or_else(|e| e.into_inner()).0.take();
let (block, state) = (data.block as usize, state as usize);
std::thread::spawn(move || {
let result = work.map_or(Err(E_ABORT), |work| work());
let (hr, len) = match &result {
Ok(bytes) => (S_OK, bytes.len()),
Err(hr) => (*hr, 0),
};
if let Ok(bytes) = result {
// SAFETY: the call is pending, so its state lives.
let state = unsafe { &*(state as *const Data) };
state.lock().unwrap_or_else(|e| e.into_inner()).1 = bytes;
}
XAsyncComplete(block as *mut AsyncBlock, hr, len);
});
}
// SAFETY: as above; the runtime checked the buffer's size.
OP_GET_RESULT => unsafe {
let state = (*state).lock().unwrap_or_else(|e| e.into_inner());
data.buffer
.cast::<u8>()
.copy_from(state.1.as_ptr(), state.1.len());
},
_ => {}
}
S_OK
}
let state: Box<Data> = Box::new(Mutex::new((Some(Box::new(work)), Vec::new())));
let context = Box::into_raw(state);
let hr = XAsyncBegin(block, context.cast(), identity, std::ptr::null(), Some(provider));
if hr < 0 {
// SAFETY: refused before the call existed; still ours.
drop(unsafe { Box::from_raw(context) });
}
hr
}
/// The result of a call begun with [`finished_with`] for `identity`, as a
/// `T` written through `out`.
pub fn result<T>(block: *mut AsyncBlock, identity: *const c_void, out: *mut T) -> HRESULT {
XAsyncGetResult(
block,
identity,
size_of::<T>(),
out.cast(),
std::ptr::null_mut(),
)
}
/// The bytes of a value, for [`finished_with`].
pub fn bytes<T: Copy>(value: T) -> Vec<u8> {
// SAFETY: a `Copy` value is plain data; padding bytes are never read.
unsafe { std::slice::from_raw_parts((&raw const value).cast::<u8>(), size_of::<T>()) }.to_vec()
}
type Work = extern "system" fn(*mut AsyncBlock) -> HRESULT;
/// Runs `work` on the block's work port as an async call of its own; its
/// return value is the call's result.
pub fn XAsyncRun(block: *mut AsyncBlock, work: Option<Work>) -> HRESULT {
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 => {
// SAFETY: the context is the `Work` given to `XAsyncRun`.
let work = unsafe { std::mem::transmute::<*mut c_void, Work>(data.context) };
work(data.block)
}
_ => S_OK,
}
}
let Some(work) = work else {
return E_INVALIDARG;
};
let identity = XAsyncRun as *const c_void;
XAsyncBegin(
block,
work as *mut c_void,
identity,
std::ptr::null(),
Some(provider),
)
}
// The object `QueryApiImpl` returns. Each method takes the object first,
@@ -671,6 +865,9 @@ extern "system" fn m_get_result_size(_: This, b: *mut AsyncBlock, out: *mut usiz
extern "system" fn m_cancel(_: This, b: *mut AsyncBlock) {
XAsyncCancel(b)
}
extern "system" fn m_run(_: This, b: *mut AsyncBlock, work: Option<Work>) -> HRESULT {
XAsyncRun(b, work)
}
extern "system" fn m_begin(
_: This,
b: *mut AsyncBlock,
@@ -787,7 +984,7 @@ static VTABLE: Methods<31> = Methods([
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_run as *const (), // 0x30
m_begin as *const (), // 0x38
missing::<8> as *const (), // 0x40
m_schedule as *const (), // 0x48
@@ -927,6 +1124,61 @@ mod tests {
XTaskQueueCloseHandle(q);
}
#[test]
fn run_returns_the_work_result() {
extern "system" fn work(_: *mut AsyncBlock) -> HRESULT {
E_ABORT
}
let mut block = AsyncBlock {
queue: std::ptr::null(),
context: std::ptr::null_mut(),
callback: None,
internal: [0; 4],
};
assert_eq!(
slot::<extern "system" fn(This, *mut AsyncBlock, Option<Work>) -> HRESULT>(0x30)(
&OBJECT,
&mut block,
Some(work)
),
S_OK
);
assert_eq!(XAsyncGetStatus(&mut block, true), E_ABORT);
}
#[test]
fn pool_callbacks_may_wait_for_each_other() {
static SECOND: AtomicBool = AtomicBool::new(false);
static FIRST: AtomicBool = AtomicBool::new(false);
extern "system" fn waits(_: *mut c_void, _: bool) {
let start = std::time::Instant::now();
while !SECOND.load(Ordering::SeqCst) && start.elapsed().as_secs() < 5 {
std::thread::yield_now();
}
FIRST.store(SECOND.load(Ordering::SeqCst), Ordering::SeqCst);
}
extern "system" fn releases(_: *mut c_void, _: bool) {
SECOND.store(true, Ordering::SeqCst);
}
let mut q = std::ptr::null();
assert_eq!(XTaskQueueCreate(1, 1, &mut q), S_OK);
let none = std::ptr::null_mut();
assert_eq!(
XTaskQueueSubmitDelayedCallback(q, WORK, 0, none, Some(waits)),
S_OK
);
assert_eq!(
XTaskQueueSubmitDelayedCallback(q, WORK, 0, none, Some(releases)),
S_OK
);
let start = std::time::Instant::now();
while !FIRST.load(Ordering::SeqCst) && start.elapsed().as_secs() < 10 {
std::thread::sleep(Duration::from_millis(1));
}
assert!(FIRST.load(Ordering::SeqCst));
XTaskQueueCloseHandle(q);
}
#[test]
fn terminate_cancels_what_is_queued() {
static TERMINATED: AtomicBool = AtomicBool::new(false);
+780
View File
@@ -0,0 +1,780 @@
//! `xg_xs.dll`: the console's texture layout library. Titles ask it which
//! swizzle mode a texture should use, how large it is, where each mip and
//! slice lies, and to copy linear data into tiled memory and back. Served
//! from `victory_formats::texture`.
//!
//! Grand Theft Auto VI imports `XGCreateTextureComputer` and
//! `XGSuggestSwizzleMode` and calls these computer methods: Release (0x08),
//! the layout (0x10), copies into (0x40) and out of (0x48) a subresource,
//! and the 64 KiB tiling (0x50). The other slots log and fail.
#![allow(non_snake_case)]
// Title code passes pointers the real library would trust.
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::sync::atomic::{AtomicU32, Ordering};
use victory_formats::texture::{Dimension, Error, Layout, Swizzle, Texture, TextureDesc};
use super::xasync::{E_INVALIDARG, E_NOTIMPL};
use super::xgameruntime::{HRESULT, S_OK};
use crate::{HleModule, hle_export};
const E_FAIL: HRESULT = 0x8000_4005_u32 as i32;
/// `D3D12_RESOURCE_DESC`, whose layout field carries `0x100 | swizzle
/// mode` on the console (1 row major, 0 "pick one").
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct ResourceDesc {
pub dimension: u32,
pub alignment: u64,
pub width: u64,
pub height: u32,
pub depth_or_array: u16,
pub mips: u16,
pub format: u32,
pub samples: u32,
pub quality: u32,
pub layout: u32,
pub flags: u32,
}
const _: () = assert!(size_of::<ResourceDesc>() == 0x38);
const SWIZZLED: u32 = 0x100;
const ROW_MAJOR: u32 = 1;
const ALLOW_RENDER_TARGET: u32 = 1;
const ALLOW_DEPTH_STENCIL: u32 = 2;
const TEXTURE_1D: u32 = 2;
const TEXTURE_3D: u32 = 4;
/// The mode the console's library picks for a description: linear for 1D,
/// the XOR render and depth modes for targets, else 4 KiB standard
/// (`.ttpf` textures without a mode of their own use it).
///
/// shortcut: the rule of the library's older optimal-mode function (any
/// size, 2D, 3D and cubes alike); `XGSuggestSwizzleMode` itself is newer
/// than every copy we could check. Revisit if streamed textures come out
/// scrambled.
fn suggested(desc: &ResourceDesc) -> Swizzle {
if desc.dimension == TEXTURE_1D {
Swizzle::LINEAR
} else if desc.flags & ALLOW_DEPTH_STENCIL != 0 {
Swizzle::SW_64KB_Z_X
} else if desc.flags & ALLOW_RENDER_TARGET != 0 {
Swizzle::SW_64KB_R_X
} else {
Swizzle::SW_4KB_S
}
}
/// `(desc, flags, out layout)`; the title passes flags 0 and puts the
/// result in the description's layout field.
pub extern "system" fn XGSuggestSwizzleMode(
desc: *const ResourceDesc,
_flags: u32,
out: *mut u32,
) -> HRESULT {
// SAFETY: the title passes a description and room for the layout
// (either may be null).
match unsafe { (desc.as_ref(), out.as_mut()) } {
(Some(desc), Some(out)) => {
*out = SWIZZLED | suggested(desc).0;
S_OK
}
_ => E_INVALIDARG,
}
}
#[repr(C)]
pub struct Computer {
vtable: &'static Vtable,
refs: AtomicU32,
desc: ResourceDesc,
mips: u32,
texture: Texture,
}
type This = *mut Computer;
fn computer<'a>(this: This) -> &'a Computer {
// SAFETY: called from computer methods only.
unsafe { &*this }
}
pub extern "system" fn XGCreateTextureComputer(
desc: *const ResourceDesc,
out: *mut This,
) -> HRESULT {
// SAFETY: the title passes a description and room for a pointer.
let (Some(&desc), false) = (unsafe { desc.as_ref() }, out.is_null()) else {
return E_INVALIDARG;
};
let Some(texture) = texture(&desc) else {
tracing::warn!(?desc, "no texture layout");
return E_INVALIDARG;
};
tracing::debug!(
width = desc.width,
height = desc.height,
format = desc.format,
layout = format_args!("{:#x}", desc.layout),
size = texture.size,
"texture computer"
);
let mips = texture.planes[0].layout.mips.len() as u32;
let computer = Box::new(Computer {
vtable: &VTABLE,
refs: AtomicU32::new(1),
desc,
mips,
texture,
});
// SAFETY: checked non-null.
unsafe { out.write(Box::into_raw(computer)) };
S_OK
}
fn texture(desc: &ResourceDesc) -> Option<Texture> {
let dimension = match desc.dimension {
TEXTURE_1D => Dimension::Tex1d,
3 => Dimension::Tex2d,
TEXTURE_3D => Dimension::Tex3d,
_ => return None,
};
let swizzle = match desc.layout {
0 => suggested(desc),
ROW_MAJOR => Swizzle::LINEAR,
l if l & !0xff == SWIZZLED => Swizzle(l & 0xff),
_ => return None,
};
let texture = Texture::new(&TextureDesc {
dimension,
width: u32::try_from(desc.width).ok()?,
height: desc.height,
depth_or_array: u32::from(desc.depth_or_array),
mips: u32::from(desc.mips),
format: desc.format,
samples: desc.samples.max(1),
swizzle,
})
.ok()?;
// The layout struct has room for 15 mips.
(texture.planes[0].layout.mips.len() <= MIPS).then_some(texture)
}
const MIPS: usize = 15;
/// One mip in the layout the title reads (offsets 0x00, 0x08, 0x10 and
/// 0x1c are read by Grand Theft Auto VI; the rest follow the library's
/// older public shape).
#[repr(C)]
#[derive(Debug, Default, Clone, Copy)]
pub struct MipOut {
pub size: u64,
pub offset: u64,
pub slice_size: u64,
pub pitch_texels: u32,
pub pitch_bytes: u32,
pub alignment: u32,
/// Width, height in elements, depth or array size.
pub padded: [u32; 3],
pub elements: [u32; 2],
pub texels: [u32; 2],
pub depth_or_array: u32,
pub samples: u32,
pub swizzle: u32,
pub bank_rotation: [u64; 2],
pub slice_depth: u32,
pub in_tail: u32,
/// Where a tail mip starts in elements: x bits 0-10, y 11-21.
pub tail_position: u32,
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct PlaneOut {
/// 1 data, 7 depth, 8 stencil (metadata planes are not made).
pub usage: u32,
pub size: u64,
pub slice_size: u64,
pub offset: u64,
pub alignment: u64,
pub element_bytes: u32,
pub standard_mips: u32,
pub tail_mips: u32,
pub mips: [MipOut; MIPS],
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct LayoutOut {
pub size: u64,
pub alignment: u64,
pub mips: u32,
pub planes: u32,
pub plane: [PlaneOut; 4],
pub dimension: u32,
}
const _: () = assert!(size_of::<MipOut>() == 0x70);
const _: () = assert!(size_of::<PlaneOut>() == 0x6c8);
const _: () = assert!(size_of::<LayoutOut>() == 0x1b40);
/// The mode a tail mip is reported in: the 256-byte one of its kind (3 for
/// the render kind, which GFX10 lacks), the depth mode itself.
fn tail_swizzle(swizzle: Swizzle) -> u32 {
match swizzle.0 {
2 | 6 | 10 | 18 | 22 | 26 => Swizzle::SW_256B_D.0,
23 | 27 => 3,
24 => swizzle.0,
_ => Swizzle::SW_256B_S.0,
}
}
fn mip_out(desc: &ResourceDesc, l: &Layout, i: usize) -> MipOut {
let m = &l.mips[i];
let bpe = u64::from(l.desc.element_bytes);
let block = l.desc.block;
let three_d = desc.dimension == TEXTURE_3D;
let array = u32::from(desc.depth_or_array).max(1);
let mut out = MipOut {
pitch_texels: m.pitch * block,
pitch_bytes: m.pitch * l.desc.element_bytes,
padded: [m.pitch, m.rows, if three_d { m.depth_pitch } else { array }],
elements: [m.width, m.height],
texels: [((desc.width >> i) as u32).max(1), (desc.height >> i).max(1)],
depth_or_array: if three_d { m.depth } else { array },
samples: l.desc.samples,
slice_depth: l.block[2],
..MipOut::default()
};
let slice = u64::from(m.pitch) * u64::from(m.rows) * bpe;
let depth = u64::from(if three_d { m.depth_pitch } else { 1 });
match m.tail {
None => {
out.offset = m.offset;
out.slice_size = slice * u64::from(l.desc.samples);
out.size = out.slice_size * depth;
out.alignment = l.alignment as u32;
out.swizzle = l.desc.swizzle.0;
}
Some(t) => {
out.in_tail = 1;
out.alignment = 256;
out.swizzle = tail_swizzle(l.desc.swizzle);
if l.thick {
// A 3D tail mip is placed by position, not by offset.
out.slice_size = l.alignment / u64::from(l.block[2]);
out.tail_position = t.x | t.y << 11;
} else {
out.offset = u64::from(t.offset);
out.slice_size = slice;
}
out.size = out.slice_size * depth;
}
}
out
}
extern "system" fn add_ref(this: This) -> u32 {
computer(this).refs.fetch_add(1, Ordering::Relaxed) + 1
}
extern "system" fn release(this: This) -> u32 {
let left = computer(this).refs.fetch_sub(1, Ordering::AcqRel) - 1;
if left == 0 {
// SAFETY: made by `Box::into_raw` in `XGCreateTextureComputer`; the
// last reference is gone.
drop(unsafe { Box::from_raw(this) });
}
left
}
extern "system" fn layout(this: This, out: *mut LayoutOut) -> HRESULT {
if out.is_null() {
return E_INVALIDARG;
}
let c = computer(this);
// SAFETY: the title passes room for the layout; every field is plain
// data, so zeroes are a valid start.
let out = unsafe {
out.write_bytes(0, 1);
&mut *out
};
out.size = c.texture.size;
out.alignment = c.texture.alignment;
out.mips = c.mips;
out.planes = c.texture.planes.len() as u32;
out.dimension = c.desc.dimension;
// The library calls a depth plane "depth" only beside stencil or
// without mips.
let depth =
c.desc.flags & ALLOW_DEPTH_STENCIL != 0 && (c.texture.planes.len() > 1 || c.mips == 1);
for (plane, p) in out.plane.iter_mut().zip(&c.texture.planes) {
let l = &p.layout;
plane.usage = match (p.stencil, depth) {
(true, _) => 8,
(false, true) => 7,
(false, false) => 1,
};
plane.size = l.size;
plane.slice_size = l.slice_size;
plane.offset = p.offset;
plane.alignment = l.alignment;
plane.element_bytes = l.desc.element_bytes;
plane.standard_mips = l.first_tail_mip;
plane.tail_mips = c.mips - l.first_tail_mip;
for (i, mip) in plane.mips.iter_mut().take(l.mips.len()).enumerate() {
*mip = mip_out(&c.desc, l, i);
}
}
S_OK
}
/// The plane, its mip and array slice for a subresource index, and the
/// tiled bytes and the linear bytes the copy touches.
struct CopyArgs<'a> {
layout: &'a Layout,
mip: u32,
slice: u32,
tiled: usize,
linear: usize,
}
fn copy_args(
c: &Computer,
plane: u32,
subresource: u32,
row: u32,
depth: u32,
) -> Option<CopyArgs<'_>> {
let p = c.texture.planes.get(plane as usize)?;
let l = &p.layout;
let (mip, slice) = (subresource % c.mips, subresource / c.mips);
let m = l.mips.get(mip as usize)?;
let bytes = m.width as usize * l.desc.element_bytes as usize;
let depths = l.subresource_depth(mip) as usize;
let linear = (depths - 1) * depth as usize + (m.height as usize - 1) * row as usize + bytes;
Some(CopyArgs {
layout: l,
mip,
slice,
tiled: (p.offset + l.size) as usize,
linear,
})
}
fn result(r: Result<(), Error>) -> HRESULT {
match r {
Ok(()) => S_OK,
Err(Error::Unsupported) => E_NOTIMPL,
Err(_) => E_INVALIDARG,
}
}
/// `(tiled base, plane, subresource, linear, row pitch, depth pitch)`.
extern "system" fn copy_into(
this: This,
tiled: *mut u8,
plane: u32,
subresource: u32,
linear: *const u8,
row: u32,
depth: u32,
) -> HRESULT {
let c = computer(this);
let Some(a) = copy_args(c, plane, subresource, row, depth) else {
return E_INVALIDARG;
};
if tiled.is_null() || linear.is_null() {
return E_INVALIDARG;
}
let offset = c.texture.planes[plane as usize].offset as usize;
// SAFETY: the title's memory holds the whole texture and its rows.
let (tiled, linear) = unsafe {
(
std::slice::from_raw_parts_mut(tiled.add(offset), a.tiled - offset),
std::slice::from_raw_parts(linear, a.linear),
)
};
let r = a
.layout
.tile(tiled, a.mip, a.slice, linear, row as usize, depth as usize);
if r.is_err() {
tracing::warn!(?r, desc = ?c.desc, subresource, "copy into a texture failed");
}
result(r)
}
/// `(linear, plane, subresource, sample, tiled base, row pitch, depth
/// pitch)`.
#[allow(clippy::too_many_arguments)]
extern "system" fn copy_from(
this: This,
linear: *mut u8,
plane: u32,
subresource: u32,
_sample: u32,
tiled: *const u8,
row: u32,
depth: u32,
) -> HRESULT {
let c = computer(this);
let Some(a) = copy_args(c, plane, subresource, row, depth) else {
return E_INVALIDARG;
};
if tiled.is_null() || linear.is_null() {
return E_INVALIDARG;
}
let offset = c.texture.planes[plane as usize].offset as usize;
// SAFETY: the title's memory holds the whole texture and its rows.
let (tiled, linear) = unsafe {
(
std::slice::from_raw_parts(tiled.add(offset), a.tiled - offset),
std::slice::from_raw_parts_mut(linear, a.linear),
)
};
let r = a
.layout
.detile(tiled, a.mip, a.slice, linear, row as usize, depth as usize);
if r.is_err() {
tracing::warn!(?r, desc = ?c.desc, subresource, "copy out of a texture failed");
}
result(r)
}
#[repr(C)]
pub struct PackedMips {
pub standard: u8,
pub packed: u8,
pub tiles: u32,
pub start: u32,
}
#[repr(C)]
pub struct SubresourceTiling {
pub width: u32,
pub height: u16,
pub depth: u16,
pub start: u32,
}
const TILE: u64 = 64 << 10;
/// `(total tiles, packed mips, tile shape in texels, in: room / out:
/// count, first, subresource tilings)`, in 64 KiB tiles of plane 0, for 2D
/// 64 KiB modes only (others fail, as on the console). The mip tail is the
/// packed part, tile 0 of each slice; tilings list the standard mips of
/// every slice in turn. With a tail the console's library lists two slices
/// at most and zeroes all but the first; so do we (the title reads slice 0
/// only).
extern "system" fn tiling(
this: This,
tiles: *mut u32,
packed: *mut PackedMips,
shape: *mut [u32; 3],
count: *mut u32,
first: u32,
out: *mut SubresourceTiling,
) -> HRESULT {
let c = computer(this);
let l = &c.texture.planes[0].layout;
if l.alignment != TILE {
return E_FAIL;
}
if l.thick {
return E_NOTIMPL;
}
let standard = l.first_tail_mip;
let tail = standard < c.mips;
let tail_tiles = match standard {
0 => l.slice_size / TILE,
s if s < c.mips => l.mips[s as usize - 1].offset / TILE,
_ => 0,
};
let block = l.desc.block;
// SAFETY: each output is null or room for its value; `out` has room
// for `*count` entries.
unsafe {
if let Some(t) = tiles.as_mut() {
*t = (l.size / TILE) as u32;
}
if let Some(p) = packed.as_mut() {
*p = PackedMips {
standard: standard as u8,
packed: (c.mips - standard) as u8,
tiles: tail_tiles as u32,
start: 0,
};
}
if let Some(s) = shape.as_mut() {
*s = [l.block[0] * block, l.block[1] * block, l.block[2]];
}
if let Some(n) = count.as_mut() {
let slices = if tail { l.slices.min(2) } else { l.slices };
let wanted = (standard * slices).saturating_sub(first).min(*n);
for i in 0..wanted {
let (slice, mip) = ((first + i) / standard, (first + i) % standard);
let m = &l.mips[mip as usize];
let entry = if tail && slice > 0 {
SubresourceTiling {
width: 0,
height: 0,
depth: 0,
start: 0,
}
} else {
SubresourceTiling {
width: m.pitch / l.block[0],
height: (m.rows / l.block[1]) as u16,
depth: 1,
start: ((u64::from(slice) * l.slice_size + m.offset) / TILE) as u32,
}
};
out.add(i as usize).write(entry);
}
*n = wanted;
}
}
S_OK
}
/// Slot 0x30 `(plane, mip, x, y, z or slice, sample, bit position)`: an
/// element's byte offset from the texture's start. Grand Theft Auto VI reads
/// texels of a 128x4 `4KB_S` texture on the CPU through it (title+0x5151c90);
/// an error returned as an offset made it read wild memory. 0 if outside.
extern "system" fn element_offset(
this: This,
plane: u32,
mip: u32,
x: u64,
y: u32,
z: u32,
_sample: u32,
bit: *mut u32,
) -> u64 {
if !bit.is_null() {
// SAFETY: the caller passes room for the bit position or null.
unsafe { bit.write(0) };
}
let Some(p) = computer(this).texture.planes.get(plane as usize) else {
return 0;
};
let x = u32::try_from(x).unwrap_or(u32::MAX);
match p.layout.offset(mip, x, y, z) {
Ok(at) => p.offset + at,
Err(e) => {
tracing::warn!(?e, mip, x, y, z, "texel outside its texture");
0
}
}
}
/// Slots the title does not call: size, alignment, offsets, coordinates,
/// view descriptor, tiled-resource query.
extern "system" fn unused(this: This) -> HRESULT {
tracing::warn!(desc = ?computer(this).desc, "unimplemented texture computer method");
E_NOTIMPL
}
#[repr(C)]
struct Vtable([*const (); 13]);
// SAFETY: function addresses only.
unsafe impl Sync for Vtable {}
static VTABLE: Vtable = Vtable([
add_ref as *const (), // 0x00
release as *const (), // 0x08
layout as *const (), // 0x10
unused as *const (), // 0x18 size
unused as *const (), // 0x20 alignment
unused as *const (), // 0x28 mip offset
element_offset as *const (), // 0x30
unused as *const (), // 0x38 element coordinate
copy_into as *const (), // 0x40
copy_from as *const (), // 0x48
tiling as *const (), // 0x50
unused as *const (), // 0x58 view descriptor
unused as *const (), // 0x60 tiled resource?
]);
pub(crate) fn module() -> HleModule {
HleModule {
name: "xg",
dlls: &["xg_xs.dll"],
exports: vec![
hle_export!(XGCreateTextureComputer),
hle_export!(XGSuggestSwizzleMode),
],
}
}
#[cfg(test)]
mod tests {
use super::*;
fn desc(width: u64, height: u32, mips: u16, format: u32, layout: u32) -> ResourceDesc {
ResourceDesc {
dimension: 3,
alignment: 0,
width,
height,
depth_or_array: 1,
mips,
format,
samples: 1,
quality: 0,
layout,
flags: 0,
}
}
/// Method `index` of a computer, as the title calls it.
fn slot<T: Copy>(c: This, index: usize) -> T {
// SAFETY: the computer is live; T is the slot's function type.
unsafe { std::mem::transmute_copy(&(*c).vtable.0[index]) }
}
fn create(d: &ResourceDesc) -> This {
let mut c = std::ptr::null_mut();
assert_eq!(XGCreateTextureComputer(d, &mut c), S_OK);
c
}
/// Element offsets: linear rows of 1 KiB (128 elements), 0 outside.
#[test]
fn element_offsets_follow_the_layout() {
type Offset = extern "system" fn(This, u32, u32, u64, u32, u32, u32, *mut u32) -> u64;
let c = create(&desc(128, 4, 1, 11, 0x100));
let offset: Offset = slot(c, 6);
let mut bit = 7;
assert_eq!(offset(c, 0, 0, 3, 1, 0, 0, &mut bit), (128 + 3) * 8);
assert_eq!(bit, 0);
assert_eq!(offset(c, 0, 0, 128, 0, 0, 0, std::ptr::null_mut()), 0);
slot::<extern "system" fn(This) -> u32>(c, 1)(c);
}
#[test]
fn suggestions_follow_the_use() {
let mut out = 0;
let mut d = desc(256, 256, 1, 98, 0);
assert_eq!(XGSuggestSwizzleMode(&d, 0, &mut out), S_OK);
assert_eq!(out, 0x105);
d.flags = ALLOW_RENDER_TARGET;
XGSuggestSwizzleMode(&d, 0, &mut out);
assert_eq!(out, 0x11b);
d.flags = ALLOW_DEPTH_STENCIL;
XGSuggestSwizzleMode(&d, 0, &mut out);
assert_eq!(out, 0x118);
}
/// The title's calls: layout, then a copy in and out of each mip.
#[test]
fn layout_and_copies_through_the_object() {
// 256x256 BC7, full chain, 64 KiB display mode.
let c = create(&desc(256, 256, 0, 98, 0x10a));
// SAFETY: plain data, filled by the call.
let mut l: Box<LayoutOut> = Box::new(unsafe { std::mem::zeroed() });
let get: extern "system" fn(This, *mut LayoutOut) -> HRESULT = slot(c, 2);
assert_eq!(get(c, &mut *l), S_OK);
assert_eq!(
(l.size, l.alignment, l.mips, l.planes),
(131072, 65536, 9, 1)
);
let p = &l.plane[0];
assert_eq!((p.standard_mips, p.tail_mips, p.element_bytes), (1, 8, 16));
assert_eq!((p.mips[0].offset, p.mips[0].pitch_bytes), (65536, 1024));
assert_eq!((p.mips[1].offset, p.mips[1].in_tail), (32768, 1));
type Into = extern "system" fn(This, *mut u8, u32, u32, *const u8, u32, u32) -> HRESULT;
type From =
extern "system" fn(This, *mut u8, u32, u32, u32, *const u8, u32, u32) -> HRESULT;
let (into, from): (Into, From) = (slot(c, 8), slot(c, 9));
let mut tiled = vec![0u8; l.size as usize];
for mip in 0..9u32 {
let m = &p.mips[mip as usize];
let row = m.elements[0] * 16;
let rows: Vec<u8> = (0..row * m.elements[1]).map(|i| (i ^ mip) as u8).collect();
assert_eq!(
into(c, tiled.as_mut_ptr(), 0, mip, rows.as_ptr(), row, 0),
S_OK
);
let mut back = vec![0u8; rows.len()];
assert_eq!(
from(c, back.as_mut_ptr(), 0, mip, 0, tiled.as_ptr(), row, 0),
S_OK
);
assert_eq!(back, rows, "mip {mip}");
}
// 0x50: one tile for the tail, one for mip 0.
type Tiling = extern "system" fn(
This,
*mut u32,
*mut PackedMips,
*mut [u32; 3],
*mut u32,
u32,
*mut SubresourceTiling,
) -> HRESULT;
let tiling: Tiling = slot(c, 10);
let (mut tiles, mut shape, mut n) = (0, [0; 3], 4);
let mut packed = PackedMips {
standard: 0,
packed: 0,
tiles: 0,
start: 0,
};
let mut subs: Vec<SubresourceTiling> = (0..4)
.map(|_| SubresourceTiling {
width: 0,
height: 0,
depth: 0,
start: 0,
})
.collect();
assert_eq!(
tiling(
c,
&mut tiles,
&mut packed,
&mut shape,
&mut n,
0,
subs.as_mut_ptr()
),
S_OK
);
assert_eq!(
(tiles, packed.standard, packed.packed, packed.tiles),
(2, 1, 8, 1)
);
assert_eq!((shape, n, subs[0].start), ([256, 256, 1], 1, 1));
assert_eq!(release(c), 0);
// 4 KiB modes have no 64 KiB tiling.
let null = std::ptr::null_mut::<u8>();
let c = create(&desc(256, 256, 0, 98, 0x105));
assert_eq!(
tiling(
c,
&mut tiles,
null.cast(),
null.cast(),
null.cast(),
0,
null.cast()
),
E_FAIL
);
assert_eq!(release(c), 0);
}
#[test]
fn bad_descriptions_fail() {
let mut c = std::ptr::null_mut();
let bad = desc(256, 256, 1, 0, 0x10a);
assert_eq!(XGCreateTextureComputer(&bad, &mut c), E_INVALIDARG);
let bad = desc(256, 256, 1, 28, 0x103);
assert_eq!(XGCreateTextureComputer(&bad, &mut c), E_INVALIDARG);
assert!(module().exports.len() == 2);
}
}
+78 -9
View File
@@ -6,7 +6,7 @@
use std::ffi::{CStr, c_char, c_void};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, token,
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, token,
};
use crate::runtime;
@@ -62,12 +62,65 @@ extern "system" fn title_id(_: This, out: *mut u32) -> HRESULT {
put(out, runtime::title().id)
}
/// As documented: the title ends (suspended first, as on any end) and the
/// game starts again in a new process; this never returns. Grand Theft
/// Auto VI relaunches itself (its own path from `GetModuleFileNameA`) with
/// arguments from its configuration. The new `victory run` gets the same
/// options, the new executable, and the title's arguments after `--`
/// (the title reads the whole command line).
extern "system" fn launch_new_game(
_: This,
exe: *const c_char,
args: *const c_char,
_user: *const c_void,
) {
let (exe, args) = (text(exe).unwrap_or_default(), text(args).unwrap_or_default());
tracing::info!(exe, args, "XLaunchNewGame");
let current = runtime::main_image()
.and_then(runtime::image_path)
.unwrap_or_default();
let ours: Vec<_> = std::env::args_os().skip(1).collect();
let command = relaunch_args(ours, current.as_os_str(), &exe, &args);
super::lifecycle::end_title(
"XLaunchNewGame",
Box::new(move || super::lifecycle::relaunch(command)),
);
loop {
std::thread::park();
}
}
/// Our own arguments for the relaunch: the title's executable replaced by
/// `exe`, earlier title arguments dropped, `args` after `--`.
fn relaunch_args(
ours: Vec<std::ffi::OsString>,
current: &std::ffi::OsStr,
exe: &str,
args: &str,
) -> Vec<std::ffi::OsString> {
let mut out: Vec<_> = ours.into_iter().take_while(|a| a != "--").collect();
if !exe.is_empty()
&& let Some(slot) = out.iter_mut().find(|a| a.as_os_str() == current)
{
*slot = exe.into();
}
if !args.trim().is_empty() {
out.push("--".into());
out.extend(args.split_whitespace().map(Into::into));
}
out
}
/// 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];
/// serve: accessibility (0), app capture (1), async calls and providers
/// (2, 3), display (4), game (5), invites (6), game saves (7), game UI (8),
/// launcher (9), networking (10), packages (11), persistent local storage
/// (12), speech synthesis (13), store (14), system (15), task queues (16),
/// users (18), error reports (19), game events (20). Not threads (17) or
/// game streaming (21).
const AVAILABLE: [u32; 20] = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20,
];
extern "system" fn is_feature_available(_: This, feature: u32) -> bool {
AVAILABLE.contains(&feature)
@@ -109,8 +162,8 @@ 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)
title_id as *const (), // 0x18
launch_new_game as *const (), // 0x20
]);
static FEATURES_VTABLE: Methods<4> = Methods([
@@ -140,12 +193,28 @@ mod tests {
use super::*;
use crate::modules::xgameruntime::method;
#[test]
fn a_relaunch_keeps_our_options() {
let ours: Vec<std::ffi::OsString> =
["run", "G:/game.exe", "--execute", "--console", "series-s", "--", "-old"]
.map(Into::into)
.into();
let current = std::ffi::OsStr::new("G:/game.exe");
let again = relaunch_args(ours.clone(), current, "G:/game.exe", " -config=x -y ");
let expected = ["run", "G:/game.exe", "--execute", "--console", "series-s", "--"];
assert_eq!(again[..6], expected.map(std::ffi::OsString::from));
assert_eq!(again[6..], ["-config=x", "-y"].map(std::ffi::OsString::from));
let other = relaunch_args(ours, current, "G:/other.exe", "");
assert_eq!(other.len(), 5);
assert_eq!(other[1], "G:/other.exe");
}
#[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");
assert!(!check(&FEATURES_OBJECT, 21), "game streaming");
type Register = extern "system" fn(
This,
+51 -6
View File
@@ -8,10 +8,13 @@
//! 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`).
//! whose slots we know. Implemented, as an offline retail console with one
//! signed-in user: task queues and async blocks (`xasync`), the user
//! (`xuser`), system information (`xsystem`), title id, feature checks,
//! invites and events (`xgame`), persistent local storage (`storage`), game
//! saves (`xgamesave`), networking (`xnetworking`), the package
//! (`xpackage`), the store (`xstore`), system dialogs (`xgameui`), speech
//! (`speech`), HDR, URIs, display deferrals and screenshots (`display`).
#![allow(non_snake_case)]
// Title code calls these through its import table, passing pointers the real
// API would trust.
@@ -21,7 +24,10 @@ 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 super::{
display, speech, storage, xasync, xgame, xgamesave, xgameui, xnetworking, xpackage, xstore,
xsystem, xuser,
};
use crate::{HleModule, hle_export};
pub type HRESULT = i32;
@@ -91,12 +97,19 @@ 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] = [
const AREAS: &[&[Interface]] = &[
xasync::INTERFACES,
xuser::INTERFACES,
xsystem::INTERFACES,
xgame::INTERFACES,
storage::INTERFACES,
xnetworking::INTERFACES,
xpackage::INTERFACES,
display::INTERFACES,
xgamesave::INTERFACES,
xstore::INTERFACES,
xgameui::INTERFACES,
speech::INTERFACES,
];
/// `AddRef` and `Release`.
@@ -146,6 +159,12 @@ pub fn put_string(text: &str, size: usize, buffer: *mut u8, used: *mut usize) ->
S_OK
}
/// The title's NUL-terminated string, if any.
pub fn text(s: *const c_char) -> Option<String> {
// SAFETY: the title passes a NUL-terminated string or null.
(!s.is_null()).then(|| unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned())
}
/// A new registration token for callbacks we never call (events nobody
/// raises offline).
pub fn token() -> u64 {
@@ -181,6 +200,19 @@ pub extern "system" fn InitializeApiImplEx(version: u64, build: u64, flags: u64)
S_OK
}
/// The stub prefers this one when present. It passes the same three values
/// and a pointer to the title's initialisation options, null unless the
/// title initialises with options (Grand Theft Auto VI does not).
pub extern "system" fn InitializeApiImplEx2(
version: u64,
build: u64,
flags: u64,
options: *const c_void,
) -> HRESULT {
tracing::info!(version, build, flags, ?options, "InitializeApiImplEx2");
S_OK
}
pub extern "system" fn UninitializeApiImpl() {
tracing::info!("UninitializeApiImpl");
}
@@ -198,6 +230,17 @@ pub extern "system" fn QueryApiImpl(
else {
return NOT_SUPPORTED;
};
#[cfg(feature = "diagnostics")]
if tracing::enabled!(tracing::Level::DEBUG) {
// Each runtime call site once: which title code uses which area, when.
static CALLS: Mutex<Vec<String>> = Mutex::new(Vec::new());
let from = super::kernel::callers();
let mut calls = CALLS.lock().unwrap_or_else(|e| e.into_inner());
if !calls.contains(&from) {
tracing::debug!(%provider, %iid, %from, "runtime call");
calls.push(from);
}
}
let found = AREAS
.iter()
.flat_map(|area| area.iter())
@@ -236,6 +279,7 @@ pub(crate) fn module() -> HleModule {
hle_export!(XGameRuntimeUninitialize),
hle_export!(InitializeApiImpl),
hle_export!(InitializeApiImplEx),
hle_export!(InitializeApiImplEx2),
hle_export!(UninitializeApiImpl),
hle_export!(QueryApiImpl),
hle_export!(XErrorReport),
@@ -257,6 +301,7 @@ mod tests {
for name in [
c"InitializeApiImpl",
c"InitializeApiImplEx",
c"InitializeApiImplEx2",
c"QueryApiImpl",
c"UninitializeApiImpl",
c"XErrorReport",
File diff suppressed because it is too large. Load diff
+321
View File
@@ -0,0 +1,321 @@
//! System dialogs a title opens (XGameUi). A profile card has nothing to
//! show and closes at once. Text entry opens a small host dialog (title,
//! description, default text, the length limit) on a thread of its own and
//! completes the call with what the user typed, or as cancelled (`E_ABORT`)
//! when the dialog is dismissed or cannot open.
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xasync::{self, AsyncBlock, E_ABORT};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text,
};
pub const PROVIDER: Guid = Guid::new(
0xdfcd_4649,
0x4ff8,
0x4043,
[0xba, 0x07, 0x35, 0xd6, 0x07, 0xdf, 0x98, 0xb0],
);
/// As Grand Theft Auto VI (2026) asks for it; the slots it calls (0x38,
/// 0x40, 0x88-0x98) take the public API's arguments in the 2020 order.
pub const IID_2026: Guid = Guid::new(
0xeaf6_69df,
0x5542,
0x4590,
[0x99, 0xa3, 0x8d, 0xc0, 0x61, 0xf8, 0x37, 0xcc],
);
pub static OBJECT: Object = Object::new("game ui", &VTABLE);
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID_2026, &OBJECT)];
type This = *const Object;
static PROFILE: u8 = 0;
static TEXT: u8 = 0;
extern "system" fn profile_card_async(
_: This,
block: *mut AsyncBlock,
_user: *const c_void,
xuid: u64,
) -> HRESULT {
tracing::info!(xuid, "profile card: nothing to show");
xasync::finished(block, (&raw const PROFILE).cast(), S_OK)
}
extern "system" fn profile_card_result(_: This, block: *mut AsyncBlock) -> HRESULT {
let none = std::ptr::null_mut();
xasync::XAsyncGetResult(block, (&raw const PROFILE).cast(), 0, none, none.cast())
}
/// Grand Theft Auto VI treats `E_ABORT` as cancelled and goes on; any
/// other failure as an error.
extern "system" fn text_entry_async(
_: This,
block: *mut AsyncBlock,
title: *const c_char,
description: *const c_char,
default: *const c_char,
_scope: u32,
max_length: u32,
) -> HRESULT {
let [title, description, default] = [title, description, default].map(|t| text(t).unwrap_or_default());
tracing::info!(title, description, max_length, "text entry");
xasync::pending_with(block, (&raw const TEXT).cast(), move || {
match ask(&title, &description, &default, max_length) {
Some(typed) => {
tracing::info!(length = typed.chars().count(), "text entry: done");
let mut bytes = limit(&typed, max_length).into_bytes();
bytes.push(0);
Ok(bytes)
}
None => {
tracing::info!("text entry: cancelled");
Err(E_ABORT)
}
}
})
}
/// Bytes of the result, its NUL included.
extern "system" fn text_entry_size(_: This, block: *mut AsyncBlock, out: *mut u32) -> HRESULT {
let mut size = 0;
let hr = xasync::XAsyncGetResultSize(block, &mut size);
if hr < 0 {
return hr;
}
put(out, size as u32)
}
extern "system" fn text_entry_result(
_: This,
block: *mut AsyncBlock,
size: u32,
buffer: *mut c_char,
used: *mut u32,
) -> HRESULT {
let mut written = 0;
let identity = (&raw const TEXT).cast();
let hr = xasync::XAsyncGetResult(block, identity, size as usize, buffer.cast(), &mut written);
if hr < 0 || used.is_null() {
return hr;
}
put(used, written as u32)
}
/// At most `max` characters (0: no limit).
fn limit(typed: &str, max: u32) -> String {
match max {
0 => typed.to_owned(),
max => typed.chars().take(max as usize).collect(),
}
}
/// Asks the user in a modal host dialog; `None` if dismissed.
#[cfg(not(test))]
fn ask(title: &str, description: &str, default: &str, max: u32) -> Option<String> {
dialog::ask(title, description, default, max)
}
/// Tests answer for the user: "typed" for a title starting with "Type",
/// cancelled otherwise.
#[cfg(test)]
fn ask(title: &str, _: &str, default: &str, _: u32) -> Option<String> {
title.starts_with("Type").then(|| format!("{default}typed"))
}
mod dialog {
use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM};
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::SetFocus;
use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, DLGTEMPLATE};
const EDIT: i32 = 100;
// Edit control messages (the controls headers).
const EM_SETSEL: u32 = 0xb1;
const EM_LIMITTEXT: u32 = 0xc5;
/// The dialog's state, behind its user data while it runs.
struct Entry {
max: u32,
typed: Option<String>,
}
/// The description, an edit box with the default text, OK and Cancel,
/// from an in-memory template (dialog units, the system font); Enter
/// accepts, Esc cancels.
#[allow(dead_code)] // unused in test builds
pub(super) fn ask(title: &str, description: &str, default: &str, max: u32) -> Option<String> {
let mut t: Vec<u16> = Vec::new();
fn dword(t: &mut Vec<u16>, v: u32) {
t.extend([v as u16, (v >> 16) as u16]);
}
fn text(t: &mut Vec<u16>, s: &str) {
t.extend(s.encode_utf16().filter(|&c| c != 0));
t.push(0);
}
let style = wm::WS_POPUP | wm::WS_CAPTION | wm::WS_SYSMENU;
let flags = (wm::DS_MODALFRAME | wm::DS_CENTER | wm::DS_SETFOREGROUND) as u32;
dword(&mut t, style | flags);
dword(&mut t, wm::WS_EX_TOPMOST);
t.extend([4, 0, 0, 240, 62, 0, 0]); // items, x, y, cx, cy, no menu, default class
text(&mut t, title);
let mut item = |style: u32, rect: [u16; 4], id: u16, class: u16, caption: &str| {
if t.len() % 2 == 1 {
t.push(0); // items start on a DWORD
}
dword(&mut t, wm::WS_CHILD | wm::WS_VISIBLE | style);
dword(&mut t, 0);
t.extend(rect);
t.extend([id, 0xffff, class]);
text(&mut t, caption);
t.push(0); // no creation data
};
let (button, edit, label) = (0x80, 0x81, 0x82);
let tab = wm::WS_TABSTOP;
item(0, [7, 7, 226, 10], 0xffff, label, description);
let edit_style = wm::WS_BORDER | tab | wm::ES_AUTOHSCROLL as u32;
item(edit_style, [7, 20, 226, 12], EDIT as u16, edit, default);
let ok = wm::BS_DEFPUSHBUTTON as u32 | tab;
item(ok, [129, 40, 50, 14], wm::IDOK as u16, button, "OK");
let cancel = wm::BS_PUSHBUTTON as u32 | tab;
item(cancel, [183, 40, 50, 14], wm::IDCANCEL as u16, button, "Cancel");
// The template must start on a DWORD.
let template: Vec<u32> = t
.chunks(2)
.map(|c| u32::from(c[0]) | u32::from(c.get(1).copied().unwrap_or(0)) << 16)
.collect();
let mut entry = Entry { max, typed: None };
// SAFETY: a complete template and our dialog procedure; `entry`
// outlives the modal dialog.
unsafe {
wm::DialogBoxIndirectParamW(
GetModuleHandleW(std::ptr::null()),
template.as_ptr().cast::<DLGTEMPLATE>(),
std::ptr::null_mut(),
Some(procedure),
(&raw mut entry) as LPARAM,
);
}
entry.typed
}
extern "system" fn procedure(dialog: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> isize {
// SAFETY: our dialog; its user data is the `Entry` from `ask`,
// stored at WM_INITDIALOG.
unsafe {
let edit = wm::GetDlgItem(dialog, EDIT);
match message {
wm::WM_INITDIALOG => {
wm::SetWindowLongPtrW(dialog, wm::GWLP_USERDATA, lparam);
let entry = &*(lparam as *const Entry);
wm::SendMessageW(edit, EM_LIMITTEXT, entry.max as WPARAM, 0);
wm::SendMessageW(edit, EM_SETSEL, 0, -1);
SetFocus(edit);
0 // focus set here
}
wm::WM_COMMAND => {
let entry = &mut *(wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA) as *mut Entry);
match (wparam & 0xffff) as i32 {
wm::IDOK => {
let mut buffer = vec![0u16; wm::GetWindowTextLengthW(edit) as usize + 1];
let n = wm::GetWindowTextW(edit, buffer.as_mut_ptr(), buffer.len() as i32);
entry.typed = Some(String::from_utf16_lossy(&buffer[..n.max(0) as usize]));
wm::EndDialog(dialog, 1);
}
wm::IDCANCEL => {
wm::EndDialog(dialog, 0);
}
_ => return 0,
}
1
}
_ => 0,
}
}
}
}
static VTABLE: Methods<20> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
missing::<3> as *const (), // 0x18 message dialog
missing::<4> as *const (), // 0x20
missing::<5> as *const (), // 0x28 send invite
missing::<6> as *const (), // 0x30
profile_card_async as *const (), // 0x38
profile_card_result as *const (), // 0x40
missing::<9> as *const (), // 0x48 achievements
missing::<10> as *const (), // 0x50
missing::<11> as *const (), // 0x58 player picker
missing::<12> as *const (), // 0x60
missing::<13> as *const (), // 0x68
missing::<14> as *const (), // 0x70 error dialog
missing::<15> as *const (), // 0x78
missing::<16> as *const (), // 0x80 notification position
text_entry_async as *const (), // 0x88
text_entry_size as *const (), // 0x90
text_entry_result as *const (), // 0x98
]);
#[cfg(test)]
mod tests {
use super::*;
use crate::modules::xgameruntime::method;
fn block() -> AsyncBlock {
AsyncBlock {
queue: std::ptr::null(),
context: std::ptr::null_mut(),
callback: None,
internal: [0; 4],
}
}
#[test]
fn dialogs_end_with_what_was_typed() {
let this: This = &OBJECT;
let mut b = block();
type Card = extern "system" fn(This, *mut AsyncBlock, *const c_void, u64) -> HRESULT;
type Done = extern "system" fn(This, *mut AsyncBlock) -> HRESULT;
assert_eq!(
method::<Card>(&OBJECT, 0x38)(this, &mut b, std::ptr::null(), 1),
S_OK
);
assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK);
assert_eq!(method::<Done>(&OBJECT, 0x40)(this, &mut b), S_OK);
type Entry = extern "system" fn(
This,
*mut AsyncBlock,
*const c_char,
*const c_char,
*const c_char,
u32,
u32,
) -> HRESULT;
type Size = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT;
type Result_ = extern "system" fn(This, *mut AsyncBlock, u32, *mut c_char, *mut u32) -> HRESULT;
let null = std::ptr::null();
let entry = method::<Entry>(&OBJECT, 0x88);
// Dismissed: cancelled.
let mut b = block();
assert_eq!(entry(this, &mut b, c"Name".as_ptr(), null, null, 0, 16), S_OK);
assert_eq!(xasync::XAsyncGetStatus(&mut b, true), E_ABORT);
let mut size = 0;
assert_eq!(method::<Size>(&OBJECT, 0x90)(this, &mut b, &mut size), E_ABORT);
// Typed: the text, cut to the limit, with its NUL.
let mut b = block();
let default = c"abc".as_ptr();
assert_eq!(entry(this, &mut b, c"Type".as_ptr(), null, default, 0, 6), S_OK);
assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK);
assert_eq!(method::<Size>(&OBJECT, 0x90)(this, &mut b, &mut size), S_OK);
assert_eq!(size, 7);
let mut out = [0 as c_char; 7];
let mut used = 0;
let result = method::<Result_>(&OBJECT, 0x98);
assert_eq!(result(this, &mut b, 7, out.as_mut_ptr(), &mut used), S_OK);
assert_eq!((text(out.as_ptr()).as_deref(), used), (Some("abctyp"), 7));
assert_eq!(limit("\u{e9}t\u{e9}s", 3), "\u{e9}t\u{e9}");
}
}
+634 -35
View File
@@ -8,14 +8,18 @@
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::alloc::{Layout, alloc, dealloc};
use std::collections::{BTreeMap, HashMap};
use std::ffi::c_void;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, LazyLock, Mutex, MutexGuard};
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE};
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,
CreateFileMappingW, MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER,
MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE,
MEM_RESERVE_PLACEHOLDER, MEMORY_BASIC_INFORMATION, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile3,
MemExtendedParameterAddressRequirements, PAGE_NOACCESS, PAGE_READWRITE, SEC_RESERVE,
UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQueryEx,
};
use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
@@ -24,11 +28,6 @@ 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);
@@ -39,6 +38,7 @@ static TRANSFERRED: AtomicUsize = AtomicUsize::new(0);
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;
const PAGES_64K: u32 = PAGES_2M | PAGES_64K_BIT;
/// 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.
@@ -47,16 +47,23 @@ const HOST_PROTECTION: u32 = 0x1ff;
const GRAPHICS: u64 = 3;
/// XMem flag bit of 32-bit graphics memory.
const ADDRESS_32BIT: u64 = 4;
/// The host's write watching (not in windows-sys' memory module).
const MEM_WRITE_WATCH: u32 = 0x20_0000;
/// 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 {
/// The addresses XMem `flags` allow, first and last: the low 4 GiB for
/// 32-bit memory; else from 4 GiB (kept for 32-bit requests, which the
/// title's big pools would otherwise crowd out) up to 46 down to 40 bits
/// from the field at bit 12, or 40 bits without one: the console keeps
/// title memory there, and its ray-tracing structures must be (Grand Theft
/// Auto VI's BVH builder refuses one above; the title asks for its GPU heap
/// with no field). Decision 0001.
fn address_range(flags: u64) -> (usize, usize) {
let bits = match (flags & ADDRESS_32BIT, flags >> 12 & 7) {
(0, 0) => return 0,
(0, 0) => 40,
(0, field) => 47 - field,
_ => 32,
_ => return (0, u32::MAX as usize),
};
(1 << bits) - 1
(1 << 32, (1 << bits) - 1)
}
pub extern "system" fn XMemVirtualAlloc(
@@ -66,42 +73,78 @@ pub extern "system" fn XMemVirtualAlloc(
flags: u64,
protect: u32,
) -> *mut c_void {
let (lowest, highest) = address_range(flags);
let mut requirements = MEM_ADDRESS_REQUIREMENTS {
HighestEndingAddress: highest_address(flags) as *mut c_void,
LowestStartingAddress: lowest as *mut c_void,
HighestEndingAddress: highest 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 {
let mut protect = match protect & HOST_PROTECTION {
0 => PAGE_NOACCESS,
p => p,
};
// A reservation of 64 KiB pages takes physical pages later
// (`XMemMapPhysicalPages`); on the host only a placeholder can.
// shortcut: committing part of such a reservation later would fail
// (Grand Theft Auto VI's 23 calls never do); replace that part of the
// placeholder then.
let placeholder = kind & PAGES_64K == PAGES_64K && kind & MEM_COMMIT == 0;
if placeholder {
if kind & MEM_REPLACE_PLACEHOLDER != 0 {
// Part of a placeholder the title split: it stays one.
return base;
}
protect = PAGE_NOACCESS;
}
let mut kind = kind & !(PAGES_2M | PAGES_64K_BIT);
if placeholder {
kind |= MEM_RESERVE | MEM_RESERVE_PLACEHOLDER;
}
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);
let constrained = base.is_null();
if constrained {
kind |= MEM_RESERVE;
// The GPU side copies only the pages the title wrote since its last
// copy (`victory_gpu`, decision 0007); placeholders cannot be
// watched (their physical-page views are copied whole).
if kind & MEM_RESERVE_PLACEHOLDER == 0 {
kind |= MEM_WRITE_WATCH;
}
}
// SAFETY: the title's own arguments, cleaned of console bits; the
// parameter points at `requirements`, which outlives the call.
unsafe {
let at = unsafe {
VirtualAlloc2(
GetCurrentProcess(),
base,
size,
kind,
protect,
if constrained { &mut parameter } else { std::ptr::null_mut() },
if constrained {
&mut parameter
} else {
std::ptr::null_mut()
},
constrained.into(),
)
};
if base.is_null() {
tracing::debug!(
size,
kind = format_args!("{kind:#x}"),
flags = format_args!("{flags:#x}"),
at = format_args!("{at:p}"),
"XMemVirtualAlloc"
);
}
at
}
/// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the
@@ -115,8 +158,9 @@ pub struct BasicInformation {
}
// 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.
// all of it is GPU-reachable here (Grand Theft Auto VI's BVH builder, the
// only caller, wants graphics memory); 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,
@@ -130,7 +174,11 @@ pub extern "system" fn XMemVirtualQuery(
return 0;
}
let info = &mut *out;
info.flags = if info.host.State == MEM_COMMIT { GRAPHICS } else { 0 };
info.flags = if info.host.State == MEM_COMMIT {
GRAPHICS
} else {
0
};
info.tag_code = 0;
info.tag = [0; 4];
}
@@ -151,10 +199,66 @@ fn layout(size: usize, attributes: u64) -> Option<Layout> {
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.
type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void;
type FreeRoutine = extern "system" fn(*mut c_void, u64);
/// The allocation and free routines the title's exe exports as
/// `__XMemAllocationHooks__` (Grand Theft Auto VI does): `XMemAlloc` and
/// `XMemFree` call them, for the title's own calls and its middleware's;
/// the `…Default` exports do not.
fn hooks() -> [usize; 2] {
static AT: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
let at = match AT.get() {
Some(&at) => at,
// Looked up once the title is mapped, which is before it runs.
None => match crate::runtime::main_image() {
Some(base) => *AT.get_or_init(|| {
use windows_sys::Win32::System::LibraryLoader::GetProcAddress;
// SAFETY: a mapped image and a NUL-terminated name.
let at = unsafe {
GetProcAddress(base as _, c"__XMemAllocationHooks__".as_ptr().cast())
}
.map_or(0, |f| f as usize);
tracing::info!(found = at != 0, "xmem allocation hooks");
at
}),
None => 0,
},
};
if at == 0 {
return [0; 2];
}
// SAFETY: the export is two routine pointers.
unsafe { (at as *const [usize; 2]).read() }
}
/// The title's general allocator, for middleware too: its hook if it has
/// one, else [`XMemAllocDefault`].
pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void {
match hooks()[0] {
0 => XMemAllocDefault(size, attributes),
hook => {
// SAFETY: the title's own routine of this type.
let alloc: AllocRoutine = unsafe { std::mem::transmute(hook) };
alloc(size, attributes)
}
}
}
/// See [`XMemAlloc`].
pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) {
match hooks()[1] {
0 => XMemFreeDefault(address, attributes),
hook => {
// SAFETY: the title's own routine of this type.
let free: FreeRoutine = unsafe { std::mem::transmute(hook) };
free(address, attributes)
}
}
}
/// The system allocator behind [`XMemAlloc`].
pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_void {
if attributes & ALLOC_32BIT != 0 {
return XMemVirtualAlloc(
std::ptr::null_mut(),
@@ -167,6 +271,10 @@ pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void {
let Some(layout) = layout(size, attributes) else {
return std::ptr::null_mut();
};
// shortcut: the host heap's addresses lie above 2^40, unlike the
// console's; nothing seen builds ray-tracing structures in this memory
// (Grand Theft Auto VI uses its GPU heap). Sub-allocate from a
// reservation below 2^40 if one does.
// SAFETY: the layout has a non-zero size.
let block = unsafe { alloc(layout) };
if block.is_null() {
@@ -183,8 +291,8 @@ pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void {
}
}
/// Frees what [`XMemAlloc`] returned, given the same attributes.
pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) {
/// Frees what [`XMemAllocDefault`] returned, given the same attributes.
pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) {
if address.is_null() {
return;
}
@@ -204,6 +312,383 @@ pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) {
}
}
/// A retail console has no tools memory.
pub extern "system" fn XMemIsToolsMemAvailable() -> BOOL {
0
}
// Physical pages: on the console, 64 KiB frames a title maps into its own
// reservations, at more than one address if it likes. Here each allocation
// is a pagefile-backed section, its pages are 64 KiB slices of it, and a
// mapping is a view of consecutive slices in place of a host placeholder.
const PAGE: usize = 64 << 10;
struct Section(HANDLE);
// SAFETY: a section handle may be used from any thread.
unsafe impl Send for Section {}
// SAFETY: as above.
unsafe impl Sync for Section {}
impl Drop for Section {
fn drop(&mut self) {
// SAFETY: our handle; views keep the section alive on their own.
unsafe { CloseHandle(self.0) };
}
}
/// Where a page lives, or what a view starts with: a section and a page
/// index in it.
#[derive(Clone)]
struct Slice {
section: Arc<Section>,
index: usize,
}
#[derive(Default)]
struct Physical {
next_page: usize,
pages: HashMap<usize, Slice>,
/// Mapped views by address: their length and what they show.
views: BTreeMap<usize, (usize, Slice)>,
}
static PHYSICAL: LazyLock<Mutex<Physical>> = LazyLock::new(|| {
Mutex::new(Physical {
// Page numbers are opaque to titles; 0 stays unused.
next_page: 0x10_0000,
..Default::default()
})
});
fn physical() -> MutexGuard<'static, Physical> {
PHYSICAL.lock().unwrap_or_else(|e| e.into_inner())
}
/// `count` is in and out (pages wanted, pages given); all or nothing here.
pub extern "system" fn XMemAllocatePhysicalPages(
flags: u64,
count: *mut usize,
pages: *mut usize,
) -> BOOL {
if count.is_null() || pages.is_null() {
return 0;
}
// SAFETY: checked non-null.
let n = unsafe { *count };
let Some(size) = n.checked_mul(PAGE).filter(|&s| s > 0) else {
return 0;
};
// A pagefile-backed section of `size` bytes, its pages committed when
// first mapped or written (`commit`): Grand Theft Auto VI asks for 6.1
// GiB at once, which a busy host often cannot commit (error 1450).
// SAFETY: plain section creation.
let handle = unsafe {
CreateFileMappingW(
INVALID_HANDLE_VALUE,
std::ptr::null(),
PAGE_READWRITE | SEC_RESERVE,
(size as u64 >> 32) as u32,
size as u32,
std::ptr::null(),
)
};
if handle.is_null() {
let error = std::io::Error::last_os_error();
tracing::warn!(n, %error, "XMemAllocatePhysicalPages failed");
// SAFETY: checked non-null.
unsafe { count.write(0) };
return 0;
}
tracing::debug!(
n,
flags = format_args!("{flags:#x}"),
"XMemAllocatePhysicalPages"
);
let section = Arc::new(Section(handle));
let mut physical = physical();
let first = physical.next_page;
physical.next_page += n * FRAMES;
for index in 0..n {
let slice = Slice {
section: section.clone(),
index,
};
let number = first + index * FRAMES;
physical.pages.insert(number, slice);
// SAFETY: the title passes room for `n` page numbers.
unsafe { pages.add(index).write(number) };
}
1
}
/// Page numbers count 4 KiB frames, so a 64 KiB page's is a multiple of
/// 16: Grand Theft Auto VI keeps them as 21-bit `number >> 4` and rebuilds
/// them with `<< 4` (128 GiB of pages at most).
const FRAMES: usize = PAGE >> 12;
/// Pages still mapped stay readable through their views until unmapped.
pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> BOOL {
if pages.is_null() {
return 0;
}
let mut physical = physical();
for i in 0..n {
// SAFETY: the title passes `n` page numbers.
physical.pages.remove(&unsafe { *pages.add(i) });
}
1
}
/// Copies `data` into physical pages, from `offset` bytes into the first,
/// whether or not they are mapped anywhere (DirectStorage destinations).
/// False if a page is unknown or the host fails.
pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> bool {
use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile};
let mut done = 0;
while done < data.len() {
let (page, within) = ((offset + done) / PAGE, (offset + done) % PAGE);
let Some(slice) = pages
.get(page)
.and_then(|p| physical().pages.get(p).cloned())
else {
return false;
};
let at = (slice.index * PAGE) as u64;
// SAFETY: one page of a section we own, mapped for the copy only.
let view = unsafe {
MapViewOfFile(
slice.section.0,
FILE_MAP_WRITE,
(at >> 32) as u32,
at as u32,
PAGE,
)
};
if view.Value.is_null() {
return false;
}
if !commit(view.Value as usize, PAGE) {
// SAFETY: our view.
unsafe { UnmapViewOfFile(view) };
return false;
}
let n = (PAGE - within).min(data.len() - done);
// SAFETY: the view holds `PAGE` bytes; `within + n <= PAGE`.
unsafe {
view.Value
.cast::<u8>()
.add(within)
.copy_from_nonoverlapping(data[done..].as_ptr(), n);
UnmapViewOfFile(view);
}
done += n;
}
true
}
/// Maps `n` pages at `address`, in place of what is mapped there; null
/// `pages` unmaps. Returns `address`, or null if a page or the host fails.
pub extern "system" fn XMemMapPhysicalPages(
address: *mut c_void,
n: usize,
pages: *const usize,
) -> *mut c_void {
let base = address as usize;
let mut physical = physical();
unmap(&mut physical, base, n * PAGE);
if pages.is_null() {
return address;
}
// SAFETY: the title passes `n` page numbers.
let pages = unsafe { std::slice::from_raw_parts(pages, n) };
let mut i = 0;
while i < n {
let Some(first) = physical.pages.get(&pages[i]).cloned() else {
tracing::warn!(page = pages[i], "XMemMapPhysicalPages: unknown page");
return std::ptr::null_mut();
};
// One view per run of consecutive slices of one section.
let run = 1 + pages[i + 1..]
.iter()
.zip(1..)
.take_while(|&(page, k)| {
physical.pages.get(page).is_some_and(|s| {
Arc::ptr_eq(&s.section, &first.section) && s.index == first.index + k
})
})
.count();
if !map(&mut physical, base + i * PAGE, run * PAGE, first) {
return std::ptr::null_mut();
}
i += run;
}
address
}
/// One page at each address; null `pages`, or a page number 0, unmaps
/// (Grand Theft Auto VI passes 0 for addresses to clear).
pub extern "system" fn XMemMapPhysicalPagesScatter(
addresses: *const *mut c_void,
n: usize,
pages: *const usize,
) -> BOOL {
if addresses.is_null() {
return 0;
}
for i in 0..n {
// SAFETY: the title passes `n` addresses and, unless null, `n` pages.
let (address, page) = unsafe {
(
*addresses.add(i),
if pages.is_null() || *pages.add(i) == 0 {
std::ptr::null()
} else {
pages.add(i)
},
)
};
if XMemMapPhysicalPages(address, 1, page).is_null() {
return 0;
}
}
1
}
/// Maps the physical pages shown at `[from, from + len)` at `to` as well,
/// in place of what `to` shows; `from` 0 unmaps. The GPU's page-mapping
/// copies (`victory_gpu`, queue `CopyPageMappingsBatchX`): Grand Theft Auto
/// VI maps pages into a pool view, then has the GPU map them into its tiled
/// heap. Page by page; false if a source page is not mapped physical memory.
pub fn map_alias(to: u64, from: u64, len: u64) -> bool {
let (to, from, len) = (to as usize, from as usize, len as usize);
let mut physical = physical();
unmap(&mut physical, to, len);
for k in (0..len).step_by(PAGE) {
if from == 0 {
break;
}
let at = from + k;
let Some(slice) = physical
.views
.range(..=at)
.next_back()
.filter(|(base, (size, _))| at < *base + size)
.map(|(base, (_, s))| Slice {
index: s.index + (at - base) / PAGE,
section: s.section.clone(),
})
else {
return false;
};
if !map(&mut physical, to + k, PAGE, slice) {
return false;
}
}
true
}
/// Maps `slice` and the slices after it over `[base, base + len)`, which
/// must lie in one placeholder.
fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
// SAFETY: splits the placeholder around the range (failing harmlessly
// when the range is the whole placeholder), then maps the section
// there; both act only on placeholders.
let view = unsafe {
VirtualFree(
base as *mut c_void,
len,
MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
);
MapViewOfFile3(
slice.section.0,
GetCurrentProcess(),
base as *const c_void,
(slice.index * PAGE) as u64,
len,
MEM_REPLACE_PLACEHOLDER,
PAGE_READWRITE,
std::ptr::null_mut(),
0,
)
};
if view.Value as usize != base {
tracing::warn!(
address = format_args!("{base:#x}"),
len,
error = %std::io::Error::last_os_error(),
"mapping physical pages failed (not a placeholder?)"
);
return false;
}
if !commit(base, len) {
// SAFETY: the view just mapped, back to a placeholder.
unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) };
return false;
}
// New contents, read-write: the GPU side's copies no longer guard it.
victory_gpu::title_memory_remapped(base, len);
physical.views.insert(base, (len, slice));
true
}
/// Commits the section pages a view shows (once per page, whichever view).
fn commit(base: usize, len: usize) -> bool {
// SAFETY: `[base, base + len)` is a view of a reserved section.
let done =
!unsafe { VirtualAlloc(base as *const c_void, len, MEM_COMMIT, PAGE_READWRITE) }.is_null();
if !done {
tracing::warn!(
len,
error = %std::io::Error::last_os_error(),
"committing physical pages failed"
);
}
done
}
/// Returns `[base, base + len)` to placeholders; views reaching past it
/// are mapped again outside it.
fn unmap(physical: &mut Physical, base: usize, len: usize) {
let end = base + len;
// Views do not overlap: the one holding `base`, then those starting
// inside (the GPU's page mappings make one view per page).
let first = physical
.views
.range(..=base)
.next_back()
.filter(|(at, (size, _))| *at + size > base)
.map(|(at, _)| *at);
let hit: Vec<usize> = first
.into_iter()
.chain(physical.views.range(base + 1..end).map(|(at, _)| *at))
.collect();
for at in hit {
let Some((size, slice)) = physical.views.remove(&at) else {
continue;
};
victory_gpu::title_memory_remapped(at, size);
// SAFETY: a view we mapped; it becomes a placeholder again.
unsafe {
UnmapViewOfFile2(
GetCurrentProcess(),
MEMORY_MAPPED_VIEW_ADDRESS {
Value: at as *mut c_void,
},
MEM_PRESERVE_PLACEHOLDER,
)
};
if at < base {
map(physical, at, base - at, slice.clone());
}
if at + size > end {
let index = slice.index + (end - at) / PAGE;
map(physical, end, at + size - end, Slice { index, ..slice });
}
}
}
/// The oldest layout we know; newer titles pass other flag values (Minecraft
/// 0x20000001) and read the same leading fields.
#[repr(C)]
@@ -238,10 +723,11 @@ pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut Workin
};
// SAFETY: our own process and a sized structure.
unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) };
let (gpu_optimal, standard) = victory_gpu::console::current().title_memory();
let stats = WorkingSet {
title_limit: GPU_OPTIMAL_LIMIT + STANDARD_LIMIT - TRANSFERRED.load(Ordering::Relaxed),
title_limit: gpu_optimal + standard - TRANSFERRED.load(Ordering::Relaxed),
title_used: counters.PagefileUsage,
gpu_optimal_limit: GPU_OPTIMAL_LIMIT,
gpu_optimal_limit: gpu_optimal,
..Default::default()
};
// SAFETY: checked non-null; the title passes room for the structure.
@@ -260,10 +746,11 @@ pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL {
let Some(size) = size.checked_next_multiple_of(2 * MIB) else {
return 0;
};
let standard = victory_gpu::console::current().title_memory().1;
let moved = kind == TITLE_TO_SYSTEM
&& TRANSFERRED
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |t| {
t.checked_add(size).filter(|&t| t <= STANDARD_LIMIT)
t.checked_add(size).filter(|&t| t <= standard)
})
.is_ok();
moved.into()
@@ -276,6 +763,13 @@ pub(crate) fn module() -> HleModule {
exports: vec![
hle_export!(XMemAlloc),
hle_export!(XMemFree),
hle_export!(XMemAllocDefault),
hle_export!(XMemFreeDefault),
hle_export!(XMemIsToolsMemAvailable),
hle_export!(XMemAllocatePhysicalPages),
hle_export!(XMemFreePhysicalPages),
hle_export!(XMemMapPhysicalPages),
hle_export!(XMemMapPhysicalPagesScatter),
hle_export!(XMemVirtualAlloc),
hle_export!(XMemVirtualQuery),
hle_export!(XMemGetWorkingSetStatistics),
@@ -330,9 +824,36 @@ mod tests {
assert_eq!(info.host.State, MEM_COMMIT);
assert_eq!(info.host.Protect, PAGE_READWRITE);
assert_eq!(info.flags & GRAPHICS, GRAPHICS);
// Write-watched, for the GPU side's copies.
let (mut found, mut count, mut granularity) = ([0usize; 4], 4, 0);
// SAFETY: room for `count` addresses.
let watched = unsafe {
windows_sys::Win32::System::Memory::GetWriteWatch(
0,
p,
4 * MIB,
found.as_mut_ptr().cast(),
&mut count,
&mut granularity,
)
};
assert_eq!(watched, 0);
// SAFETY: our own reservation.
assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
assert_eq!(query(p).flags, 0);
// No address field: above the 32-bit range and below 2^40, where
// the console keeps it.
let p = XMemVirtualAlloc(
std::ptr::null_mut(),
16 << 30,
MEM_RESERVE,
GRAPHICS,
PAGE_NOACCESS,
);
assert!(!p.is_null() && (p as usize) >= 1 << 32, "{p:p}");
assert!((p as usize) + (16 << 30) <= 1 << 40, "{p:p}");
// SAFETY: our own reservation.
assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
}
#[test]
@@ -342,7 +863,8 @@ mod tests {
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 standard = victory_gpu::console::current().title_memory().1;
assert_eq!(XMemTransferMemory(0, standard), 0, "over budget");
let mut after = WorkingSet::default();
XMemGetWorkingSetStatistics(0x2000_0001, &mut after);
assert_eq!(before.title_limit - after.title_limit, 128 * MIB);
@@ -354,4 +876,81 @@ mod tests {
assert_eq!(size_of::<BasicInformation>(), 0x40);
assert_eq!(std::mem::offset_of!(WorkingSet, gpu_optimal_limit), 0x28);
}
#[test]
fn physical_pages_map_alias_and_unmap() {
let mut pages = [0usize; 3];
let mut n = 3;
assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1);
assert_eq!(n, 3);
// Packed into 21 bits as `number >> 4`, as the title keeps them.
for p in pages {
assert_eq!((p >> 4 & 0x1f_ffff) << 4, p);
}
// Reservations of 64 KiB pages, as titles make them for mapping.
let reserve = || {
XMemVirtualAlloc(
std::ptr::null_mut(),
3 * PAGE,
MEM_RESERVE | PAGES_64K,
0,
PAGE_READWRITE,
)
};
let (a, b) = (reserve(), reserve());
assert!(!a.is_null() && !b.is_null());
let at = |p: *mut c_void, page: usize| p.wrapping_byte_add(page * PAGE);
assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
// The same page at a second address shows the same bytes.
assert_eq!(
XMemMapPhysicalPages(at(b, 1), 1, pages[2..].as_ptr()),
at(b, 1)
);
// SAFETY: both pages are mapped read-write.
unsafe {
at(a, 2).cast::<u8>().write(7);
assert_eq!(at(b, 1).cast::<u8>().read(), 7);
a.cast::<u8>().write(1);
}
// Writes into pages (DirectStorage's) show through their views.
assert!(write_physical(&pages[2..], 1, &[9]));
// SAFETY: mapped read-write.
assert_eq!(unsafe { at(b, 1).cast::<u8>().add(1).read() }, 9);
// Unmapping the middle page keeps its neighbours.
assert_eq!(
XMemMapPhysicalPages(at(a, 1), 1, std::ptr::null()),
at(a, 1)
);
assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE);
assert_eq!(query(a).host.State, MEM_COMMIT);
assert_eq!(query(at(a, 2)).host.State, MEM_COMMIT);
// SAFETY: still mapped.
assert_eq!(unsafe { at(a, 2).cast::<u8>().read() }, 7);
// A scattered page lands in the hole.
let addresses = [at(a, 1)];
assert_eq!(
XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, pages.as_ptr()),
1
);
// SAFETY: page 0 is now mapped at both `a` and `a + PAGE`.
assert_eq!(unsafe { at(a, 1).cast::<u8>().read() }, 1);
// Page number 0 unmaps.
assert_eq!(
XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, [0usize].as_ptr()),
1
);
assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE);
// The GPU's page-mapping copy: what `a + 2 pages` shows, at `b`.
assert!(map_alias(b as u64, at(a, 2) as u64, PAGE as u64));
// SAFETY: mapped read-write.
assert_eq!(unsafe { b.cast::<u8>().read() }, 7);
assert!(map_alias(b as u64, 0, PAGE as u64));
assert_eq!(query(b).host.State, MEM_RESERVE);
assert!(!map_alias(b as u64, at(a, 1) as u64, PAGE as u64));
assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
assert_eq!(XMemIsToolsMemAvailable(), 0);
}
}
@@ -0,0 +1,210 @@
//! XNetworking as an offline console answers it: the network stack is up
//! (titles wait for that before anything else) but reaches nothing, the
//! connectivity hint never changes, and the title's security allow list,
//! which comes from the service, cannot be fetched.
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xasync::{self, AsyncBlock};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, add_ref, missing, put, text, token,
};
pub const PROVIDER: Guid = Guid::new(
0x37e5_6907,
0x2f10,
0x41e8,
[0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a],
);
/// As Grand Theft Auto VI (2026) asks for it; the slots it calls (0x18-0x88)
/// take the same arguments as under the provider's own id (older titles).
pub const IID_2026: Guid = Guid::new(
0xbf23_46b2,
0x39af,
0x4658,
[0xb5, 0xea, 0x44, 0x71, 0x3c, 0x7e, 0x83, 0xb3],
);
pub static OBJECT: Object = Object::new("networking", &VTABLE);
pub const INTERFACES: &[Interface] =
&[(PROVIDER, PROVIDER, &OBJECT), (PROVIDER, IID_2026, &OBJECT)];
/// `HRESULT_FROM_WIN32(ERROR_NETWORK_UNREACHABLE)`: what needs the service.
pub const UNREACHABLE: HRESULT = 0x8007_04CF_u32 as i32;
/// The documented default for the preferred local UDP multiplayer port.
const UDP_PORT: u16 = 3074;
/// The connectivity hint: level, cost, interface type, then four flags.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConnectivityHint {
pub level: u32,
pub cost: u32,
pub interface_type: u32,
pub initialized: bool,
pub approaching_data_limit: bool,
pub over_data_limit: bool,
pub roaming: bool,
}
/// Initialized, no connectivity (level 1), cost unknown (0).
const OFFLINE: ConnectivityHint = ConnectivityHint {
level: 1,
cost: 0,
interface_type: 0,
initialized: true,
approaching_data_limit: false,
over_data_limit: false,
roaming: false,
};
type This = *const Object;
extern "system" fn udp_port(_: This, out: *mut u16) -> HRESULT {
put(out, UDP_PORT)
}
/// Tells our port queries apart from other calls on the same block.
static PORT: u8 = 0;
extern "system" fn udp_port_async(_: This, block: *mut AsyncBlock) -> HRESULT {
xasync::finished_with(block, (&raw const PORT).cast(), Ok(xasync::bytes(UDP_PORT)))
}
extern "system" fn udp_port_result(_: This, block: *mut AsyncBlock, out: *mut u16) -> HRESULT {
xasync::result(block, (&raw const PORT).cast(), out)
}
static SECURITY: u8 = 0;
/// The allow list comes from the service: unreachable offline.
extern "system" fn security_info_async(
_: This,
url: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
tracing::debug!(
url = text(url).unwrap_or_default(),
"security information: offline"
);
xasync::finished(block, (&raw const SECURITY).cast(), UNREACHABLE)
}
extern "system" fn security_info_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT {
xasync::XAsyncGetResultSize(block, out)
}
extern "system" fn security_info_result(
_: This,
block: *mut AsyncBlock,
size: usize,
used: *mut usize,
buffer: *mut u8,
_info: *mut *const c_void,
) -> HRESULT {
xasync::XAsyncGetResult(
block,
(&raw const SECURITY).cast(),
size,
buffer.cast(),
used,
)
}
/// No security information can exist offline, so no certificate passes.
extern "system" fn verify_certificate(
_: This,
_request: *mut c_void,
_info: *const c_void,
) -> HRESULT {
UNREACHABLE
}
extern "system" fn connectivity_hint(_: This, out: *mut ConnectivityHint) -> HRESULT {
put(out, OFFLINE)
}
/// The hint never changes 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
}
static VTABLE: Methods<18> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
udp_port as *const (), // 0x18
udp_port_async as *const (), // 0x20
udp_port_result as *const (), // 0x28
missing::<6> as *const (), // 0x30 port changed
missing::<7> as *const (), // 0x38
security_info_async as *const (), // 0x40
security_info_size as *const (), // 0x48
security_info_result as *const (), // 0x50
missing::<11> as *const (), // 0x58 the same for UTF-16 URLs
missing::<12> as *const (), // 0x60
missing::<13> as *const (), // 0x68
verify_certificate as *const (), // 0x70
connectivity_hint as *const (), // 0x78
register as *const (), // 0x80 hint changed (never)
unregister as *const (), // 0x88
]);
#[cfg(test)]
mod tests {
use super::*;
use crate::modules::xgameruntime::{S_OK, method};
fn block() -> AsyncBlock {
AsyncBlock {
queue: std::ptr::null(),
context: std::ptr::null_mut(),
callback: None,
internal: [0; 4],
}
}
#[test]
fn offline_but_initialized() {
let this: This = &OBJECT;
type Hint = extern "system" fn(This, *mut ConnectivityHint) -> HRESULT;
let mut hint = OFFLINE;
hint.initialized = false;
assert_eq!(method::<Hint>(&OBJECT, 0x78)(this, &mut hint), S_OK);
assert!(hint.initialized && hint.level == 1);
assert_eq!(size_of::<ConnectivityHint>(), 16);
type Begin = extern "system" fn(This, *mut AsyncBlock) -> HRESULT;
type Port = extern "system" fn(This, *mut AsyncBlock, *mut u16) -> HRESULT;
let mut b = block();
assert_eq!(method::<Begin>(&OBJECT, 0x20)(this, &mut b), S_OK);
assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK);
let mut port = 0;
assert_eq!(method::<Port>(&OBJECT, 0x28)(this, &mut b, &mut port), S_OK);
assert_eq!(port, 3074);
type Url = extern "system" fn(This, *const c_char, *mut AsyncBlock) -> HRESULT;
type Size = extern "system" fn(This, *mut AsyncBlock, *mut usize) -> HRESULT;
let mut b = block();
let url = c"https://example.invalid/";
assert_eq!(
method::<Url>(&OBJECT, 0x40)(this, url.as_ptr(), &mut b),
S_OK
);
assert_eq!(xasync::XAsyncGetStatus(&mut b, true), UNREACHABLE);
let mut size = 0;
assert_eq!(
method::<Size>(&OBJECT, 0x48)(this, &mut b, &mut size),
UNREACHABLE
);
}
}
+371
View File
@@ -0,0 +1,371 @@
//! XPackage: the title's own installation, complete and launchable, with
//! every chunk ready; no other package (content, add-ons) is installed.
//! The package is the folder of the title's executable (`G:` to the title).
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use std::path::Path;
use std::sync::OnceLock;
use super::xasync::{self, AsyncBlock};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token,
};
use crate::runtime;
pub const PROVIDER: Guid = Guid::new(
0xaf40_6016,
0xe850,
0x4aa8,
[0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e],
);
/// As Grand Theft Auto VI (2026) asks for it. Its slots up to 0xd0 take the
/// arguments the public API lists in the same order; 0x110 uninstalls a
/// package, 0x128/0x130 mount one with UI, 0x138 enumerates packages.
pub const IID_2026: Guid = Guid::new(
0x0b9d_556e,
0xab70,
0x43f4,
[0xba, 0xa0, 0x99, 0x99, 0xac, 0x4c, 0xb0, 0x40],
);
pub static OBJECT: Object = Object::new("package", &VTABLE);
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID_2026, &OBJECT)];
/// The documented "could not resolve an identifier for the package".
pub const NO_PACKAGE: HRESULT = 0x8924_5208_u32 as i32;
/// Our installation's identifier: the title id in hex (titles keep it in 33
/// bytes and hand it back to us).
pub fn identifier() -> String {
format!("{:08X}", runtime::title().id)
}
fn is_ours(id: *const c_char) -> bool {
text(id).is_some_and(|id| id == identifier())
}
/// Bytes in the package folder, counted once.
fn package_bytes() -> u64 {
fn size(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() => size(&e.path()),
Ok(m) => m.len(),
Err(_) => 0,
})
.sum()
}
static BYTES: OnceLock<u64> = OnceLock::new();
*BYTES.get_or_init(|| {
let exe = runtime::main_image().and_then(runtime::image_path);
exe.as_deref().and_then(Path::parent).map_or(0, size)
})
}
type This = *const Object;
extern "system" fn current_identifier(_: This, size: usize, buffer: *mut u8) -> HRESULT {
put_string(&identifier(), size, buffer, std::ptr::null_mut())
}
extern "system" fn is_packaged(_: This) -> bool {
true
}
/// Installation monitors all watch the same finished installation, so the
/// handle is a fixed address.
static MONITOR: u8 = 0;
fn monitor() -> *const c_void {
(&raw const MONITOR).cast()
}
extern "system" fn create_monitor(
_: This,
id: *const c_char,
_selector_count: u32,
_selectors: *const c_void,
_interval_ms: u32,
_queue: *const c_void,
out: *mut *const c_void,
) -> HRESULT {
if !is_ours(id) {
return NO_PACKAGE;
}
put(out, monitor())
}
extern "system" fn close_monitor(_: This, _: *const c_void) {}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Progress {
pub total_bytes: u64,
pub installed_bytes: u64,
pub launch_bytes: u64,
pub launchable: bool,
pub completed: bool,
}
extern "system" fn progress(_: This, _: *const c_void, out: *mut Progress) {
let bytes = package_bytes();
put(
out,
Progress {
total_bytes: bytes,
installed_bytes: bytes,
launch_bytes: bytes,
launchable: true,
completed: true,
},
);
}
/// The installation is complete, so progress never changes.
extern "system" fn register_progress(
_: This,
_monitor: *const c_void,
_context: *mut c_void,
_callback: *const c_void,
out: *mut u64,
) -> HRESULT {
put(out, token())
}
/// 0: ready.
// shortcut: every selector counts as installed, including ones the
// package's layout does not have (the console answers those with an
// invalid-selector error); Grand Theft Auto VI asks only about its own
// chunks, which a full install has.
extern "system" fn find_availability(
_: This,
id: *const c_char,
_selector_count: u32,
_selectors: *const c_void,
out: *mut u32,
) -> HRESULT {
if !is_ours(id) {
return NO_PACKAGE;
}
put(out, 0)
}
extern "system" fn change_order(
_: This,
id: *const c_char,
_count: u32,
_selectors: *const c_void,
) -> HRESULT {
if is_ours(id) { S_OK } else { NO_PACKAGE }
}
static INSTALL: u8 = 0;
/// Everything is installed: done at once, the result is a monitor.
extern "system" fn install_chunks_async(
_: This,
id: *const c_char,
_count: u32,
_selectors: *const c_void,
_interval_ms: u32,
_suppress_confirmation: bool,
block: *mut AsyncBlock,
) -> HRESULT {
let result = if is_ours(id) {
Ok(xasync::bytes(monitor()))
} else {
Err(NO_PACKAGE)
};
xasync::finished_with(block, (&raw const INSTALL).cast(), result)
}
extern "system" fn install_chunks_result(
_: This,
block: *mut AsyncBlock,
out: *mut *const c_void,
) -> HRESULT {
xasync::result(block, (&raw const INSTALL).cast(), out)
}
/// Nothing to download.
extern "system" fn estimate_download(
_: This,
id: *const c_char,
_count: u32,
_selectors: *const c_void,
bytes: *mut u64,
confirm: *mut bool,
) -> HRESULT {
if !is_ours(id) {
return NO_PACKAGE;
}
if !confirm.is_null() {
// SAFETY: checked non-null.
unsafe { confirm.write(false) };
}
put(bytes, 0)
}
// shortcut: accepted but nothing is removed (the package folder is the
// user's), so the chunks stay ready; Grand Theft Auto VI's one call site
// (title+0x293b4b0, its chunk manager) would then see them still installed.
extern "system" fn uninstall_chunks(
_: This,
id: *const c_char,
_count: u32,
_selectors: *const c_void,
) -> HRESULT {
if is_ours(id) { S_OK } else { NO_PACKAGE }
}
/// Mount handles only come from mounting another package, and there is
/// none.
extern "system" fn mount_path(_: This, _: *const c_void, _: usize, _: *mut u8) -> HRESULT {
xasync::E_INVALIDARG
}
extern "system" fn close_mount(_: This, _: *const c_void) {}
/// Only other packages are uninstalled this way, and none is installed.
extern "system" fn uninstall_package(_: This, id: *const c_char) -> bool {
tracing::info!(
id = text(id).unwrap_or_default(),
"package uninstall refused"
);
false
}
static MOUNT: u8 = 0;
extern "system" fn mount_async(_: This, id: *const c_char, block: *mut AsyncBlock) -> HRESULT {
tracing::info!(
id = text(id).unwrap_or_default(),
"package mount: not installed"
);
xasync::finished(block, (&raw const MOUNT).cast(), NO_PACKAGE)
}
extern "system" fn mount_result(
_: This,
block: *mut AsyncBlock,
out: *mut *const c_void,
) -> HRESULT {
xasync::result(block, (&raw const MOUNT).cast(), out)
}
/// Titles enumerate content packages (kind 1); there are none.
// shortcut: the game kind (0) also lists nothing, not this installation;
// Grand Theft Auto VI enumerates only content (kind 1, title+0x2937bf0).
extern "system" fn enumerate(
_: This,
kind: u32,
_scope: u32,
_context: *mut c_void,
_callback: *const c_void,
) -> HRESULT {
tracing::debug!(kind, "packages enumerated: none");
S_OK
}
static VTABLE: Methods<40> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
current_identifier as *const (), // 0x18
is_packaged as *const (), // 0x20
create_monitor as *const (), // 0x28
close_monitor as *const (), // 0x30
progress as *const (), // 0x38
missing::<8> as *const (), // 0x40 update a monitor
register_progress as *const (), // 0x48
missing::<10> as *const (), // 0x50 unregister it
missing::<11> as *const (), // 0x58 user locale
find_availability as *const (), // 0x60
missing::<13> as *const (), // 0x68 enumerate chunk availability
change_order as *const (), // 0x70
missing::<15> as *const (), // 0x78 install chunks
install_chunks_async as *const (), // 0x80
install_chunks_result as *const (), // 0x88
estimate_download as *const (), // 0x90
uninstall_chunks as *const (), // 0x98
missing::<20> as *const (), // 0xa0
missing::<21> as *const (), // 0xa8
missing::<22> as *const (), // 0xb0
missing::<23> as *const (), // 0xb8 mount (deprecated)
missing::<24> as *const (), // 0xc0 mount path size
mount_path as *const (), // 0xc8
close_mount as *const (), // 0xd0
missing::<27> as *const (), // 0xd8
missing::<28> as *const (), // 0xe0 enumerate packages (older)
missing::<29> as *const (), // 0xe8
missing::<30> as *const (), // 0xf0
missing::<31> as *const (), // 0xf8
missing::<32> as *const (), // 0x100
missing::<33> as *const (), // 0x108
uninstall_package as *const (), // 0x110
missing::<35> as *const (), // 0x118
missing::<36> as *const (), // 0x120
mount_async as *const (), // 0x128
mount_result as *const (), // 0x130
enumerate as *const (), // 0x138
]);
#[cfg(test)]
mod tests {
use super::*;
use crate::modules::xgameruntime::method;
#[test]
fn the_installation_is_complete_and_alone() {
let this: This = &OBJECT;
type Id = extern "system" fn(This, usize, *mut u8) -> HRESULT;
let mut id = [0u8; 33];
assert_eq!(method::<Id>(&OBJECT, 0x18)(this, 33, id.as_mut_ptr()), S_OK);
let len = id.iter().position(|&b| b == 0).unwrap();
assert_eq!(std::str::from_utf8(&id[..len]).unwrap(), identifier());
assert!(method::<extern "system" fn(This) -> bool>(&OBJECT, 0x20)(
this
));
type Find =
extern "system" fn(This, *const c_char, u32, *const c_void, *mut u32) -> HRESULT;
let mut availability = 9;
let ours = format!("{}\0", identifier());
let find = method::<Find>(&OBJECT, 0x60);
let none = std::ptr::null();
assert_eq!(
find(this, ours.as_ptr().cast(), 0, none, &mut availability),
S_OK
);
assert_eq!(availability, 0, "ready");
assert_eq!(
find(this, c"dlc".as_ptr(), 0, none, &mut availability),
NO_PACKAGE
);
type Progress_ = extern "system" fn(This, *const c_void, *mut Progress);
let mut p = Progress {
total_bytes: 1,
installed_bytes: 0,
launch_bytes: 0,
launchable: false,
completed: false,
};
method::<Progress_>(&OBJECT, 0x38)(this, monitor(), &mut p);
assert!(p.completed && p.launchable && p.installed_bytes == p.total_bytes);
type Mount = extern "system" fn(This, *const c_char, *mut AsyncBlock) -> HRESULT;
let mut block = AsyncBlock {
queue: std::ptr::null(),
context: std::ptr::null_mut(),
callback: None,
internal: [0; 4],
};
assert_eq!(
method::<Mount>(&OBJECT, 0x128)(this, c"dlc".as_ptr(), &mut block),
S_OK
);
assert_eq!(xasync::XAsyncGetStatus(&mut block, true), NO_PACKAGE);
}
}
+479
View File
@@ -0,0 +1,479 @@
//! XStore as an offline console answers it: the game's own licence is
//! local and active (a full, owned game); the user owns no add-ons; what
//! needs the store service (catalog, consumables, purchase and update
//! pages, collection ids, update checks) fails with the documented store
//! network error.
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xasync::{self, AsyncBlock, E_ILLEGAL_METHOD_CALL};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token,
};
use super::xpackage;
use crate::runtime;
pub const PROVIDER: Guid = Guid::new(
0x0dd1_12ac,
0x7c24,
0x448c,
[0xb9, 0x2b, 0x39, 0x60, 0xfb, 0x5b, 0xd3, 0x0c],
);
/// As Grand Theft Auto VI (2026) asks for it; every slot it calls takes
/// the public API's arguments in the 2020 order.
pub const IID_2026: Guid = Guid::new(
0xb09d_803c,
0x2414,
0x4a05,
[0x82, 0xc6, 0x66, 0xdf, 0xdc, 0x9e, 0x9a, 0x44],
);
/// The same table extended by durables licensing (0x238, 0x240).
pub const DURABLES_IID: Guid = Guid::new(
0x2d42_fea5,
0xe71d,
0x4b76,
[0x97, 0xcd, 0xc5, 0x0a, 0xfb, 0xb3, 0xae, 0x5d],
);
pub static OBJECT: Object = Object::new("store", &VTABLE);
pub const INTERFACES: &[Interface] = &[
(PROVIDER, IID_2026, &OBJECT),
(PROVIDER, DURABLES_IID, &OBJECT),
];
/// The documented "failed to communicate with the store network".
pub const NETWORK_ERROR: HRESULT = 0x8924_5301_u32 as i32;
type This = *const Object;
type Handle = *const c_void;
/// Contexts and product queries hold nothing (queries are always empty),
/// so their handles are fixed addresses. A licence handle says whether it
/// is valid by which address it is.
static CONTEXT: u8 = 0;
static QUERY: u8 = 0;
static VALID: u8 = 0;
static INVALID: u8 = 0;
fn handle(of: &'static u8) -> Handle {
(of as *const u8).cast()
}
/// Identifies our calls on a block: one per result shape.
static FAILED: u8 = 0;
static QUERY_CALL: u8 = 0;
static LICENSE_CALL: u8 = 0;
static GAME_LICENSE: u8 = 0;
fn offline(block: *mut AsyncBlock, what: &str) -> HRESULT {
tracing::info!(what, "store call: offline");
xasync::finished(block, (&raw const FAILED).cast(), NETWORK_ERROR)
}
/// The result functions of calls that failed: their status.
extern "system" fn status(_: This, block: *mut AsyncBlock) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn create_context(_: This, _user: *const c_void, out: *mut Handle) -> HRESULT {
put(out, handle(&CONTEXT))
}
extern "system" fn close(_: This, _: Handle) {}
extern "system" fn associated_products_async(
_: This,
_: Handle,
_kinds: u32,
_per_page: u32,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "associated products")
}
/// The user owns no add-ons: an empty query.
extern "system" fn entitled_products_async(
_: This,
_: Handle,
_kinds: u32,
_per_page: u32,
block: *mut AsyncBlock,
) -> HRESULT {
xasync::finished_with(
block,
(&raw const QUERY_CALL).cast(),
Ok(xasync::bytes(handle(&QUERY))),
)
}
extern "system" fn query_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT {
xasync::result(block, (&raw const QUERY_CALL).cast(), out)
}
/// Empty, so the callback never runs.
extern "system" fn enumerate_products(
_: This,
_: Handle,
_: *mut c_void,
_: *const c_void,
) -> HRESULT {
S_OK
}
extern "system" fn has_more_pages(_: This, _: Handle) -> bool {
false
}
/// There is no next page to ask for.
extern "system" fn next_page_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
xasync::finished(block, (&raw const QUERY_CALL).cast(), E_ILLEGAL_METHOD_CALL)
}
fn license_for(owned: bool, block: *mut AsyncBlock) -> HRESULT {
let license = handle(if owned { &VALID } else { &INVALID });
xasync::finished_with(
block,
(&raw const LICENSE_CALL).cast(),
Ok(xasync::bytes(license)),
)
}
/// Only the game's own package is installed, so only its licence is valid.
extern "system" fn license_for_package_async(
_: This,
_: Handle,
package: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
let ours = text(package).is_some_and(|p| p == xpackage::identifier());
license_for(ours, block)
}
/// The user owns no durables: their licences are not valid.
extern "system" fn license_for_durables_async(
_: This,
_: Handle,
store_id: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
tracing::debug!(
store_id = text(store_id).unwrap_or_default(),
"durable not owned"
);
license_for(false, block)
}
extern "system" fn license_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT {
xasync::result(block, (&raw const LICENSE_CALL).cast(), out)
}
extern "system" fn is_license_valid(_: This, license: Handle) -> bool {
license == handle(&VALID)
}
/// The game licence, as the public API lays it out.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct GameLicense {
pub sku_store_id: [u8; 18],
pub is_active: bool,
pub is_trial_owned_by_this_user: bool,
pub is_disc_license: bool,
pub is_trial: bool,
pub trial_seconds_remaining: u32,
pub trial_unique_id: [u8; 64],
pub expiration: i64,
}
/// A full, active licence for the game's SKU (`<store id>/0010`, the
/// store's first SKU), not a trial, without expiry.
fn game_license() -> GameLicense {
let mut sku = [0u8; 18];
let id = format!("{}/0010", runtime::title().store_id);
let len = id.len().min(sku.len() - 1);
sku[..len].copy_from_slice(&id.as_bytes()[..len]);
GameLicense {
sku_store_id: sku,
is_active: true,
is_trial_owned_by_this_user: false,
is_disc_license: false,
is_trial: false,
trial_seconds_remaining: 0,
trial_unique_id: [0; 64],
expiration: 0,
}
}
extern "system" fn game_license_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
let license = xasync::bytes(game_license());
xasync::finished_with(block, (&raw const GAME_LICENSE).cast(), Ok(license))
}
extern "system" fn game_license_result(
_: This,
block: *mut AsyncBlock,
out: *mut GameLicense,
) -> HRESULT {
xasync::result(block, (&raw const GAME_LICENSE).cast(), out)
}
extern "system" fn consumable_balance_async(
_: This,
_: Handle,
_store_id: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "consumable balance")
}
extern "system" fn report_fulfillment_async(
_: This,
_: Handle,
_store_id: *const c_char,
_quantity: u32,
_tracking_id: *const c_void,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "consumable fulfillment")
}
/// Collections and purchase ids alike.
extern "system" fn user_id_async(
_: This,
_: Handle,
_ticket: *const c_char,
_publisher_user_id: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "user store id")
}
extern "system" fn size_status(_: This, block: *mut AsyncBlock, _out: *mut usize) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn string_status(
_: This,
block: *mut AsyncBlock,
_: usize,
_: *mut c_char,
) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn count_status(_: This, block: *mut AsyncBlock, _out: *mut u32) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn array_status(
_: This,
block: *mut AsyncBlock,
_: u32,
_: *mut c_void,
) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn purchase_ui_async(
_: This,
_: Handle,
_store_id: *const c_char,
_name: *const c_char,
_json: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "purchase page")
}
extern "system" fn product_page_ui_async(
_: This,
_: Handle,
_store_id: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "product page")
}
extern "system" fn redeem_ui_async(
_: This,
_: Handle,
_token: *const c_char,
_allowed: *const *const c_char,
_allowed_count: usize,
_disallow_csv: bool,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "redeem page")
}
extern "system" fn updates_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
offline(block, "update check")
}
/// Installing updates or packages by id alike.
extern "system" fn install_async(
_: This,
_: Handle,
_ids: *const *const c_char,
_count: usize,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "package download")
}
/// The game's own store id maps to its installation; nothing else is
/// installed.
extern "system" fn package_identifier(
_: This,
store_id: *const c_char,
size: usize,
buffer: *mut u8,
) -> HRESULT {
let title = runtime::title();
match text(store_id) {
Some(id) if !title.store_id.is_empty() && id == title.store_id => {
put_string(&xpackage::identifier(), size, buffer, std::ptr::null_mut())
}
_ => xpackage::NO_PACKAGE,
}
}
/// Licences never change offline, so these callbacks never run.
extern "system" fn register(
_: This,
_: Handle,
_queue: *const c_void,
_context: *mut c_void,
_callback: *const c_void,
out: *mut u64,
) -> HRESULT {
put(out, token())
}
extern "system" fn unregister(_: This, _: Handle, _token: u64, _wait: bool) -> bool {
true
}
static VTABLE: Methods<76> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
create_context as *const (), // 0x18
close as *const (), // 0x20
associated_products_async as *const (), // 0x28
query_result as *const (), // 0x30
missing::<7> as *const (), // 0x38 products by id
missing::<8> as *const (), // 0x40
entitled_products_async as *const (), // 0x48
query_result as *const (), // 0x50
missing::<11> as *const (), // 0x58 product for the game
missing::<12> as *const (), // 0x60
missing::<13> as *const (), // 0x68 product for a package
missing::<14> as *const (), // 0x70
enumerate_products as *const (), // 0x78
has_more_pages as *const (), // 0x80
next_page_async as *const (), // 0x88
query_result as *const (), // 0x90
close as *const (), // 0x98 a product query
license_for_package_async as *const (), // 0xa0
license_result as *const (), // 0xa8
is_license_valid as *const (), // 0xb0
close as *const (), // 0xb8 a licence
missing::<24> as *const (), // 0xc0 can acquire for store id
missing::<25> as *const (), // 0xc8
missing::<26> as *const (), // 0xd0 can acquire for package
missing::<27> as *const (), // 0xd8
game_license_async as *const (), // 0xe0
game_license_result as *const (), // 0xe8
missing::<30> as *const (), // 0xf0 add-on licences
missing::<31> as *const (), // 0xf8
missing::<32> as *const (), // 0x100
consumable_balance_async as *const (), // 0x108
status as *const (), // 0x110
report_fulfillment_async as *const (), // 0x118
missing::<36> as *const (), // 0x120
user_id_async as *const (), // 0x128 collections id
size_status as *const (), // 0x130
string_status as *const (), // 0x138
user_id_async as *const (), // 0x140 purchase id
size_status as *const (), // 0x148
string_status as *const (), // 0x150
missing::<43> as *const (), // 0x158 licence token
missing::<44> as *const (), // 0x160
missing::<45> as *const (), // 0x168
missing::<46> as *const (), // 0x170
missing::<47> as *const (), // 0x178
missing::<48> as *const (), // 0x180
purchase_ui_async as *const (), // 0x188
missing::<50> as *const (), // 0x190
missing::<51> as *const (), // 0x198 rate and review
missing::<52> as *const (), // 0x1a0
redeem_ui_async as *const (), // 0x1a8
missing::<54> as *const (), // 0x1b0
updates_async as *const (), // 0x1b8
count_status as *const (), // 0x1c0
array_status as *const (), // 0x1c8
missing::<58> as *const (), // 0x1d0 download updates
missing::<59> as *const (), // 0x1d8
install_async as *const (), // 0x1e0 updates
status as *const (), // 0x1e8
install_async as *const (), // 0x1f0 packages by store id
count_status as *const (), // 0x1f8
array_status as *const (), // 0x200
package_identifier as *const (), // 0x208
register as *const (), // 0x210 game licence changed
unregister as *const (), // 0x218
register as *const (), // 0x220 package licence lost
unregister as *const (), // 0x228
missing::<70> as *const (), // 0x230
license_for_durables_async as *const (), // 0x238
license_result as *const (), // 0x240
missing::<73> as *const (), // 0x248 associated products page
missing::<74> as *const (), // 0x250
product_page_ui_async as *const (), // 0x258
]);
#[cfg(test)]
mod tests {
use super::*;
use crate::modules::xgameruntime::method;
fn block() -> AsyncBlock {
AsyncBlock {
queue: std::ptr::null(),
context: std::ptr::null_mut(),
callback: None,
internal: [0; 4],
}
}
#[test]
fn the_game_is_licensed_and_the_store_is_offline() {
let this: This = &OBJECT;
assert_eq!(size_of::<GameLicense>(), 104);
type Begin = extern "system" fn(This, Handle, *mut AsyncBlock) -> HRESULT;
type Result = extern "system" fn(This, *mut AsyncBlock, *mut GameLicense) -> HRESULT;
let mut b = block();
assert_eq!(
method::<Begin>(&OBJECT, 0xe0)(this, handle(&CONTEXT), &mut b),
S_OK
);
assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK);
let mut license = std::mem::MaybeUninit::<GameLicense>::zeroed();
assert_eq!(
method::<Result>(&OBJECT, 0xe8)(this, &mut b, license.as_mut_ptr()),
S_OK
);
// SAFETY: written by the call.
let license = unsafe { license.assume_init() };
assert!(license.is_active && !license.is_trial);
let mut b = block();
assert_eq!(
method::<Begin>(&OBJECT, 0x1b8)(this, handle(&CONTEXT), &mut b),
S_OK
);
assert_eq!(xasync::XAsyncGetStatus(&mut b, true), NETWORK_ERROR);
type Count = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT;
assert_eq!(
method::<Count>(&OBJECT, 0x1c0)(this, &mut b, &mut 0),
NETWORK_ERROR
);
type Durable = extern "system" fn(This, Handle, *const c_char, *mut AsyncBlock) -> HRESULT;
type License = extern "system" fn(This, *mut AsyncBlock, *mut Handle) -> HRESULT;
let mut b = block();
let durable = method::<Durable>(&OBJECT, 0x238);
assert_eq!(
durable(this, handle(&CONTEXT), c"9XYZ".as_ptr(), &mut b),
S_OK
);
assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK);
let mut l = std::ptr::null();
assert_eq!(
method::<License>(&OBJECT, 0x240)(this, &mut b, &mut l),
S_OK
);
assert!(!method::<extern "system" fn(This, Handle) -> bool>(
&OBJECT, 0xb0
)(this, l));
}
}
+248 -2
View File
@@ -1,5 +1,6 @@
//! XSystem: the console's identity and sandbox, and how analytics describe
//! the device. Fixed values: one offline retail Xbox Series X.
//! the device. Fixed values: one offline retail console, the model the user
//! chose ([`victory_gpu::console`]).
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use super::xgameruntime::{
@@ -40,8 +41,18 @@ const DEVICE_ID: &str = "VkljdG9yeSBvZmZsaW5lIGRldmljZSBpZGVudGl0eSE=";
pub static OBJECT: Object = Object::new("system", &VTABLE);
pub static ANALYTICS_OBJECT: Object = Object::new("analytics", &ANALYTICS_VTABLE);
/// The interface as Grand Theft Auto VI (2026) asks for it; it calls the
/// same three slots (0x18, 0x20, 0x28) with the same arguments.
pub const IID_2026: Guid = Guid::new(
0x1861_cf2e,
0xe18b,
0x4834,
[0xa9, 0xf5, 0xb4, 0xa4, 0xe6, 0xef, 0xb4, 0xcf],
);
pub const INTERFACES: &[Interface] = &[
(PROVIDER, IID, &OBJECT),
(PROVIDER, IID_2026, &OBJECT),
(ANALYTICS, ANALYTICS, &ANALYTICS_OBJECT),
];
@@ -96,7 +107,7 @@ extern "system" fn analytics_info(_: This, out: *mut AnalyticsInfo) -> *mut Anal
os: OS,
hosting_os: OS,
family: text("Xbox"),
form: text("Xbox Series X"),
form: text(victory_gpu::console::current().name()),
};
// SAFETY: the caller passes room for the struct.
unsafe { out.write(info) };
@@ -119,6 +130,241 @@ static ANALYTICS_VTABLE: Methods<4> = Methods([
analytics_info as *const (), // 0x18
]);
/// The device type is not a runtime call: code linked into the title reads
/// `ConsoleMode` from this key (`RegOpenKeyW`, `RegQueryValueExW`) and
/// takes a missing value for a PC.
#[cfg(windows)]
mod device_type {
#![allow(non_snake_case)]
use std::ffi::c_void;
use victory_gpu::console::{self, Console};
use crate::modules::files::host;
use crate::{HleModule, hle_export};
type Key = *mut c_void;
const LOCAL_MACHINE: Key = 0xffff_ffff_8000_0002_u64 as Key;
const KEY: &str = r"Software\Microsoft\Windows NT\CurrentVersion\OEM";
const VALUE: &str = "ConsoleMode";
const SUCCESS: u32 = 0;
const FILE_NOT_FOUND: u32 = 2;
const INVALID_PARAMETER: u32 = 87;
const MORE_DATA: u32 = 234;
const DWORD: u32 = 4;
/// Stands for the key; never a host handle value.
static OEM: u8 = 0;
fn oem() -> Key {
(&raw const OEM).cast_mut().cast()
}
/// What the title's code maps to each model's device type.
pub(super) fn console_mode(console: Console) -> u32 {
match console {
Console::SeriesX => 0x64,
Console::SeriesS => 0x60,
}
}
fn is(text: *const u16, expected: &str) -> bool {
if text.is_null() {
return false;
}
// 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))
};
text.eq_ignore_ascii_case(expected)
}
/// Opens our key for its path; the key has no subkeys. `None`: not
/// ours, ask the host.
fn open(root: Key, sub: *const u16, out: *mut Key) -> Option<u32> {
if root == oem() {
return Some(FILE_NOT_FOUND);
}
if root == LOCAL_MACHINE && is(sub, KEY) && !out.is_null() {
// SAFETY: checked non-null; the title passes room for a key.
unsafe { out.write(oem()) };
return Some(SUCCESS);
}
None
}
// Our titles import only these registry functions (and `RegOpenKeyExW`
// below), so no other call can reach the host with our key.
pub extern "system" fn RegOpenKeyW(root: Key, sub: *const u16, out: *mut Key) -> u32 {
open(root, sub, out).unwrap_or_else(|| {
host!("advapi32.dll", "RegOpenKeyW": extern "system" fn(Key, *const u16, *mut Key) -> u32)(
root, sub, out,
)
})
}
pub extern "system" fn RegOpenKeyExW(
root: Key,
sub: *const u16,
options: u32,
access: u32,
out: *mut Key,
) -> u32 {
open(root, sub, out).unwrap_or_else(|| {
host!("advapi32.dll", "RegOpenKeyExW": extern "system" fn(
Key, *const u16, u32, u32, *mut Key,
) -> u32)(root, sub, options, access, out)
})
}
pub extern "system" fn RegQueryValueExW(
key: Key,
name: *const u16,
reserved: *mut u32,
kind: *mut u32,
data: *mut u8,
size: *mut u32,
) -> u32 {
if key != oem() {
return host!("advapi32.dll", "RegQueryValueExW": extern "system" fn(
Key, *const u16, *mut u32, *mut u32, *mut u8, *mut u32,
) -> u32)(key, name, reserved, kind, data, size);
}
if !is(name, VALUE) {
return FILE_NOT_FOUND;
}
if !data.is_null() && size.is_null() {
return INVALID_PARAMETER;
}
// SAFETY: the title passes valid or null pointers, sized by `size`.
unsafe {
if !kind.is_null() {
kind.write(DWORD);
}
if size.is_null() {
return SUCCESS;
}
let room = size.read();
size.write(4);
if data.is_null() {
return SUCCESS;
}
if room < 4 {
return MORE_DATA;
}
data.cast::<u32>()
.write_unaligned(console_mode(console::current()));
}
tracing::debug!(console = console::current().name(), "device type read");
SUCCESS
}
pub extern "system" fn RegCloseKey(key: Key) -> u32 {
if key == oem() {
return SUCCESS;
}
host!("advapi32.dll", "RegCloseKey": extern "system" fn(Key) -> u32)(key)
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "device type",
dlls: &["advapi32.dll", "api-ms-win-core-registry-*"],
exports: vec![
hle_export!(RegOpenKeyW),
hle_export!(RegOpenKeyExW),
hle_export!(RegQueryValueExW),
hle_export!(RegCloseKey),
],
}
}
#[cfg(test)]
mod tests {
use super::*;
fn w(s: &str) -> Vec<u16> {
s.encode_utf16().chain([0]).collect()
}
#[test]
fn titles_read_the_chosen_model() {
assert_eq!(console_mode(Console::SeriesX), 0x64);
assert_eq!(console_mode(Console::SeriesS), 0x60);
let mut key = std::ptr::null_mut();
let path = w(&KEY.to_ascii_lowercase());
assert_eq!(RegOpenKeyW(LOCAL_MACHINE, path.as_ptr(), &mut key), SUCCESS);
let (mut kind, mut value, mut size) = (0, 0u32, 4);
let name = w(VALUE);
let query = |data: *mut u32, size: *mut u32, kind: *mut u32| {
RegQueryValueExW(
key,
name.as_ptr(),
std::ptr::null_mut(),
kind,
data.cast(),
size,
)
};
assert_eq!(query(&mut value, &mut size, &mut kind), SUCCESS);
assert_eq!((kind, size), (DWORD, 4));
assert_eq!(value, console_mode(console::current()));
let mut small = 2;
assert_eq!(query(&mut value, &mut small, &mut kind), MORE_DATA);
assert_eq!(small, 4);
let other = w("Other");
assert_eq!(
RegQueryValueExW(
key,
other.as_ptr(),
std::ptr::null_mut(),
&mut kind,
std::ptr::null_mut(),
&mut size
),
FILE_NOT_FOUND
);
let mut sub = std::ptr::null_mut();
assert_eq!(
RegOpenKeyExW(key, other.as_ptr(), 0, 1, &mut sub),
FILE_NOT_FOUND
);
assert_eq!(RegCloseKey(key), SUCCESS);
let mut again = std::ptr::null_mut();
assert_eq!(
RegOpenKeyExW(LOCAL_MACHINE, path.as_ptr(), 0, 1, &mut again),
SUCCESS
);
assert_eq!(again, oem());
}
#[test]
fn other_keys_reach_the_host() {
let mut key = std::ptr::null_mut();
let path = w(r"Software\Microsoft\Windows NT\CurrentVersion");
assert_eq!(RegOpenKeyW(LOCAL_MACHINE, path.as_ptr(), &mut key), SUCCESS);
assert_ne!(key, oem());
let (mut size, name) = (0, w("ProductName"));
assert_eq!(
RegQueryValueExW(
key,
name.as_ptr(),
std::ptr::null_mut(),
std::ptr::null_mut(),
std::ptr::null_mut(),
&mut size
),
SUCCESS
);
assert!(size > 0);
assert_eq!(RegCloseKey(key), SUCCESS);
}
}
}
#[cfg(windows)]
pub(crate) use device_type::module;
#[cfg(test)]
mod tests {
use super::*;
+139 -38
View File
@@ -4,11 +4,11 @@
//! input device is associated with the user (there are none, `gameinput`).
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::c_void;
use std::ffi::{c_char, 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,
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token,
};
/// The user provider.
@@ -81,6 +81,9 @@ pub static DEVICE_OBJECT: Object = Object::new("user devices", &DEVICE_VTABLE);
pub const INTERFACES: &[Interface] = &[
(PROVIDER, IID, &OBJECT),
// Grand Theft Auto VI (2026) asks with the provider's id; its thunks call
// the same slots with the same arguments (0x108/0x110 change events).
(PROVIDER, PROVIDER, &OBJECT),
(PROVIDER, GAMERTAG_IID, &GAMERTAG_OBJECT),
(DEVICE_PROVIDER, DEVICE_IID, &DEVICE_OBJECT),
];
@@ -178,6 +181,65 @@ extern "system" fn check_privilege(
put(has, true)
}
/// 3: adult.
extern "system" fn get_age_group(_: This, _: Handle, out: *mut u32) -> HRESULT {
put(out, 3)
}
static RESOLVE: u8 = 0;
static TOKEN: u8 = 0;
/// Every privilege is granted, so there is nothing to resolve.
extern "system" fn resolve_privilege_async(
_: This,
_: Handle,
_options: u32,
_privilege: u32,
block: *mut AsyncBlock,
) -> HRESULT {
xasync::finished(block, (&raw const RESOLVE).cast(), S_OK)
}
extern "system" fn resolve_privilege_result(_: This, block: *mut AsyncBlock) -> HRESULT {
let none = std::ptr::null_mut();
xasync::XAsyncGetResult(block, (&raw const RESOLVE).cast(), 0, none, none.cast())
}
/// The documented "failed to get token": tokens come from the service.
pub const FAILED_TO_GET_TOKEN: HRESULT = 0x8924_5111_u32 as i32;
#[allow(clippy::too_many_arguments)]
extern "system" fn token_async(
_: This,
_: Handle,
_options: u32,
_method: *const c_char,
url: *const c_char,
_header_count: usize,
_headers: *const c_void,
_body_size: usize,
_body: *const c_void,
block: *mut AsyncBlock,
) -> HRESULT {
tracing::info!(
url = text(url).unwrap_or_default(),
"token and signature: offline"
);
xasync::finished(block, (&raw const TOKEN).cast(), FAILED_TO_GET_TOKEN)
}
extern "system" fn token_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT {
xasync::XAsyncGetResultSize(block, out)
}
extern "system" fn token_result(
_: This,
block: *mut AsyncBlock,
size: usize,
buffer: *mut c_void,
_data: *mut *const c_void,
used: *mut usize,
) -> HRESULT {
xasync::XAsyncGetResult(block, (&raw const TOKEN).cast(), size, buffer, used)
}
/// The user never changes and no device is ever associated, so these
/// callbacks are never called.
extern "system" fn register(
@@ -198,43 +260,44 @@ extern "system" fn find_for_device(_: This, _device: *const c_void, _: *mut Hand
USER_NOT_FOUND
}
// Unset slots: gamer pictures, token and signature, issue resolution.
// Unset slots (no title seen calls them): maximum users, gamer pictures,
// the UTF-16 token calls, 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
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
get_age_group as *const (), // 0x98
check_privilege as *const (), // 0xa0
resolve_privilege_async as *const (), // 0xa8 with UI
resolve_privilege_result as *const (), // 0xb0
token_async as *const (), // 0xb8 token and signature
token_size as *const (), // 0xc0
token_result as *const (), // 0xc8
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([
@@ -294,5 +357,43 @@ mod tests {
get(this, handle, 0, 2, name.as_mut_ptr(), &mut used),
E_NOT_SUFFICIENT_BUFFER
);
type Age = extern "system" fn(This, Handle, *mut u32) -> HRESULT;
let mut age = 0;
assert_eq!(slot::<Age>(&OBJECT, 0x98)(this, handle, &mut age), S_OK);
assert_eq!(age, 3, "adult");
type Token = extern "system" fn(
This,
Handle,
u32,
*const c_char,
*const c_char,
usize,
*const c_void,
usize,
*const c_void,
*mut AsyncBlock,
) -> HRESULT;
let (null, url) = (std::ptr::null(), c"https://example.invalid/");
let token = slot::<Token>(&OBJECT, 0xb8);
assert_eq!(
token(
this,
handle,
0,
c"GET".as_ptr(),
url.as_ptr(),
0,
null,
0,
null,
&mut block
),
S_OK
);
assert_eq!(
xasync::XAsyncGetStatus(&mut block, true),
FAILED_TO_GET_TOKEN
);
}
}
+112 -16
View File
@@ -32,6 +32,12 @@ pub fn set_image_path(base: usize, path: &Path) {
paths.push((base, path));
}
/// Forgets a title image that was unmapped again.
pub fn forget_image(base: usize) {
let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
paths.retain(|(b, _)| *b != base);
}
pub fn image_path(base: usize) -> Option<PathBuf> {
let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
paths
@@ -70,33 +76,88 @@ pub fn load_title_dll(file: &str) -> Result<Option<usize>, String> {
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Title {
pub id: u32,
/// The store's product id (empty if the manifest has none).
pub store_id: String,
/// Persistent local storage: our folder for it and the title's quota.
/// Game saves live beside it ([`Title::saves`]).
pub storage: PathBuf,
pub storage_bytes: u64,
}
impl Title {
/// Title id and storage quota from the manifest's text (zero where it
/// has none); the storage folder is left for the caller to choose.
// shortcut: finds the two elements by text, not as XML; parse properly
// once more of the manifest is needed.
/// Id, store id and storage quota from the manifest (zero or empty
/// where it has none); the storage folder is left for the caller.
pub fn from_manifest(text: &str) -> Title {
fn element<'a>(text: &'a str, tag: &str) -> Option<&'a str> {
let start = text.find(&format!("<{tag}>"))? + tag.len() + 2;
let len = text[start..].find('<')?;
Some(text[start..start + len].trim())
}
let id = element(text, "TitleId").and_then(|v| u32::from_str_radix(v, 16).ok());
let storage_mb = text
.find("<PersistentLocalStorage>")
.and_then(|at| element(&text[at..], "SizeMB"))
.and_then(|v| v.parse::<u64>().ok());
let elements = elements(text);
let get = |path: &str| {
elements
.iter()
.find(|(p, _)| p == path)
.map(|(_, text)| text.as_str())
};
let id = get("Game/TitleId").and_then(|v| u32::from_str_radix(v, 16).ok());
let storage_mb = get("Game/PersistentLocalStorage/SizeMB").and_then(|v| v.parse().ok());
Title {
id: id.unwrap_or(0),
store_id: get("Game/StoreId").unwrap_or_default().to_owned(),
storage: PathBuf::new(),
storage_bytes: storage_mb.unwrap_or(0) << 20,
}
}
/// Where game saves live: next to persistent local storage, under the
/// data directory, never the cache.
pub fn saves(&self) -> PathBuf {
self.storage.with_file_name("saves")
}
}
/// Each element of an XML text as its path from the root (`Game/TitleId`)
/// and its trimmed text up to the first child, the predefined entities
/// decoded; comments, CDATA sections, declarations and attributes are
/// skipped.
fn elements(text: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
let mut path: Vec<&str> = Vec::new();
let mut rest = text;
while let Some(open) = rest.find('<') {
rest = &rest[open..];
let end = if rest.starts_with("<!--") {
rest.find("-->").map(|e| e + 3)
} else if rest.starts_with("<![CDATA[") {
rest.find("]]>").map(|e| e + 3)
} else {
rest.find('>').map(|e| e + 1)
};
let Some(end) = end else { break };
let tag = &rest[1..end - 1];
rest = &rest[end..];
if tag.starts_with(['!', '?']) {
continue;
}
if let Some(name) = tag.strip_prefix('/') {
if let Some(at) = path.iter().rposition(|n| *n == name.trim()) {
path.truncate(at);
}
continue;
}
let closed = tag.ends_with('/');
let name = tag
.trim_end_matches('/')
.split_whitespace()
.next()
.unwrap_or("");
path.push(name);
let body = rest[..rest.find('<').unwrap_or(rest.len())].trim();
let body = [("&lt;", "<"), ("&gt;", ">"), ("&quot;", "\""), ("&apos;", "'"), ("&amp;", "&")]
.iter()
.fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c));
out.push((path.join("/"), body));
if closed {
path.pop();
}
}
out
}
static TITLE: Mutex<Option<Title>> = Mutex::new(None);
@@ -114,17 +175,52 @@ pub fn title() -> Title {
.unwrap_or_default()
}
/// Gives the process the console's millisecond timers. Titles pace
/// themselves with short waits (Grand Theft Auto VI's audio mixer sleeps
/// about 4 ms per 5.3 ms block) and cannot tune the timer on the console;
/// a desktop process waits in 15.6 ms ticks unless it asks for finer ones,
/// and Windows 11 drops that request while the window is hidden unless the
/// process opts out. Process-wide, for the whole run.
#[cfg(windows)]
pub fn use_console_timers() {
use windows_sys::Win32::Media::timeBeginPeriod;
use windows_sys::Win32::System::Threading::{
GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION,
PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE,
ProcessPowerThrottling, SetProcessInformation,
};
let keep = PROCESS_POWER_THROTTLING_STATE {
Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION,
ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION,
StateMask: 0,
};
// SAFETY: plain process settings; `keep` outlives the call.
unsafe {
SetProcessInformation(
GetCurrentProcess(),
ProcessPowerThrottling,
(&raw const keep).cast(),
size_of_val(&keep) as u32,
);
timeBeginPeriod(1);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_title_id_and_storage_quota() {
let text = "<Game><Identity Name=\"x\"/>\n <TitleId>639AA8DD</TitleId>\n\
fn reads_title_id_store_id_and_storage_quota() {
let text = "\u{feff}<?xml version=\"1.0\"?>\n<Game configVersion=\"1\">\
<!-- <TitleId>00000000</TitleId> -->\
<Identity Name=\"x\"/>\n <TitleId>639AA8DD</TitleId>\n\
<![CDATA[ <TitleId>1</TitleId> ]]> <StoreId>9&amp;C</StoreId><Other><SizeMB>7</SizeMB></Other>\
<PersistentLocalStorage>\n <SizeMB>1024</SizeMB> <!-- c -->\n\
</PersistentLocalStorage></Game>";
let t = Title::from_manifest(text);
assert_eq!((t.id, t.storage_bytes), (0x639A_A8DD, 1024 << 20));
assert_eq!(t.store_id, "9&C");
assert_eq!(Title::from_manifest("").storage_bytes, 0);
}
}