Run Minecraft: runtime HLE, D3D12.X device on the host GPU, shader IR
Loader: map title-shipped DLLs, patch static TLS loads to slot 0, crash reporter, title paths for GetModuleFileName*. HLE: task queue and async, XUser (one offline user), system ids, title id, features, invites, game events, persistent local storage, GameInput with no devices, xmem, console audio hardware queues, life cycle (close suspends, then terminates), and a file layer with virtual drives rewritten in path-taking imports. GPU: D3D12.X device, DXGI chain, heaps, resources, fences, queues and command lists translated onto a host D3D12 device; clears, barriers, copies, resolves and PresentX into the title's window. Shaders: SGD5 reader and `victory translate`; SSA IR with node splitting for irreducible flow; structurisation removing EXEC. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
12caefe804
commit
754619f30e
61 files changed
+12775
-88
No files matched your search
@@ -17,6 +17,9 @@ pub struct Config {
|
||||
pub game_dir: Option<PathBuf>,
|
||||
/// Root for all derived data. Always outside the repository.
|
||||
pub cache_dir: PathBuf,
|
||||
/// What titles write and must keep (persistent local storage). Never
|
||||
/// inside the cache, which may be deleted at any time.
|
||||
pub data_dir: PathBuf,
|
||||
/// Other titles used to exercise platform-level code.
|
||||
pub test_titles: Vec<PathBuf>,
|
||||
/// The config file that was read, if any.
|
||||
@@ -35,6 +38,7 @@ struct FileConfig {
|
||||
struct FilePaths {
|
||||
game_dir: Option<PathBuf>,
|
||||
cache_dir: Option<PathBuf>,
|
||||
data_dir: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
test_titles: Vec<PathBuf>,
|
||||
}
|
||||
@@ -83,10 +87,14 @@ impl Config {
|
||||
};
|
||||
let cache_dir = env_path("VICTORY_CACHE_DIR")
|
||||
.or(file.cache_dir)
|
||||
.map_or_else(default_cache_dir, Ok)?;
|
||||
.map_or_else(|| default_dir("cache"), Ok)?;
|
||||
let data_dir = env_path("VICTORY_DATA_DIR")
|
||||
.or(file.data_dir)
|
||||
.map_or_else(|| default_dir("data"), Ok)?;
|
||||
Ok(Config {
|
||||
game_dir: env_path("VICTORY_GAME_DIR").or(file.game_dir),
|
||||
cache_dir,
|
||||
data_dir,
|
||||
test_titles,
|
||||
source,
|
||||
})
|
||||
@@ -102,20 +110,30 @@ impl Config {
|
||||
|
||||
/// Returns `<cache>/<sub>`, creating it, after checking the asset policy.
|
||||
pub fn cache_subdir(&self, sub: &str) -> Result<PathBuf> {
|
||||
let dir = self.cache_dir.join(sub);
|
||||
ensure_outside_repo(&dir)?;
|
||||
std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
|
||||
Ok(dir)
|
||||
subdir(&self.cache_dir, sub)
|
||||
}
|
||||
|
||||
/// Returns `<data>/<sub>`, creating it, after checking the asset policy.
|
||||
pub fn data_subdir(&self, sub: &str) -> Result<PathBuf> {
|
||||
subdir(&self.data_dir, sub)
|
||||
}
|
||||
}
|
||||
|
||||
fn default_cache_dir() -> Result<PathBuf> {
|
||||
fn subdir(root: &Path, sub: &str) -> Result<PathBuf> {
|
||||
let dir = root.join(sub);
|
||||
ensure_outside_repo(&dir)?;
|
||||
std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
/// `%LOCALAPPDATA%/victory/<name>` (elsewhere the XDG or home cache).
|
||||
fn default_dir(name: &str) -> Result<PathBuf> {
|
||||
let base = std::env::var_os("LOCALAPPDATA")
|
||||
.or_else(|| std::env::var_os("XDG_CACHE_HOME"))
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))
|
||||
.context("cannot determine a cache directory; set VICTORY_CACHE_DIR")?;
|
||||
Ok(base.join("victory").join("cache"))
|
||||
.context("cannot determine a user directory; set VICTORY_CACHE_DIR and VICTORY_DATA_DIR")?;
|
||||
Ok(base.join("victory").join(name))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -7,5 +7,9 @@ rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
memchr.workspace = true
|
||||
miniz_oxide.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -3,6 +3,8 @@
|
||||
//! offsets or byte-pattern signatures). What may and may not be stored here
|
||||
//! is defined in docs/asset-policy.md.
|
||||
|
||||
pub mod sgd5;
|
||||
|
||||
/// A specific build of the Grand Theft Auto VI executable we know how to run.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct KnownBuild {
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
//! `SGD5`: the engine's shader file. Each record holds one shader container,
|
||||
//! deflate-packed. The header tables are not decoded yet, so records are
|
||||
//! found by their marker and cross-checked by their sizes:
|
||||
//!
|
||||
//! ```text
|
||||
//! u8 name length (with NUL), name, NUL, u8 kind,
|
||||
//! u32 n, u32 0x000DDCE7, u32 n, u32 unpacked size, raw deflate (n - 12 bytes)
|
||||
//! ```
|
||||
|
||||
pub const MAGIC: &[u8; 4] = b"SGD5";
|
||||
const MARKER: [u8; 4] = 0x000D_DCE7_u32.to_le_bytes();
|
||||
/// Containers are at most a few MiB; refuse to allocate for absurd sizes.
|
||||
const MAX_UNPACKED: usize = 64 << 20;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Record<'a> {
|
||||
/// Offset of the marker in the file.
|
||||
pub offset: usize,
|
||||
/// Like `PS_<name>_<hash>_Wrapped`; `None` if the bytes before the
|
||||
/// record do not read as one.
|
||||
pub name: Option<&'a str>,
|
||||
/// Record type, meaning unknown (0x32 most shaders, 0x41 mesh shaders
|
||||
/// and some material families, 0x3c compute, 0x40, 0x42).
|
||||
pub kind: u8,
|
||||
packed: &'a [u8],
|
||||
unpacked_size: usize,
|
||||
}
|
||||
|
||||
impl Record<'_> {
|
||||
/// The container, or `None` if the stream is corrupt.
|
||||
pub fn unpack(&self) -> Option<Vec<u8>> {
|
||||
miniz_oxide::inflate::decompress_to_vec_with_limit(self.packed, self.unpacked_size)
|
||||
.ok()
|
||||
.filter(|out| out.len() == self.unpacked_size)
|
||||
}
|
||||
}
|
||||
|
||||
/// An SGD5 file, or a file holding one (an archive: records are found by
|
||||
/// their marker, so no index is needed).
|
||||
pub fn is_sgd5(file: &[u8]) -> bool {
|
||||
memchr::memmem::find(file, MAGIC).is_some()
|
||||
}
|
||||
|
||||
/// Every record in an SGD5 file, in file order.
|
||||
pub fn records(file: &[u8]) -> impl Iterator<Item = Record<'_>> {
|
||||
memchr::memmem::find_iter(file, &MARKER).filter_map(|at| record(file, at))
|
||||
}
|
||||
|
||||
fn record(file: &[u8], at: usize) -> Option<Record<'_>> {
|
||||
let u32_at = |o: usize| {
|
||||
file.get(o..o + 4)
|
||||
.map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")) as usize)
|
||||
};
|
||||
let n = u32_at(at.checked_sub(4)?)?;
|
||||
let unpacked_size = u32_at(at + 8)?;
|
||||
if u32_at(at + 4)? != n || n < 12 || unpacked_size > MAX_UNPACKED {
|
||||
return None;
|
||||
}
|
||||
let nul = at.checked_sub(6)?;
|
||||
Some(Record {
|
||||
offset: at,
|
||||
name: (file[nul] == 0).then(|| name_before(file, nul)).flatten(),
|
||||
kind: file[at - 5],
|
||||
packed: file.get(at + 12..at + n)?,
|
||||
unpacked_size,
|
||||
})
|
||||
}
|
||||
|
||||
/// The printable name that ends at `nul` and follows its length byte.
|
||||
fn name_before(file: &[u8], nul: usize) -> Option<&str> {
|
||||
let run = file[..nul]
|
||||
.iter()
|
||||
.rposition(|b| !b.is_ascii_graphic())
|
||||
.map_or(0, |p| p + 1);
|
||||
// From 32 characters on, the length byte is printable too.
|
||||
(run.saturating_sub(1)..nul)
|
||||
.find(|&l| usize::from(file[l]) == nul - l)
|
||||
.and_then(|l| std::str::from_utf8(&file[l + 1..nul]).ok())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn record_bytes(name: &str, kind: u8, payload: &[u8]) -> Vec<u8> {
|
||||
let packed = miniz_oxide::deflate::compress_to_vec(payload, 6);
|
||||
let n = (packed.len() + 12) as u32;
|
||||
let mut out = vec![0xF4, 0x01, 0, 0, name.len() as u8 + 1];
|
||||
out.extend_from_slice(name.as_bytes());
|
||||
out.extend_from_slice(&[0, kind]);
|
||||
for v in [n, 0x000D_DCE7, n, payload.len() as u32] {
|
||||
out.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
out.extend_from_slice(&packed);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_records() {
|
||||
let long = format!("PS_{}_Wrapped", "x".repeat(40));
|
||||
let mut file = MAGIC.to_vec();
|
||||
file.extend_from_slice(&[1, 2, 3, 4]);
|
||||
file.extend(record_bytes(
|
||||
"VS_Blit_0011aabb_Wrapped",
|
||||
0x32,
|
||||
b"first container",
|
||||
));
|
||||
// A marker whose sizes disagree is not a record.
|
||||
file.extend_from_slice(&[9, 0, 0, 0, 0xE7, 0xDC, 0x0D, 0, 8, 0, 0, 0]);
|
||||
file.extend(record_bytes(&long, 0x41, &[7; 300]));
|
||||
|
||||
assert!(is_sgd5(&file));
|
||||
let found: Vec<_> = records(&file).collect();
|
||||
assert_eq!(found.len(), 2);
|
||||
assert_eq!(found[0].name, Some("VS_Blit_0011aabb_Wrapped"));
|
||||
assert_eq!(found[0].kind, 0x32);
|
||||
assert_eq!(found[0].unpack().as_deref(), Some(&b"first container"[..]));
|
||||
assert_eq!(found[1].name, Some(long.as_str()));
|
||||
assert_eq!(found[1].unpack(), Some(vec![7; 300]));
|
||||
|
||||
// The same file inside an archive.
|
||||
let mut archive = vec![0x5A; 0x1000];
|
||||
archive.extend_from_slice(&file);
|
||||
assert!(is_sgd5(&archive));
|
||||
assert_eq!(records(&archive).count(), 2);
|
||||
assert!(!is_sgd5(&archive[..0x1000]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_stream_does_not_unpack() {
|
||||
let mut file = record_bytes("CS_x", 0x3c, &[1; 64]);
|
||||
file[27] = 0xFF; // first packed byte: reserved block type
|
||||
let r = records(&file).next().unwrap();
|
||||
assert_eq!(r.unpack(), None);
|
||||
}
|
||||
}
|
||||
@@ -7,5 +7,22 @@ rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tracing.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_LibraryLoader", "Win32_System_Threading"] }
|
||||
windows = { workspace = true, features = [
|
||||
"Win32_Graphics_Direct3D",
|
||||
"Win32_Graphics_Direct3D12",
|
||||
"Win32_Graphics_Dxgi",
|
||||
"Win32_Graphics_Dxgi_Common",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_Security",
|
||||
"Win32_System_LibraryLoader",
|
||||
"Win32_System_Threading",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
] }
|
||||
@@ -0,0 +1,201 @@
|
||||
//! Descriptor heaps: zeroed memory, with handles that are plain addresses
|
||||
//! (CPU and GPU alike, as on the console).
|
||||
//!
|
||||
//! Descriptor sizes: views 32 bytes and samplers 16, the size of RDNA 2's
|
||||
//! image and sampler descriptors, so a title that copies descriptors itself
|
||||
//! moves whole ones. Render target and depth views are ours alone; 128 bytes
|
||||
//! leaves room for whatever stride a title assumes.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use crate::object::{self, DESCRIPTOR_HEAP, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid};
|
||||
use crate::resource::{Memory, PAGEABLE_IIDS};
|
||||
|
||||
const HEAP_IIDS: [Iid; 4] = [
|
||||
guid(
|
||||
0x8efb471d,
|
||||
0x616c,
|
||||
0x4f49,
|
||||
[0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51],
|
||||
),
|
||||
PAGEABLE_IIDS[0],
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct HeapDesc {
|
||||
kind: u32,
|
||||
count: u32,
|
||||
flags: u32,
|
||||
nodes: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Heap {
|
||||
object: Object,
|
||||
desc: HeapDesc,
|
||||
memory: Memory,
|
||||
}
|
||||
|
||||
fn heap<'a>(this: This) -> &'a Heap {
|
||||
// SAFETY: called from descriptor heap methods only.
|
||||
unsafe { &*this.cast::<Heap>() }
|
||||
}
|
||||
|
||||
/// Bytes per descriptor, by heap type (views, samplers, render targets,
|
||||
/// depth).
|
||||
fn increment(kind: u32) -> Option<u32> {
|
||||
[32, 16, 128, 128].get(kind as usize).copied()
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn increment_size(_: This, kind: u32) -> u32 {
|
||||
increment(kind).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// What our render target views hold: the resource and the view
|
||||
/// description, turned into a host view when a command uses them.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct RtvRecord {
|
||||
tag: u32,
|
||||
described: u32,
|
||||
pub(crate) resource: This,
|
||||
desc: [u32; 6],
|
||||
}
|
||||
const RTV_TAG: u32 = u32::from_le_bytes(*b"vRTV");
|
||||
const _: () = assert!(size_of::<RtvRecord>() <= 112);
|
||||
|
||||
impl RtvRecord {
|
||||
/// The view description in the host's type (the same layout).
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn desc(
|
||||
&self,
|
||||
) -> Option<windows::Win32::Graphics::Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC> {
|
||||
// SAFETY: 24 bytes in the host's layout.
|
||||
(self.described != 0).then(|| unsafe {
|
||||
(&raw const self.desc)
|
||||
.cast::<windows::Win32::Graphics::Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC>()
|
||||
.read_unaligned()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Device method: records the view at `handle` (descriptor memory).
|
||||
pub(crate) extern "system" fn create_rtv(
|
||||
_: This,
|
||||
resource: This,
|
||||
desc: *const [u32; 6],
|
||||
handle: u64,
|
||||
) {
|
||||
if handle == 0 {
|
||||
return;
|
||||
}
|
||||
// SAFETY: the title passes a description or null.
|
||||
let described = unsafe { desc.as_ref() };
|
||||
let record = RtvRecord {
|
||||
tag: RTV_TAG,
|
||||
described: u32::from(described.is_some()),
|
||||
resource,
|
||||
desc: described.copied().unwrap_or_default(),
|
||||
};
|
||||
// SAFETY: the handle is a descriptor slot, at least 112 bytes.
|
||||
unsafe { (handle as *mut RtvRecord).write_unaligned(record) };
|
||||
}
|
||||
|
||||
/// The view recorded at `handle`, if one is.
|
||||
pub(crate) fn rtv_record(handle: u64) -> Option<RtvRecord> {
|
||||
if handle == 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the handle is a descriptor slot the title passes back.
|
||||
let record = unsafe { (handle as *const RtvRecord).read_unaligned() };
|
||||
(record.tag == RTV_TAG).then_some(record)
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create_heap(
|
||||
_: This,
|
||||
desc: *const HeapDesc,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(&desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
let Some(size) = increment(desc.kind).map(|i| u64::from(i) * u64::from(desc.count.max(1)))
|
||||
else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
tracing::debug!(?desc, "descriptor heap");
|
||||
let memory = match Memory::zeroed(size, 64) {
|
||||
Ok(memory) => memory,
|
||||
Err(hr) => return hr,
|
||||
};
|
||||
let heap = Box::new(Heap {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
desc,
|
||||
memory,
|
||||
});
|
||||
object::hand_out(DESCRIPTOR_HEAP, heap, iid, &HEAP_IIDS, out)
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let found = object::is(iid, &HEAP_IIDS).then_some(this);
|
||||
object::answer(DESCRIPTOR_HEAP, iid, found, out)
|
||||
}
|
||||
extern "system" fn release(this: This) -> u32 {
|
||||
object::release_boxed::<Heap>(this)
|
||||
}
|
||||
extern "system" fn desc(this: This, out: *mut HeapDesc) {
|
||||
if !out.is_null() {
|
||||
// SAFETY: checked non-null; the title passes room for a description.
|
||||
unsafe { out.write(heap(this).desc) };
|
||||
}
|
||||
}
|
||||
/// The same address for the CPU and the GPU start.
|
||||
extern "system" fn start(this: This) -> u64 {
|
||||
heap(this).memory.address()
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, heap 3.
|
||||
static FUNCTIONS: Table<11> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<DESCRIPTOR_HEAP, 11>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
f[8] = desc as *const (); // 0x40
|
||||
f[9] = start as *const (); // 0x48 CPU
|
||||
f[10] = start as *const (); // 0x50 GPU
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::{S_OK, slot};
|
||||
|
||||
#[test]
|
||||
fn heaps_hold_count_descriptors_from_their_start() {
|
||||
let null = std::ptr::null();
|
||||
let desc = HeapDesc {
|
||||
kind: 0,
|
||||
count: 1000,
|
||||
flags: 1,
|
||||
nodes: 0,
|
||||
};
|
||||
let mut h = null;
|
||||
assert_eq!(create_heap(null, &desc, &HEAP_IIDS[0], &mut h), S_OK);
|
||||
let cpu = slot::<extern "system" fn(This) -> u64>(h, 0x48)(h);
|
||||
assert_eq!(cpu % 64, 0);
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x50)(h), cpu);
|
||||
assert_eq!(increment_size(null, 0), 32);
|
||||
// SAFETY: the heap holds 1000 descriptors of 32 bytes.
|
||||
unsafe { (cpu as *mut u8).add(999 * 32 + 31).write(1) };
|
||||
assert_eq!(increment_size(null, 9), 0);
|
||||
let bad = HeapDesc { kind: 9, ..desc };
|
||||
assert_eq!(create_heap(null, &bad, &HEAP_IIDS[0], &mut h), E_INVALIDARG);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
//! The device titles get from device creation, laid out as their inlined
|
||||
//! code expects: the object header, then device fields. Its table starts
|
||||
//! like the PC device interface (IUnknown, the object methods, then the
|
||||
//! device methods in PC order); console additions follow. Methods we have
|
||||
//! not written log their table offset and fail, so a run shows what to
|
||||
//! write next.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
|
||||
use crate::object::{
|
||||
self, E_INVALIDARG, E_NOINTERFACE, E_NOTIMPL, HRESULT, Iid, Object, S_FALSE, S_OK, Table, This,
|
||||
guid, guid_text,
|
||||
};
|
||||
use crate::{
|
||||
descriptor, dxgi, fence, frame, list, pipeline, query, queue, resource, root, signature,
|
||||
};
|
||||
|
||||
/// What D3D returns when none of the requested feature levels is supported.
|
||||
const UNSUPPORTED: HRESULT = 0x887A_0004_u32 as i32;
|
||||
|
||||
/// The device interface id (the same as on PC). Titles also import it as
|
||||
/// data.
|
||||
pub static IID: Iid = guid(
|
||||
0x189819f1,
|
||||
0x1db6,
|
||||
0x4b57,
|
||||
[0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7],
|
||||
);
|
||||
|
||||
/// The interface version these layouts were checked against (2.4, what
|
||||
/// Minecraft passes). Newer titles may lay objects out differently.
|
||||
pub const CHECKED_VERSION: u32 = 0x0002_0004;
|
||||
|
||||
/// Feature level 12_2, what the console hardware supports.
|
||||
const HIGHEST_FEATURE_LEVEL: u32 = 0xc200;
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Device {
|
||||
object: Object,
|
||||
/// GPU address of a null constant buffer; none yet.
|
||||
null_constant_buffer: u64,
|
||||
/// Byte 0 non-zero: calls the title would otherwise inline come to the
|
||||
/// table. The rest is reserved.
|
||||
out_of_line: [u32; 16],
|
||||
}
|
||||
const _: () = assert!(size_of::<Device>() == 0x58);
|
||||
|
||||
/// One device per process, as on the console.
|
||||
pub(crate) static DEVICE: Device = Device {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
null_constant_buffer: 0,
|
||||
out_of_line: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
};
|
||||
|
||||
pub(crate) fn device() -> This {
|
||||
(&raw const DEVICE).cast()
|
||||
}
|
||||
|
||||
/// Device creation: `(adapter, parameters, iid, out)`. The parameters start
|
||||
/// with the interface version; the rest (ring and scratch sizes, features
|
||||
/// to leave out) does not matter to us yet.
|
||||
pub extern "system" fn create(
|
||||
_adapter: *const c_void,
|
||||
parameters: *const u32,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
if parameters.is_null() || iid.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: checked non-null; the title passes its parameters and an id.
|
||||
let (version, iid) = unsafe { (parameters.read(), &*iid) };
|
||||
tracing::info!(version = format_args!("{version:#x}"), "D3D12.X device");
|
||||
if version != CHECKED_VERSION {
|
||||
tracing::warn!(
|
||||
version = format_args!("{version:#x}"),
|
||||
"device layouts were checked against {CHECKED_VERSION:#x} only"
|
||||
);
|
||||
}
|
||||
if *iid != IID {
|
||||
tracing::warn!(iid = %guid_text(iid), "device created as an unknown interface");
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
if out.is_null() {
|
||||
return S_FALSE;
|
||||
}
|
||||
object::answer(object::DEVICE, iid, Some(device()), out)
|
||||
}
|
||||
|
||||
/// The device, or its DXGI side.
|
||||
extern "system" fn query_interface(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let found = if object::is(iid, &[IID]) {
|
||||
Some(this)
|
||||
} else if object::is(iid, &dxgi::DEVICE_IIDS) {
|
||||
Some(dxgi::device())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
object::answer(object::DEVICE, iid, found, out)
|
||||
}
|
||||
|
||||
extern "system" fn node_count(_: This) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
/// Feature query 2: the highest of the requested feature levels we support.
|
||||
#[repr(C)]
|
||||
struct FeatureLevels {
|
||||
count: u32,
|
||||
requested: *const u32,
|
||||
highest: u32,
|
||||
}
|
||||
|
||||
/// Feature query 0, what an RDNA 2 GPU reports. The console's layout has
|
||||
/// one field more than PC's (index 11).
|
||||
const OPTIONS: [u32; 16] = [
|
||||
1, // double-precision shader operations
|
||||
1, // output-merger logic operations
|
||||
2, // minimum precision: 16-bit
|
||||
3, // tiled resources tier
|
||||
3, // resource binding tier
|
||||
1, // stencil reference from pixel shaders
|
||||
1, // typed UAV loads of more formats
|
||||
1, // rasterizer-ordered views
|
||||
3, // conservative rasterization tier
|
||||
40, // GPU address bits per resource
|
||||
0, // 64 KiB standard swizzle
|
||||
0, // console-only field
|
||||
0, // cross-node sharing tier
|
||||
0, // cross-adapter row-major textures
|
||||
1, // viewport and render target index from any stage
|
||||
2, // resource heap tier
|
||||
];
|
||||
|
||||
extern "system" fn check_feature_support(
|
||||
_: This,
|
||||
feature: u32,
|
||||
data: *mut c_void,
|
||||
size: u32,
|
||||
) -> HRESULT {
|
||||
const OPTIONS_QUERY: u32 = 0;
|
||||
const ARCHITECTURE: u32 = 1;
|
||||
const FEATURE_LEVELS: u32 = 2;
|
||||
const FORMAT_SUPPORT: u32 = 3;
|
||||
const MULTISAMPLE: u32 = 4;
|
||||
let expected = match feature {
|
||||
OPTIONS_QUERY => size_of_val(&OPTIONS),
|
||||
ARCHITECTURE => 16,
|
||||
FEATURE_LEVELS => size_of::<FeatureLevels>(),
|
||||
FORMAT_SUPPORT => 12,
|
||||
MULTISAMPLE => 16,
|
||||
_ => {
|
||||
tracing::warn!(feature, size, "device feature query not implemented");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
};
|
||||
if data.is_null() || size as usize != expected {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
match feature {
|
||||
OPTIONS_QUERY => {
|
||||
// SAFETY: checked size and non-null.
|
||||
unsafe { data.cast::<[u32; 16]>().write_unaligned(OPTIONS) };
|
||||
S_OK
|
||||
}
|
||||
ARCHITECTURE => {
|
||||
// SAFETY: checked size and non-null.
|
||||
let a = unsafe { &mut *data.cast::<[u32; 4]>() };
|
||||
if a[0] != 0 {
|
||||
return E_INVALIDARG; // one node only
|
||||
}
|
||||
// Not tile-based; unified, cache-coherent memory.
|
||||
a[1..].copy_from_slice(&[0, 1, 1]);
|
||||
S_OK
|
||||
}
|
||||
FORMAT_SUPPORT => {
|
||||
// SAFETY: checked size and non-null.
|
||||
let q = unsafe { &mut *data.cast::<[u32; 3]>() };
|
||||
// shortcut: every use of every format; answer from the host
|
||||
// device once there is one.
|
||||
q[1] = 0x7fff_ffff;
|
||||
q[2] = 0xffff;
|
||||
S_OK
|
||||
}
|
||||
MULTISAMPLE => {
|
||||
// SAFETY: checked size and non-null.
|
||||
let q = unsafe { &mut *data.cast::<[u32; 4]>() };
|
||||
// Format, sample count, flags in; one quality level out for the
|
||||
// counts the hardware has.
|
||||
q[3] = u32::from(matches!(q[1], 1 | 2 | 4 | 8));
|
||||
S_OK
|
||||
}
|
||||
_ => feature_levels(data),
|
||||
}
|
||||
}
|
||||
|
||||
fn feature_levels(data: *mut c_void) -> HRESULT {
|
||||
// SAFETY: the caller checked size and non-null.
|
||||
let query = unsafe { &mut *data.cast::<FeatureLevels>() };
|
||||
if query.requested.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: the title passes `count` levels.
|
||||
let requested = unsafe { std::slice::from_raw_parts(query.requested, query.count as usize) };
|
||||
match requested
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|&l| l <= HIGHEST_FEATURE_LEVEL)
|
||||
.max()
|
||||
{
|
||||
Some(level) => {
|
||||
query.highest = level;
|
||||
S_OK
|
||||
}
|
||||
None => UNSUPPORTED,
|
||||
}
|
||||
}
|
||||
|
||||
/// IUnknown 3, object methods 4, device methods 76.
|
||||
static FUNCTIONS: Table<83> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<{ object::DEVICE }, 83>());
|
||||
f[0] = query_interface as *const (); // 0x00
|
||||
f[7] = node_count as *const (); // 0x38
|
||||
f[8] = queue::create as *const (); // 0x40
|
||||
f[9] = list::create_allocator as *const (); // 0x48
|
||||
f[12] = list::create_list as *const (); // 0x60
|
||||
f[10] = pipeline::create_graphics as *const (); // 0x50
|
||||
f[11] = pipeline::create_compute as *const (); // 0x58
|
||||
f[13] = check_feature_support as *const (); // 0x68
|
||||
f[14] = descriptor::create_heap as *const (); // 0x70
|
||||
f[15] = descriptor::increment_size as *const (); // 0x78
|
||||
f[16] = root::create as *const (); // 0x80
|
||||
f[20] = descriptor::create_rtv as *const (); // 0xa0
|
||||
f[25] = resource::allocation_info as *const (); // 0xc8
|
||||
f[27] = resource::create_committed as *const (); // 0xd8
|
||||
f[28] = resource::create_heap as *const (); // 0xe0
|
||||
f[29] = resource::create_placed as *const (); // 0xe8
|
||||
f[36] = fence::create as *const (); // 0x120
|
||||
f[38] = resource::copyable_footprints as *const (); // 0x130
|
||||
f[39] = query::create as *const (); // 0x138
|
||||
f[41] = signature::create as *const (); // 0x148
|
||||
f[69] = object::ignore as *const (); // 0x228 debug error filter
|
||||
f[73] = list::create_list_x as *const (); // 0x248
|
||||
f[78] = frame::set_interval as *const (); // 0x270
|
||||
f[79] = frame::schedule as *const (); // 0x278
|
||||
f[80] = frame::wait as *const (); // 0x280
|
||||
f[81] = frame::statistics as *const (); // 0x288
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::slot;
|
||||
|
||||
fn create_as(iid: &Iid) -> (HRESULT, This) {
|
||||
let version = CHECKED_VERSION;
|
||||
let mut device = std::ptr::null();
|
||||
let hr = create(std::ptr::null(), &version, iid, &mut device);
|
||||
(hr, device)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creation_hands_out_the_device() {
|
||||
let (hr, device) = create_as(&IID);
|
||||
assert_eq!(hr, S_OK);
|
||||
assert_eq!(device, super::device());
|
||||
// The title tests byte 0x18 before inlining a device call.
|
||||
// SAFETY: the device is 0x58 bytes.
|
||||
assert_ne!(unsafe { device.cast::<u8>().add(0x18).read() }, 0);
|
||||
assert_eq!(create_as(&[0; 16]).0, E_NOINTERFACE);
|
||||
assert_eq!(
|
||||
slot::<extern "system" fn(This) -> u32>(device, 0x38)(device),
|
||||
1
|
||||
);
|
||||
let missing = slot::<extern "system" fn() -> HRESULT>(device, 0x88);
|
||||
assert_eq!(missing(), E_NOTIMPL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feature_levels_pick_the_highest_supported() {
|
||||
type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT;
|
||||
let device = device();
|
||||
let check = slot::<Check>(device, 0x68);
|
||||
let query = |levels: &[u32], size| {
|
||||
let mut query = FeatureLevels {
|
||||
count: levels.len() as u32,
|
||||
requested: levels.as_ptr(),
|
||||
highest: 0,
|
||||
};
|
||||
let hr = check(device, 2, (&raw mut query).cast(), size);
|
||||
(hr, query.highest)
|
||||
};
|
||||
let levels = [0xb000, 0xb100, 0xc000, 0xc100, 0xd000];
|
||||
assert_eq!(query(&levels, 0x18), (S_OK, 0xc100));
|
||||
assert_eq!(query(&levels, 0x10).0, E_INVALIDARG);
|
||||
assert_eq!(query(&levels[4..], 0x18).0, UNSUPPORTED);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
//! The DXGI side of the device: one adapter with one output, reached from
|
||||
//! the device by interface query. Tables follow the PC interfaces' order
|
||||
//! (IUnknown, the object methods, then each interface's methods).
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use crate::object::{
|
||||
self, ADAPTER, DXGI_DEVICE, E_INVALIDARG, FACTORY, HRESULT, Iid, NOT_FOUND, OUTPUT, Object,
|
||||
S_OK, Table, This, guid,
|
||||
};
|
||||
|
||||
/// The DXGI device interfaces, base first (as on PC).
|
||||
pub(crate) const DEVICE_IIDS: [Iid; 3] = [
|
||||
guid(
|
||||
0x54ec77fa,
|
||||
0x1377,
|
||||
0x44e6,
|
||||
[0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c],
|
||||
),
|
||||
guid(
|
||||
0x77db970f,
|
||||
0x6276,
|
||||
0x48ba,
|
||||
[0xba, 0x28, 0x07, 0x01, 0x43, 0xb4, 0x39, 0x2c],
|
||||
),
|
||||
guid(
|
||||
0x05008617,
|
||||
0xfbfd,
|
||||
0x4051,
|
||||
[0xa7, 0x90, 0x14, 0x48, 0x84, 0xb4, 0xf6, 0xa9],
|
||||
),
|
||||
];
|
||||
const ADAPTER_IIDS: [Iid; 3] = [
|
||||
guid(
|
||||
0x2411e7e1,
|
||||
0x12ac,
|
||||
0x4ccf,
|
||||
[0xbd, 0x14, 0x97, 0x98, 0xe8, 0x53, 0x4d, 0xc0],
|
||||
),
|
||||
guid(
|
||||
0x29038f61,
|
||||
0x3839,
|
||||
0x4626,
|
||||
[0x91, 0xfd, 0x08, 0x68, 0x79, 0x01, 0x1a, 0x05],
|
||||
),
|
||||
guid(
|
||||
0x0aa1ae0a,
|
||||
0xfa0e,
|
||||
0x4b84,
|
||||
[0x86, 0x44, 0xe0, 0x5f, 0xf8, 0xe5, 0xac, 0xb5],
|
||||
),
|
||||
];
|
||||
const FACTORY_IIDS: [Iid; 3] = [
|
||||
guid(
|
||||
0x7b7166ec,
|
||||
0x21c7,
|
||||
0x44ae,
|
||||
[0xb2, 0x1a, 0xc9, 0xae, 0x32, 0x1a, 0xe3, 0x69],
|
||||
),
|
||||
guid(
|
||||
0x770aae78,
|
||||
0xf26f,
|
||||
0x4dba,
|
||||
[0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87],
|
||||
),
|
||||
guid(
|
||||
0x50c83a1c,
|
||||
0xe072,
|
||||
0x4c48,
|
||||
[0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, 0xd0],
|
||||
),
|
||||
];
|
||||
const OUTPUT_IIDS: [Iid; 1] = [guid(
|
||||
0xae02eedb,
|
||||
0xc735,
|
||||
0x4690,
|
||||
[0x8d, 0x52, 0x5a, 0x8d, 0xc2, 0x02, 0x13, 0xaa],
|
||||
)];
|
||||
|
||||
static DEVICE: Object = Object::new(&DEVICE_FUNCTIONS);
|
||||
static ADAPTER_OBJECT: Object = Object::new(&ADAPTER_FUNCTIONS);
|
||||
static FACTORY_OBJECT: Object = Object::new(&FACTORY_FUNCTIONS);
|
||||
static OUTPUT_OBJECT: Object = Object::new(&OUTPUT_FUNCTIONS);
|
||||
|
||||
pub(crate) fn device() -> This {
|
||||
&DEVICE
|
||||
}
|
||||
|
||||
/// `found` if `iid` is one of `known`.
|
||||
fn query(kind: usize, iid: *const Iid, known: &[Iid], found: This, out: *mut This) -> HRESULT {
|
||||
object::answer(kind, iid, object::is(iid, known).then_some(found), out)
|
||||
}
|
||||
|
||||
/// The DXGI device also answers for the D3D12 device.
|
||||
extern "system" fn device_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
if object::is(iid, &[crate::device::IID]) {
|
||||
return object::answer(DXGI_DEVICE, iid, Some(crate::device::device()), out);
|
||||
}
|
||||
query(DXGI_DEVICE, iid, &DEVICE_IIDS, this, out)
|
||||
}
|
||||
extern "system" fn device_parent(_: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
query(DXGI_DEVICE, iid, &ADAPTER_IIDS, &ADAPTER_OBJECT, out)
|
||||
}
|
||||
extern "system" fn device_adapter(_: This, out: *mut This) -> HRESULT {
|
||||
object::answer(DXGI_DEVICE, &ADAPTER_IIDS[0], Some(&ADAPTER_OBJECT), out)
|
||||
}
|
||||
|
||||
extern "system" fn adapter_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
query(ADAPTER, iid, &ADAPTER_IIDS, this, out)
|
||||
}
|
||||
extern "system" fn adapter_parent(_: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
query(ADAPTER, iid, &FACTORY_IIDS, &FACTORY_OBJECT, out)
|
||||
}
|
||||
extern "system" fn adapter_outputs(_: This, index: u32, out: *mut This) -> HRESULT {
|
||||
if index != 0 {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
object::answer(ADAPTER, &OUTPUT_IIDS[0], Some(&OUTPUT_OBJECT), out)
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct AdapterDescription {
|
||||
name: [u16; 128],
|
||||
vendor: u32,
|
||||
device: u32,
|
||||
subsystem: u32,
|
||||
revision: u32,
|
||||
dedicated_video_memory: usize,
|
||||
dedicated_system_memory: usize,
|
||||
shared_system_memory: usize,
|
||||
luid: [u32; 2],
|
||||
}
|
||||
const _: () = assert!(size_of::<AdapterDescription>() == 0x130);
|
||||
|
||||
const AMD: u32 = 0x1002;
|
||||
const GIB: usize = 1 << 30;
|
||||
|
||||
extern "system" fn adapter_description(_: This, out: *mut AdapterDescription) -> HRESULT {
|
||||
if out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let mut name = [0; 128];
|
||||
for (slot, unit) in name.iter_mut().zip("VIctory console GPU".encode_utf16()) {
|
||||
*slot = unit;
|
||||
}
|
||||
// shortcut: memory sizes are the Series X game split (10 GiB fast,
|
||||
// 3.5 GiB standard), not measured; revisit once memory is emulated.
|
||||
let description = AdapterDescription {
|
||||
name,
|
||||
vendor: AMD,
|
||||
device: 0,
|
||||
subsystem: 0,
|
||||
revision: 0,
|
||||
dedicated_video_memory: 10 * GIB,
|
||||
dedicated_system_memory: 0,
|
||||
shared_system_memory: 7 * GIB / 2,
|
||||
luid: [1, 0],
|
||||
};
|
||||
// SAFETY: checked non-null; the title passes room for the description.
|
||||
unsafe { out.write(description) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn factory_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
query(FACTORY, iid, &FACTORY_IIDS, this, out)
|
||||
}
|
||||
extern "system" fn factory_adapters(_: This, index: u32, out: *mut This) -> HRESULT {
|
||||
if index != 0 {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
object::answer(FACTORY, &ADAPTER_IIDS[0], Some(&ADAPTER_OBJECT), out)
|
||||
}
|
||||
|
||||
extern "system" fn output_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
query(OUTPUT, iid, &OUTPUT_IIDS, this, out)
|
||||
}
|
||||
extern "system" fn output_parent(_: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
query(OUTPUT, iid, &ADAPTER_IIDS, &ADAPTER_OBJECT, out)
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device 5 + 2 + 3.
|
||||
static DEVICE_FUNCTIONS: Table<17> = {
|
||||
let mut f = object::missing_table::<DXGI_DEVICE, 17>();
|
||||
f[0] = device_query as *const ();
|
||||
f[6] = device_parent as *const (); // 0x30
|
||||
f[7] = device_adapter as *const (); // 0x38
|
||||
Table(f)
|
||||
};
|
||||
|
||||
/// IUnknown 3, object 4, adapter 3 + 1 + 1.
|
||||
static ADAPTER_FUNCTIONS: Table<12> = {
|
||||
let mut f = object::missing_table::<ADAPTER, 12>();
|
||||
f[0] = adapter_query as *const ();
|
||||
f[6] = adapter_parent as *const (); // 0x30
|
||||
f[7] = adapter_outputs as *const (); // 0x38
|
||||
f[8] = adapter_description as *const (); // 0x40
|
||||
Table(f)
|
||||
};
|
||||
|
||||
/// IUnknown 3, object 4, factory 5 + 2 + 11.
|
||||
static FACTORY_FUNCTIONS: Table<25> = {
|
||||
let mut f = object::missing_table::<FACTORY, 25>();
|
||||
f[0] = factory_query as *const ();
|
||||
f[7] = factory_adapters as *const (); // 0x38
|
||||
f[12] = factory_adapters as *const (); // 0x60, the same for version 1
|
||||
Table(f)
|
||||
};
|
||||
|
||||
/// IUnknown 3, object 4, output 15 (12 as on PC, then 3 console ones).
|
||||
static OUTPUT_FUNCTIONS: Table<22> = {
|
||||
let mut f = object::missing_table::<OUTPUT, 22>();
|
||||
f[0] = output_query as *const ();
|
||||
f[6] = output_parent as *const (); // 0x30
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::{E_NOINTERFACE, slot};
|
||||
|
||||
type Query = extern "system" fn(This, *const Iid, *mut This) -> HRESULT;
|
||||
type Get = extern "system" fn(This, *mut This) -> HRESULT;
|
||||
type Indexed = extern "system" fn(This, u32, *mut This) -> HRESULT;
|
||||
type Describe = extern "system" fn(This, *mut AdapterDescription) -> HRESULT;
|
||||
|
||||
/// Minecraft's startup: device → DXGI device (newest first) → adapter →
|
||||
/// description, factory, first output.
|
||||
#[test]
|
||||
fn startup_walks_from_device_to_output() {
|
||||
let d3d = crate::device::device();
|
||||
let newest_pc = guid(
|
||||
0x6007896c,
|
||||
0x3244,
|
||||
0x4afd,
|
||||
[0xbf, 0x18, 0xa6, 0xd3, 0xbe, 0xda, 0x50, 0x23],
|
||||
);
|
||||
let mut dxgi = std::ptr::null();
|
||||
let qi = slot::<Query>(d3d, 0);
|
||||
assert_eq!(qi(d3d, &newest_pc, &mut dxgi), E_NOINTERFACE);
|
||||
assert!(dxgi.is_null());
|
||||
assert_eq!(qi(d3d, &DEVICE_IIDS[2], &mut dxgi), S_OK);
|
||||
assert_eq!(dxgi, device());
|
||||
|
||||
let mut adapter = std::ptr::null();
|
||||
assert_eq!(slot::<Get>(dxgi, 0x38)(dxgi, &mut adapter), S_OK);
|
||||
let mut description = std::mem::MaybeUninit::<AdapterDescription>::uninit();
|
||||
assert_eq!(
|
||||
slot::<Describe>(adapter, 0x40)(adapter, description.as_mut_ptr()),
|
||||
S_OK
|
||||
);
|
||||
// SAFETY: written above.
|
||||
assert_eq!(unsafe { description.assume_init() }.vendor, AMD);
|
||||
|
||||
let mut factory = std::ptr::null();
|
||||
let parent = slot::<Query>(adapter, 0x30);
|
||||
assert_eq!(parent(adapter, &FACTORY_IIDS[2], &mut factory), S_OK);
|
||||
let mut again = std::ptr::null();
|
||||
assert_eq!(slot::<Indexed>(factory, 0x38)(factory, 0, &mut again), S_OK);
|
||||
assert_eq!(again, adapter);
|
||||
|
||||
let mut output = std::ptr::null();
|
||||
let outputs = slot::<Indexed>(adapter, 0x38);
|
||||
assert_eq!(outputs(adapter, 0, &mut output), S_OK);
|
||||
assert!(!output.is_null());
|
||||
assert_eq!(outputs(adapter, 1, &mut output), NOT_FOUND);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
//! Fences: a 64-bit value and the events waiting for it. Nothing runs on a
|
||||
//! GPU yet, so only signals (the title's, later our queues') move one.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use crate::object::{self, E_NOTIMPL, FENCE, HRESULT, Iid, Object, S_OK, Table, This, guid};
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
|
||||
pub(crate) const FENCE_IIDS: [Iid; 4] = [
|
||||
guid(
|
||||
0x0a753dcf,
|
||||
0xc4d8,
|
||||
0x4b91,
|
||||
[0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76],
|
||||
),
|
||||
PAGEABLE_IIDS[0],
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
#[repr(C)]
|
||||
struct Fence {
|
||||
object: Object,
|
||||
value: AtomicU64,
|
||||
/// Events to set once the value reaches theirs (handles as integers).
|
||||
waiters: Mutex<Vec<(u64, usize)>>,
|
||||
}
|
||||
|
||||
fn fence<'a>(this: This) -> &'a Fence {
|
||||
// SAFETY: called from fence methods only.
|
||||
unsafe { &*this.cast::<Fence>() }
|
||||
}
|
||||
|
||||
pub(crate) extern "system" fn create(
|
||||
_: This,
|
||||
initial: u64,
|
||||
flags: u32,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
tracing::debug!(initial, flags, "fence");
|
||||
let fence = Box::new(Fence {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
value: AtomicU64::new(initial),
|
||||
waiters: Mutex::new(Vec::new()),
|
||||
});
|
||||
object::hand_out(FENCE, fence, iid, &FENCE_IIDS, out)
|
||||
}
|
||||
|
||||
fn set_event(event: usize) {
|
||||
#[cfg(windows)]
|
||||
// SAFETY: the title passed an event handle.
|
||||
unsafe {
|
||||
windows_sys::Win32::System::Threading::SetEvent(event as *mut c_void)
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let _ = event;
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
object::answer(
|
||||
FENCE,
|
||||
iid,
|
||||
object::is(iid, &FENCE_IIDS).then_some(this),
|
||||
out,
|
||||
)
|
||||
}
|
||||
extern "system" fn release(this: This) -> u32 {
|
||||
object::release_boxed::<Fence>(this)
|
||||
}
|
||||
extern "system" fn completed(this: This) -> u64 {
|
||||
fence(this).value.load(Ordering::Acquire)
|
||||
}
|
||||
extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c_void) -> HRESULT {
|
||||
let fence = fence(this);
|
||||
let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if fence.value.load(Ordering::Acquire) >= value {
|
||||
if !event.is_null() {
|
||||
set_event(event as usize);
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
if event.is_null() {
|
||||
// shortcut: a null event means "block until reached"; nothing can
|
||||
// reach it while no GPU work runs, so fail instead of hanging.
|
||||
tracing::warn!(value, "blocking fence wait not implemented");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
waiters.push((value, event as usize));
|
||||
S_OK
|
||||
}
|
||||
pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
|
||||
let fence = fence(this);
|
||||
let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner());
|
||||
fence.value.store(value, Ordering::Release);
|
||||
waiters.retain(|&(wanted, event)| {
|
||||
let reached = wanted <= value;
|
||||
if reached {
|
||||
set_event(event);
|
||||
}
|
||||
!reached
|
||||
});
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, fence 3.
|
||||
static FUNCTIONS: Table<11> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<FENCE, 11>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
f[8] = completed as *const (); // 0x40
|
||||
f[9] = set_event_on_completion as *const (); // 0x48
|
||||
f[10] = signal as *const (); // 0x50
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::slot;
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn signals_set_waiting_events() {
|
||||
use windows_sys::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0};
|
||||
use windows_sys::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
|
||||
|
||||
let mut f = std::ptr::null();
|
||||
assert_eq!(create(std::ptr::null(), 1, 0, &FENCE_IIDS[0], &mut f), S_OK);
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u64>(f, 0x40)(f), 1);
|
||||
// SAFETY: plain auto-reset event.
|
||||
let event = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) };
|
||||
assert!(!event.is_null());
|
||||
let wait = slot::<extern "system" fn(This, u64, *mut c_void) -> HRESULT>(f, 0x48);
|
||||
let signal = slot::<extern "system" fn(This, u64) -> HRESULT>(f, 0x50);
|
||||
assert_eq!(wait(f, 5, event), S_OK);
|
||||
// SAFETY: a valid event.
|
||||
assert_ne!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0);
|
||||
assert_eq!(signal(f, 5), S_OK);
|
||||
// SAFETY: as above.
|
||||
assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0);
|
||||
assert_eq!(wait(f, 5, event), S_OK, "already reached");
|
||||
// SAFETY: as above.
|
||||
assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0);
|
||||
assert_eq!(wait(f, 9, std::ptr::null_mut()), E_NOTIMPL);
|
||||
// SAFETY: ours.
|
||||
unsafe { CloseHandle(event) };
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(f, 0x10)(f), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//! Frame pacing: the title sets a frame interval and waits for each frame
|
||||
//! to begin. Ours is a clock started by the first interval set, ticking
|
||||
//! once per interval; the token is the frame number.
|
||||
//!
|
||||
//! shortcut: event offsets and display events are not told apart (all
|
||||
//! waits end on the next tick); tie the clock to presentation once frames
|
||||
//! reach the screen.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::object::{HRESULT, S_OK, This};
|
||||
|
||||
/// `HRESULT_FROM_WIN32(WAIT_TIMEOUT)`.
|
||||
const TIMEOUT: HRESULT = 0x8007_0102_u32 as i32;
|
||||
const SIXTIETH: Duration = Duration::from_micros(16_667);
|
||||
|
||||
struct Clock {
|
||||
start: Instant,
|
||||
interval: Duration,
|
||||
}
|
||||
|
||||
static CLOCK: Mutex<Option<Clock>> = Mutex::new(None);
|
||||
static FRAME: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn clock() -> std::sync::MutexGuard<'static, Option<Clock>> {
|
||||
CLOCK.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Device method: `periods` intervals of `length` microseconds per frame.
|
||||
pub(crate) extern "system" fn set_interval(
|
||||
_: This,
|
||||
_output: This,
|
||||
length: u32,
|
||||
periods: u32,
|
||||
_flags: u32,
|
||||
) -> HRESULT {
|
||||
let interval = match u64::from(length) * u64::from(periods.max(1)) {
|
||||
0 => SIXTIETH,
|
||||
us => Duration::from_micros(us),
|
||||
};
|
||||
tracing::info!(?interval, "frame interval");
|
||||
let mut clock = clock();
|
||||
match clock.as_mut() {
|
||||
Some(c) => c.interval = interval,
|
||||
None => {
|
||||
*clock = Some(Clock {
|
||||
start: Instant::now(),
|
||||
interval,
|
||||
})
|
||||
}
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Device method: events are scheduled at every tick.
|
||||
pub(crate) extern "system" fn schedule(
|
||||
_: This,
|
||||
_kind: u32,
|
||||
_offset: u32,
|
||||
_list: *const u8,
|
||||
_flags: u32,
|
||||
) -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// How long until the next tick.
|
||||
fn until_next_tick() -> Duration {
|
||||
let mut clock = clock();
|
||||
let c = clock.get_or_insert_with(|| Clock {
|
||||
start: Instant::now(),
|
||||
interval: SIXTIETH,
|
||||
});
|
||||
let elapsed = c.start.elapsed().as_nanos();
|
||||
let interval = c.interval.as_nanos().max(1);
|
||||
let next = (elapsed / interval + 1) * interval;
|
||||
Duration::from_nanos((next - elapsed) as u64)
|
||||
}
|
||||
|
||||
/// Device method: blocks until the next tick, then hands out the frame's
|
||||
/// token.
|
||||
pub(crate) extern "system" fn wait(
|
||||
_: This,
|
||||
_kind: u32,
|
||||
timeout_ms: u32,
|
||||
_list: *const u8,
|
||||
_flags: u32,
|
||||
token: *mut u64,
|
||||
) -> HRESULT {
|
||||
let wait = until_next_tick();
|
||||
let limit = Duration::from_millis(u64::from(timeout_ms));
|
||||
if wait > limit {
|
||||
std::thread::sleep(limit);
|
||||
return TIMEOUT;
|
||||
}
|
||||
std::thread::sleep(wait);
|
||||
let frame = FRAME.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if !token.is_null() {
|
||||
// SAFETY: checked non-null; the title passes its token.
|
||||
unsafe { token.write(frame) };
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Device method: no statistics are kept, so none are returned.
|
||||
pub(crate) extern "system" fn statistics(
|
||||
_: This,
|
||||
_token: u64,
|
||||
_kinds: u32,
|
||||
count: *mut u32,
|
||||
_out: *mut u8,
|
||||
) -> HRESULT {
|
||||
if !count.is_null() {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { count.write(0) };
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn waits_end_on_ticks_and_count_frames() {
|
||||
let null = std::ptr::null();
|
||||
assert_eq!(set_interval(null, null, 2_000, 1, 0), S_OK);
|
||||
let mut first = 0;
|
||||
assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut first), S_OK);
|
||||
let before = Instant::now();
|
||||
let mut second = 0;
|
||||
assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut second), S_OK);
|
||||
assert!(second > first);
|
||||
assert!(before.elapsed() <= Duration::from_millis(50));
|
||||
assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,603 @@
|
||||
//! The host GPU: one D3D12 device and direct queue (decision 0007), and a
|
||||
//! window to present on.
|
||||
//!
|
||||
//! shortcut: every submission is waited for, so CPU and GPU never overlap;
|
||||
//! overlap them with per-submission fences once more than clears run.
|
||||
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM};
|
||||
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::Win32::Graphics::Dxgi::Common::*;
|
||||
use windows::Win32::Graphics::Dxgi::*;
|
||||
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
|
||||
use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
|
||||
use windows::Win32::UI::WindowsAndMessaging::*;
|
||||
use windows::core::{Interface, PCWSTR, w};
|
||||
|
||||
/// Resource states without the console's own bits (compression hints from
|
||||
/// bit 25 up), which the host rejects.
|
||||
pub(crate) fn pc_state(state: u32) -> u32 {
|
||||
state & 0x01ff_ffff
|
||||
}
|
||||
|
||||
/// A console state as a host texture state: PC bits only, and none of the
|
||||
/// buffer-only ones the console allows on textures (vertex, constant and
|
||||
/// index buffer, stream out, indirect arguments, as in "generic read").
|
||||
pub(crate) fn texture_state(state: u32) -> u32 {
|
||||
const BUFFER_ONLY: u32 = 0x1 | 0x2 | 0x100 | 0x200;
|
||||
pc_state(state) & !BUFFER_ONLY
|
||||
}
|
||||
|
||||
/// Render target views live only until their command is recorded, so a
|
||||
/// ring of host descriptors is enough.
|
||||
const RTV_RING: u32 = 1024;
|
||||
|
||||
pub(crate) struct Host {
|
||||
pub(crate) device: ID3D12Device,
|
||||
queue: ID3D12CommandQueue,
|
||||
fence: ID3D12Fence,
|
||||
/// The last value signalled on `fence`, behind the submission lock.
|
||||
submitted: Mutex<u64>,
|
||||
event: HANDLE,
|
||||
rtvs: ID3D12DescriptorHeap,
|
||||
rtv_size: u32,
|
||||
/// With `VICTORY_D3D12_DEBUG` set: the debug layer's messages.
|
||||
messages: Option<ID3D12InfoQueue>,
|
||||
next_rtv: AtomicU32,
|
||||
presenter: Mutex<Option<Presenter>>,
|
||||
}
|
||||
|
||||
// SAFETY: D3D12 devices, queues, fences and descriptor heaps are
|
||||
// free-threaded; the event handle is only waited on under `submitted`.
|
||||
unsafe impl Send for Host {}
|
||||
// SAFETY: as above.
|
||||
unsafe impl Sync for Host {}
|
||||
|
||||
/// The host GPU, created on first use; `None` without one (a run then
|
||||
/// behaves as before: nothing executes).
|
||||
pub(crate) fn host() -> Option<&'static Host> {
|
||||
static HOST: OnceLock<Option<Host>> = OnceLock::new();
|
||||
HOST.get_or_init(|| match create() {
|
||||
Ok(host) => Some(host),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
|
||||
None
|
||||
}
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
fn create() -> windows::core::Result<Host> {
|
||||
// SAFETY: plain D3D12 object creation with valid descriptions.
|
||||
unsafe {
|
||||
let debug = std::env::var_os("VICTORY_D3D12_DEBUG").is_some();
|
||||
if debug {
|
||||
let mut layer: Option<ID3D12Debug> = None;
|
||||
match D3D12GetDebugInterface(&mut layer) {
|
||||
Ok(()) => layer.into_iter().for_each(|l| l.EnableDebugLayer()),
|
||||
Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
|
||||
}
|
||||
}
|
||||
let mut device: Option<ID3D12Device> = None;
|
||||
D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
|
||||
let device = device.ok_or_else(windows::core::Error::empty)?;
|
||||
let messages = debug
|
||||
.then(|| device.cast::<ID3D12InfoQueue>().ok())
|
||||
.flatten();
|
||||
let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
|
||||
Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
|
||||
..Default::default()
|
||||
})?;
|
||||
let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
|
||||
let event = CreateEventW(None, false, false, None)?;
|
||||
let rtvs: ID3D12DescriptorHeap =
|
||||
device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
|
||||
Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
|
||||
NumDescriptors: RTV_RING,
|
||||
..Default::default()
|
||||
})?;
|
||||
let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
|
||||
tracing::info!("host D3D12 device ready");
|
||||
Ok(Host {
|
||||
device,
|
||||
queue,
|
||||
fence,
|
||||
submitted: Mutex::new(0),
|
||||
event,
|
||||
rtvs,
|
||||
rtv_size,
|
||||
messages,
|
||||
next_rtv: AtomicU32::new(0),
|
||||
presenter: Mutex::new(None),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A host command list and its allocator, always used together.
|
||||
pub(crate) struct HostList {
|
||||
allocator: ID3D12CommandAllocator,
|
||||
pub(crate) list: ID3D12GraphicsCommandList,
|
||||
/// Work for submission time, in recorded order.
|
||||
deferred: Mutex<Deferred>,
|
||||
/// Set when closing failed: the list must not run until reset.
|
||||
broken: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
/// What a list does on the CPU when it is submitted: copies between host
|
||||
/// memory regions (title buffers and upload buffers), and the upload
|
||||
/// buffers its GPU copies read, kept until the list is reset.
|
||||
#[derive(Default)]
|
||||
struct Deferred {
|
||||
/// Destination, source, bytes.
|
||||
copies: Vec<(usize, usize, usize)>,
|
||||
uploads: Vec<ID3D12Resource>,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
/// A new list, open for recording.
|
||||
pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
|
||||
// SAFETY: plain object creation.
|
||||
unsafe {
|
||||
let allocator: ID3D12CommandAllocator = self
|
||||
.device
|
||||
.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
|
||||
let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
|
||||
0,
|
||||
D3D12_COMMAND_LIST_TYPE_DIRECT,
|
||||
&allocator,
|
||||
None,
|
||||
)?;
|
||||
Ok(HostList {
|
||||
allocator,
|
||||
list,
|
||||
deferred: Mutex::default(),
|
||||
broken: Default::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs closed lists and waits for them.
|
||||
pub(crate) fn execute(&self, lists: &[&HostList]) {
|
||||
// A list that failed to close would remove the device.
|
||||
let lists: Vec<&HostList> = lists
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|l| !l.broken.load(Ordering::Relaxed))
|
||||
.collect();
|
||||
for list in &lists {
|
||||
list.run_deferred();
|
||||
}
|
||||
let lists: Vec<Option<ID3D12CommandList>> =
|
||||
lists.iter().map(|l| l.list.cast().ok()).collect();
|
||||
let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
|
||||
*submitted += 1;
|
||||
// SAFETY: closed lists; the fence and event are ours.
|
||||
unsafe {
|
||||
self.queue.ExecuteCommandLists(&lists);
|
||||
let waited = self
|
||||
.queue
|
||||
.Signal(&self.fence, *submitted)
|
||||
.and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
|
||||
match waited {
|
||||
Ok(()) => {
|
||||
WaitForSingleObject(self.event, INFINITE);
|
||||
}
|
||||
Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
|
||||
}
|
||||
}
|
||||
self.log_messages();
|
||||
}
|
||||
|
||||
/// Moves the debug layer's messages into our log.
|
||||
pub(crate) fn log_messages(&self) {
|
||||
let Some(queue) = &self.messages else {
|
||||
return;
|
||||
};
|
||||
// SAFETY: each message is read into a buffer of the size the queue
|
||||
// reports, then the queue is emptied.
|
||||
unsafe {
|
||||
for i in 0..queue.GetNumStoredMessages() {
|
||||
let mut size = 0;
|
||||
if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
|
||||
continue;
|
||||
}
|
||||
let mut buffer = vec![0u64; size.div_ceil(8)];
|
||||
let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
|
||||
if queue.GetMessage(i, Some(message), &mut size).is_ok() {
|
||||
let m = &*message;
|
||||
let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
|
||||
let text = String::from_utf8_lossy(text);
|
||||
tracing::warn!(
|
||||
id = m.ID.0,
|
||||
severity = m.Severity.0,
|
||||
"D3D12: {}",
|
||||
text.trim_end_matches('\0')
|
||||
);
|
||||
}
|
||||
}
|
||||
queue.ClearStoredMessages();
|
||||
}
|
||||
}
|
||||
|
||||
/// A host render target view of `resource`, valid until it is recorded.
|
||||
pub(crate) fn rtv(
|
||||
&self,
|
||||
resource: &ID3D12Resource,
|
||||
desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
|
||||
) -> D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
|
||||
// SAFETY: a slot of our heap and a live resource.
|
||||
unsafe {
|
||||
let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
|
||||
handle.ptr += (slot * self.rtv_size) as usize;
|
||||
self.device
|
||||
.CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
|
||||
handle
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HostList {
|
||||
pub(crate) fn close(&self) {
|
||||
// SAFETY: our list.
|
||||
if let Err(e) = unsafe { self.list.Close() } {
|
||||
self.broken.store(true, Ordering::Relaxed);
|
||||
tracing::warn!(error = %e, "host command list did not close");
|
||||
if let Some(host) = host() {
|
||||
host.log_messages();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Only after the list's last submission finished (every one is waited
|
||||
/// for).
|
||||
pub(crate) fn reset(&self) {
|
||||
*self.deferred() = Deferred::default();
|
||||
self.broken.store(false, Ordering::Relaxed);
|
||||
// SAFETY: the list is not executing.
|
||||
let reset = unsafe {
|
||||
self.allocator
|
||||
.Reset()
|
||||
.and_then(|()| self.list.Reset(&self.allocator, None))
|
||||
};
|
||||
if let Err(e) = reset {
|
||||
tracing::warn!(error = %e, "host command list did not reset");
|
||||
}
|
||||
}
|
||||
|
||||
fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
|
||||
self.deferred.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Copies `len` bytes from `src` to `dst` when the list is submitted.
|
||||
pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
|
||||
self.deferred()
|
||||
.copies
|
||||
.push((dst as usize, src as usize, len));
|
||||
}
|
||||
|
||||
/// A mapped upload buffer of `size` bytes, alive until the list is
|
||||
/// reset.
|
||||
///
|
||||
/// shortcut: one buffer per copy; pool them once uploads are frequent.
|
||||
pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
|
||||
let (buffer, data) = host.upload_buffer(size)?;
|
||||
self.deferred().uploads.push(buffer.clone());
|
||||
Some((buffer, data))
|
||||
}
|
||||
|
||||
fn run_deferred(&self) {
|
||||
for &(dst, src, len) in &self.deferred().copies {
|
||||
// SAFETY: both ranges were checked against their resources when
|
||||
// recorded; titles keep resources alive until their work ends.
|
||||
unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Host {
|
||||
/// A buffer in the upload heap, mapped for writing.
|
||||
fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
|
||||
let heap = D3D12_HEAP_PROPERTIES {
|
||||
Type: D3D12_HEAP_TYPE_UPLOAD,
|
||||
..Default::default()
|
||||
};
|
||||
let desc = D3D12_RESOURCE_DESC {
|
||||
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
|
||||
Width: size.max(1),
|
||||
Height: 1,
|
||||
DepthOrArraySize: 1,
|
||||
MipLevels: 1,
|
||||
SampleDesc: DXGI_SAMPLE_DESC {
|
||||
Count: 1,
|
||||
Quality: 0,
|
||||
},
|
||||
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
|
||||
..Default::default()
|
||||
};
|
||||
let mut buffer: Option<ID3D12Resource> = None;
|
||||
let mut data = std::ptr::null_mut();
|
||||
// SAFETY: plain creation and mapping of an upload buffer.
|
||||
let made = unsafe {
|
||||
self.device
|
||||
.CreateCommittedResource(
|
||||
&heap,
|
||||
D3D12_HEAP_FLAG_NONE,
|
||||
&desc,
|
||||
D3D12_RESOURCE_STATE_GENERIC_READ,
|
||||
None,
|
||||
&mut buffer,
|
||||
)
|
||||
.and_then(|()| {
|
||||
let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
|
||||
b.Map(0, None, Some(&mut data))
|
||||
})
|
||||
};
|
||||
match made {
|
||||
Ok(()) => Some((buffer?, data.cast())),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, size, "no upload buffer");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The swap chain formats a presented texture can be copied into: its own
|
||||
/// family's.
|
||||
fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
|
||||
Some(match format.0 {
|
||||
27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
|
||||
9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
const BUFFERS: u32 = 2;
|
||||
|
||||
struct Presenter {
|
||||
swap_chain: IDXGISwapChain3,
|
||||
width: u32,
|
||||
height: u32,
|
||||
format: DXGI_FORMAT,
|
||||
copy: HostList,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
/// Shows `texture`, which is in `state` (a host state) and stays in it.
|
||||
pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32) {
|
||||
// SAFETY: a live resource.
|
||||
let desc = unsafe { texture.GetDesc() };
|
||||
let Some(format) = swap_format(desc.Format) else {
|
||||
tracing::warn!(format = desc.Format.0, "cannot present this format");
|
||||
return;
|
||||
};
|
||||
let (width, height) = (desc.Width as u32, desc.Height);
|
||||
let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if presenter.is_none() {
|
||||
*presenter = match self.presenter(width, height, format) {
|
||||
Ok(p) => Some(p),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "no swap chain");
|
||||
return;
|
||||
}
|
||||
};
|
||||
}
|
||||
let Some(p) = presenter.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if (p.width, p.height, p.format) != (width, height, format) {
|
||||
// SAFETY: no back buffer is held; every submission was waited for.
|
||||
let resized = unsafe {
|
||||
p.swap_chain
|
||||
.ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
|
||||
};
|
||||
match resized {
|
||||
Ok(()) => (p.width, p.height, p.format) = (width, height, format),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, width, height, "swap chain not resized");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
let state = D3D12_RESOURCE_STATES(state as i32);
|
||||
// SAFETY: our swap chain, list and a live source texture.
|
||||
unsafe {
|
||||
let index = p.swap_chain.GetCurrentBackBufferIndex();
|
||||
let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
|
||||
return;
|
||||
};
|
||||
p.copy.reset();
|
||||
let list = &p.copy.list;
|
||||
list.ResourceBarrier(&[
|
||||
transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
|
||||
transition(
|
||||
&back,
|
||||
D3D12_RESOURCE_STATE_PRESENT,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
),
|
||||
]);
|
||||
list.CopyResource(&back, texture);
|
||||
list.ResourceBarrier(&[
|
||||
transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
|
||||
transition(
|
||||
&back,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
D3D12_RESOURCE_STATE_PRESENT,
|
||||
),
|
||||
]);
|
||||
p.copy.close();
|
||||
self.execute(&[&p.copy]);
|
||||
let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
|
||||
}
|
||||
}
|
||||
|
||||
fn presenter(
|
||||
&self,
|
||||
width: u32,
|
||||
height: u32,
|
||||
format: DXGI_FORMAT,
|
||||
) -> windows::core::Result<Presenter> {
|
||||
let hwnd = match title_window() {
|
||||
Some(hwnd) => hwnd,
|
||||
None => window(width, height)?,
|
||||
};
|
||||
// SAFETY: plain object creation for our window.
|
||||
unsafe {
|
||||
let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
|
||||
let desc = DXGI_SWAP_CHAIN_DESC1 {
|
||||
Width: width,
|
||||
Height: height,
|
||||
Format: format,
|
||||
SampleDesc: DXGI_SAMPLE_DESC {
|
||||
Count: 1,
|
||||
Quality: 0,
|
||||
},
|
||||
BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
|
||||
BufferCount: BUFFERS,
|
||||
SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
|
||||
..Default::default()
|
||||
};
|
||||
let swap_chain = factory
|
||||
.CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
|
||||
.cast::<IDXGISwapChain3>()?;
|
||||
let copy = self.new_list()?;
|
||||
copy.close();
|
||||
tracing::info!(width, height, format = format.0, "presenting to a window");
|
||||
Ok(Presenter {
|
||||
swap_chain,
|
||||
width,
|
||||
height,
|
||||
format,
|
||||
copy,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A visible top-level window of this process: the one the title made, if
|
||||
/// it made one.
|
||||
fn title_window() -> Option<HWND> {
|
||||
extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
|
||||
let mut process = 0;
|
||||
// SAFETY: a window handle from the enumeration; `found` is ours.
|
||||
unsafe {
|
||||
GetWindowThreadProcessId(hwnd, Some(&mut process));
|
||||
if process == windows::Win32::System::Threading::GetCurrentProcessId()
|
||||
&& IsWindowVisible(hwnd).as_bool()
|
||||
{
|
||||
*(found.0 as *mut Option<HWND>) = Some(hwnd);
|
||||
return false.into();
|
||||
}
|
||||
}
|
||||
true.into()
|
||||
}
|
||||
let mut found: Option<HWND> = None;
|
||||
// SAFETY: the callback only writes `found`, which outlives the call.
|
||||
let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
|
||||
found
|
||||
}
|
||||
|
||||
pub(crate) fn transition(
|
||||
resource: &ID3D12Resource,
|
||||
before: D3D12_RESOURCE_STATES,
|
||||
after: D3D12_RESOURCE_STATES,
|
||||
) -> D3D12_RESOURCE_BARRIER {
|
||||
D3D12_RESOURCE_BARRIER {
|
||||
Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
|
||||
Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
|
||||
Anonymous: D3D12_RESOURCE_BARRIER_0 {
|
||||
Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
|
||||
// SAFETY: a borrowed pointer; the barrier never releases it.
|
||||
pResource: unsafe { std::mem::transmute_copy(resource) },
|
||||
Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
|
||||
StateBefore: before,
|
||||
StateAfter: after,
|
||||
}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// A window of the given client size, owned by its own message thread.
|
||||
fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
std::thread::Builder::new()
|
||||
.name("victory-window".into())
|
||||
.spawn(move || {
|
||||
let made = make_window(width, height);
|
||||
let ok = made.is_ok();
|
||||
let _ = sender.send(made.map(|h| h.0 as usize));
|
||||
if ok {
|
||||
pump();
|
||||
}
|
||||
})
|
||||
.map_err(|_| windows::core::Error::empty())?;
|
||||
let hwnd = receiver
|
||||
.recv()
|
||||
.map_err(|_| windows::core::Error::empty())??;
|
||||
Ok(HWND(hwnd as *mut _))
|
||||
}
|
||||
|
||||
extern "system" fn window_proc(
|
||||
hwnd: HWND,
|
||||
message: u32,
|
||||
wparam: WPARAM,
|
||||
lparam: LPARAM,
|
||||
) -> LRESULT {
|
||||
// SAFETY: the default handling for our window.
|
||||
unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
|
||||
}
|
||||
|
||||
fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
|
||||
const CLASS: PCWSTR = w!("VIctory");
|
||||
// SAFETY: registers our class once and creates a window of it.
|
||||
unsafe {
|
||||
let instance = GetModuleHandleW(None)?;
|
||||
let class = WNDCLASSEXW {
|
||||
cbSize: size_of::<WNDCLASSEXW>() as u32,
|
||||
lpfnWndProc: Some(window_proc),
|
||||
hInstance: instance.into(),
|
||||
lpszClassName: CLASS,
|
||||
hCursor: LoadCursorW(None, IDC_ARROW)?,
|
||||
..Default::default()
|
||||
};
|
||||
RegisterClassExW(&class);
|
||||
let mut rect = RECT {
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: width as i32,
|
||||
bottom: height as i32,
|
||||
};
|
||||
AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
|
||||
CreateWindowExW(
|
||||
WINDOW_EX_STYLE(0),
|
||||
CLASS,
|
||||
w!("VIctory"),
|
||||
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
|
||||
CW_USEDEFAULT,
|
||||
CW_USEDEFAULT,
|
||||
rect.right - rect.left,
|
||||
rect.bottom - rect.top,
|
||||
None,
|
||||
None,
|
||||
Some(instance.into()),
|
||||
None,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn pump() {
|
||||
let mut message = MSG::default();
|
||||
// SAFETY: the standard message loop of this thread's window.
|
||||
unsafe {
|
||||
while GetMessageW(&mut message, None, 0, 0).as_bool() {
|
||||
let _ = TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,31 @@
|
||||
//! D3D12.X on host D3D12.
|
||||
//!
|
||||
//! D3D12.X records many commands by writing command-processor packets into
|
||||
//! command lists from code inlined into the title itself, so no import-level
|
||||
//! hook sees them. This crate decodes those packet streams at
|
||||
//! `ExecuteCommandLists` time and replays them on host D3D12, and maps the
|
||||
//! title's GPU virtual addresses (console memory is unified) to host
|
||||
//! resources.
|
||||
//! D3D12.X records commands from code inlined into the title, which writes
|
||||
//! packets into the command list while its put pointer is below a limit and
|
||||
//! calls the list's method otherwise. Our lists keep the limits at zero, so
|
||||
//! every command arrives here as a call, to be run on host D3D12. The
|
||||
//! title's GPU addresses are CPU addresses (console memory is unified).
|
||||
//!
|
||||
//! Planned modules: `packets` (stream decoder), `memory` (title GPU
|
||||
//! addresses to host heaps), `pipeline` (PSOs from `victory-shader` output),
|
||||
//! `present` (swap chain, frame pacing).
|
||||
//! [`device`] is the device object titles create, [`dxgi`] its adapter side,
|
||||
//! [`resource`] heaps and resources, [`fence`] fences, [`queue`] command
|
||||
//! queues, [`list`] command allocators and lists, [`descriptor`]
|
||||
//! descriptor heaps, [`root`] root signatures, [`query`] query heaps,
|
||||
//! [`signature`] command signatures, [`pipeline`] pipeline states,
|
||||
//! [`frame`] frame pacing, [`object`] what all console graphics objects
|
||||
//! share. Planned: `present` (swap chain).
|
||||
|
||||
pub mod descriptor;
|
||||
pub mod device;
|
||||
pub mod dxgi;
|
||||
pub mod fence;
|
||||
pub mod frame;
|
||||
#[cfg(windows)]
|
||||
mod host;
|
||||
pub mod list;
|
||||
pub mod object;
|
||||
pub mod pipeline;
|
||||
pub mod query;
|
||||
pub mod queue;
|
||||
pub mod resource;
|
||||
pub mod root;
|
||||
pub mod signature;
|
||||
@@ -0,0 +1,678 @@
|
||||
//! Command allocators and command lists.
|
||||
//!
|
||||
//! The title's inlined code writes packets into a list only while its put
|
||||
//! pointer is below a limit, and calls the list's method otherwise. Our
|
||||
//! lists keep the pointer and every limit at zero, so every command reaches
|
||||
//! the table as a call.
|
||||
//!
|
||||
//! shortcut: the methods record nothing yet; unwritten ones log once, so a
|
||||
//! run lists what to translate. Translate them onto host command lists
|
||||
//! (TODO.md, GPU).
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::mem::offset_of;
|
||||
|
||||
use crate::object::{
|
||||
self, ALLOCATOR, E_INVALIDARG, HRESULT, Iid, LIST, Object, S_OK, Table, This, guid,
|
||||
};
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
|
||||
const ALLOCATOR_IIDS: [Iid; 4] = [
|
||||
guid(
|
||||
0x6102dee4,
|
||||
0xaf59,
|
||||
0x4b09,
|
||||
[0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24],
|
||||
),
|
||||
PAGEABLE_IIDS[0],
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
/// The list interfaces whose ids are the same as on PC, then the device
|
||||
/// child's.
|
||||
const LIST_IIDS: [Iid; 8] = [
|
||||
guid(
|
||||
0x7116d91c,
|
||||
0xe7e4,
|
||||
0x47ce,
|
||||
[0xb8, 0xc6, 0xec, 0x81, 0x68, 0xf4, 0x37, 0xe5],
|
||||
),
|
||||
guid(
|
||||
0x5b160d0f,
|
||||
0xac1b,
|
||||
0x4185,
|
||||
[0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55],
|
||||
),
|
||||
guid(
|
||||
0x553103fb,
|
||||
0x1fe7,
|
||||
0x4557,
|
||||
[0xbb, 0x38, 0x94, 0x6d, 0x7d, 0x0e, 0x7c, 0xa7],
|
||||
),
|
||||
guid(
|
||||
0x38c3e585,
|
||||
0xff17,
|
||||
0x412c,
|
||||
[0x91, 0x50, 0x4f, 0xc6, 0xf9, 0xd7, 0x2a, 0x28],
|
||||
),
|
||||
guid(
|
||||
0x6fda83a7,
|
||||
0xb84c,
|
||||
0x4e38,
|
||||
[0x9a, 0xc8, 0xc7, 0xbd, 0x22, 0x01, 0x6b, 0x3d],
|
||||
),
|
||||
guid(
|
||||
0x8754318e,
|
||||
0xd3a9,
|
||||
0x4541,
|
||||
[0x98, 0xcf, 0x64, 0x5b, 0x50, 0xdc, 0x48, 0x74],
|
||||
),
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
#[repr(C)]
|
||||
struct Allocator {
|
||||
object: Object,
|
||||
kind: u32,
|
||||
}
|
||||
|
||||
/// The layout the title's inlined code reads.
|
||||
#[repr(C)]
|
||||
struct List {
|
||||
object: Object,
|
||||
kind: u32,
|
||||
/// The put pointer, then the plain, draw, API and unbiased API limits:
|
||||
/// all zero, so every inline check fails.
|
||||
put: [u64; 5],
|
||||
reserved: [u32; 64],
|
||||
/// State the inline code keeps for building packets; unused by us.
|
||||
graphics_root_headers: [u32; 128],
|
||||
compute_root_headers: [u32; 128],
|
||||
pipeline_shadow: [u32; 8],
|
||||
/// Ours, after the console layout: the host list the calls record
|
||||
/// into (decision 0007).
|
||||
#[cfg(windows)]
|
||||
host: Option<crate::host::HostList>,
|
||||
}
|
||||
const _: () = assert!(offset_of!(List, put) == 0x18);
|
||||
const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560);
|
||||
|
||||
/// The host list behind a title list, if there is a host GPU.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> {
|
||||
if this.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the title passes one of our lists.
|
||||
unsafe { (*this.cast::<List>()).host.as_ref() }
|
||||
}
|
||||
|
||||
pub(crate) extern "system" fn create_allocator(
|
||||
_: This,
|
||||
kind: u32,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
let allocator = Box::new(Allocator {
|
||||
object: Object::new(&ALLOCATOR_FUNCTIONS),
|
||||
kind,
|
||||
});
|
||||
object::hand_out(ALLOCATOR, allocator, iid, &ALLOCATOR_IIDS, out)
|
||||
}
|
||||
|
||||
/// Lists start open, as in D3D12.
|
||||
pub(crate) extern "system" fn create_list(
|
||||
_: This,
|
||||
_nodes: u32,
|
||||
kind: u32,
|
||||
allocator: This,
|
||||
_pipeline: This,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
new_list(kind, allocator, iid, out)
|
||||
}
|
||||
|
||||
/// The console's list creation: type, flags, node mask and barrier batch
|
||||
/// size in a description.
|
||||
#[repr(C)]
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ListDesc {
|
||||
kind: u32,
|
||||
flags: u32,
|
||||
nodes: u32,
|
||||
barrier_batch: u32,
|
||||
}
|
||||
|
||||
pub(crate) extern "system" fn create_list_x(
|
||||
_: This,
|
||||
desc: *const ListDesc,
|
||||
allocator: This,
|
||||
_pipeline: This,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
tracing::debug!(?desc, "console command list");
|
||||
new_list(desc.kind, allocator, iid, out)
|
||||
}
|
||||
|
||||
fn new_list(kind: u32, allocator: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
if allocator.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
tracing::debug!(kind, "command list");
|
||||
let list = Box::new(List {
|
||||
object: Object::new(&LIST_FUNCTIONS),
|
||||
kind,
|
||||
put: [0; 5],
|
||||
reserved: [0; 64],
|
||||
graphics_root_headers: [0; 128],
|
||||
compute_root_headers: [0; 128],
|
||||
pipeline_shadow: [0; 8],
|
||||
#[cfg(windows)]
|
||||
host: crate::host::host().and_then(|h| match h.new_list() {
|
||||
Ok(list) => Some(list),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "no host command list");
|
||||
None
|
||||
}
|
||||
}),
|
||||
});
|
||||
object::hand_out(LIST, list, iid, &LIST_IIDS, out)
|
||||
}
|
||||
|
||||
extern "system" fn allocator_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let found = object::is(iid, &ALLOCATOR_IIDS).then_some(this);
|
||||
object::answer(ALLOCATOR, iid, found, out)
|
||||
}
|
||||
extern "system" fn allocator_release(this: This) -> u32 {
|
||||
object::release_boxed::<Allocator>(this)
|
||||
}
|
||||
/// Nothing is recorded, so there is nothing to free.
|
||||
extern "system" fn allocator_reset(_: This) -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn list_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
object::answer(LIST, iid, object::is(iid, &LIST_IIDS).then_some(this), out)
|
||||
}
|
||||
extern "system" fn list_release(this: This) -> u32 {
|
||||
object::release_boxed::<List>(this)
|
||||
}
|
||||
extern "system" fn list_type(this: This) -> u32 {
|
||||
// SAFETY: `this` is one of our lists.
|
||||
unsafe { (*this.cast::<List>()).kind }
|
||||
}
|
||||
extern "system" fn close(this: This) -> HRESULT {
|
||||
#[cfg(windows)]
|
||||
if let Some(host) = host_list(this) {
|
||||
host.close();
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
extern "system" fn reset(this: This, allocator: This, _pipeline: This) -> HRESULT {
|
||||
if allocator.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if let Some(host) = host_list(this) {
|
||||
host.reset();
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// A resource barrier as titles pass it: type, flags, then a resource and
|
||||
/// either a subresource and two states (transition) or a second resource
|
||||
/// (aliasing). The same layout as the host's.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct Barrier {
|
||||
kind: u32,
|
||||
flags: u32,
|
||||
first: This,
|
||||
second: u64,
|
||||
last: u64,
|
||||
}
|
||||
|
||||
/// The barrier on host resources, or `None` if it names a resource the host
|
||||
/// GPU does not have (buffers so far).
|
||||
#[cfg(windows)]
|
||||
fn host_barrier(b: &Barrier) -> Option<Barrier> {
|
||||
use windows::core::Interface;
|
||||
let host = |r: This| crate::resource::host_resource(r).map(|h| h.as_raw().cast_const().cast());
|
||||
match b.kind {
|
||||
0 => {
|
||||
// A split barrier's first half: its second half transitions.
|
||||
const BEGIN_ONLY: u32 = 1;
|
||||
if b.flags & BEGIN_ONLY != 0 {
|
||||
return None;
|
||||
}
|
||||
// shortcut: whole resources, from the state we tracked (see
|
||||
// `host_transition`); subresources are not told apart.
|
||||
let wanted = crate::host::texture_state(b.last as u32);
|
||||
let (resource, before) = crate::resource::host_transition(b.first, wanted)?;
|
||||
Some(Barrier {
|
||||
kind: 0,
|
||||
flags: 0,
|
||||
first: resource.cast_const().cast(),
|
||||
second: 0xffff_ffff | (u64::from(before) << 32),
|
||||
last: u64::from(wanted),
|
||||
})
|
||||
}
|
||||
1 => Some(Barrier {
|
||||
first: if b.first.is_null() {
|
||||
b.first
|
||||
} else {
|
||||
host(b.first)?
|
||||
},
|
||||
second: if b.second == 0 {
|
||||
0
|
||||
} else {
|
||||
host(b.second as This)? as u64
|
||||
},
|
||||
..*b
|
||||
}),
|
||||
2 => Some(Barrier {
|
||||
first: if b.first.is_null() {
|
||||
b.first
|
||||
} else {
|
||||
host(b.first)?
|
||||
},
|
||||
..*b
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the console's barrier "actions" (none).
|
||||
extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 {
|
||||
#[cfg(windows)]
|
||||
if let Some(list) = host_list(this)
|
||||
&& !barriers.is_null()
|
||||
{
|
||||
// SAFETY: the title passes `count` barriers.
|
||||
let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) };
|
||||
let host: Vec<Barrier> = barriers.iter().filter_map(host_barrier).collect();
|
||||
if !host.is_empty() {
|
||||
use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
|
||||
const _: () = assert!(size_of::<Barrier>() == size_of::<D3D12_RESOURCE_BARRIER>());
|
||||
// SAFETY: the same layout; borrowed resource pointers, never
|
||||
// released through this slice.
|
||||
let host = unsafe {
|
||||
std::slice::from_raw_parts(
|
||||
host.as_ptr().cast::<D3D12_RESOURCE_BARRIER>(),
|
||||
host.len(),
|
||||
)
|
||||
};
|
||||
// SAFETY: an open list and live resources.
|
||||
unsafe { list.list.ResourceBarrier(host) };
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
/// Moves a title texture's host copy to `state` in the list, if needed.
|
||||
#[cfg(windows)]
|
||||
fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) {
|
||||
use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
|
||||
if let Some(texture) = crate::resource::host_resource(resource)
|
||||
&& let Some((_, before)) = crate::resource::host_transition(resource, state)
|
||||
{
|
||||
let barrier = crate::host::transition(texture, State(before as i32), State(state as i32));
|
||||
// SAFETY: an open list and a live texture.
|
||||
unsafe { list.list.ResourceBarrier(&[barrier]) };
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
const COPY_DEST: u32 = 0x400;
|
||||
#[cfg(windows)]
|
||||
const COPY_SOURCE: u32 = 0x800;
|
||||
|
||||
/// `len` bytes at `offset` of a title buffer, if they are inside it.
|
||||
#[cfg(windows)]
|
||||
fn buffer_range(buffer: This, offset: u64, len: u64) -> Option<*mut u8> {
|
||||
let (data, size) = crate::resource::buffer_bytes(buffer)?;
|
||||
let end = offset.checked_add(len)?;
|
||||
if end > size {
|
||||
tracing::warn!(offset, len, size, "copy outside its buffer");
|
||||
return None;
|
||||
}
|
||||
// SAFETY: inside the buffer, checked above.
|
||||
Some(unsafe { data.add(offset as usize) })
|
||||
}
|
||||
|
||||
/// Buffer to buffer: both are host memory, copied at submission.
|
||||
extern "system" fn copy_buffer_region(
|
||||
this: This,
|
||||
dst: This,
|
||||
dst_offset: u64,
|
||||
src: This,
|
||||
src_offset: u64,
|
||||
len: u64,
|
||||
) {
|
||||
#[cfg(windows)]
|
||||
if let Some(list) = host_list(this)
|
||||
&& let Some(to) = buffer_range(dst, dst_offset, len)
|
||||
&& let Some(from) = buffer_range(src, src_offset, len)
|
||||
{
|
||||
list.defer_copy(to, from, len as usize);
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (this, dst, dst_offset, src, src_offset, len);
|
||||
}
|
||||
|
||||
extern "system" fn copy_resource(this: This, dst: This, src: This) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let Some(list) = host_list(this) else {
|
||||
return;
|
||||
};
|
||||
if let (Some(to), Some(from)) = (
|
||||
crate::resource::host_resource(dst),
|
||||
crate::resource::host_resource(src),
|
||||
) {
|
||||
ensure_state(list, dst, COPY_DEST);
|
||||
ensure_state(list, src, COPY_SOURCE);
|
||||
// SAFETY: an open list and live textures.
|
||||
unsafe { list.list.CopyResource(to, from) };
|
||||
} else if let (Some((to, a)), Some((from, b))) = (
|
||||
crate::resource::buffer_bytes(dst),
|
||||
crate::resource::buffer_bytes(src),
|
||||
) {
|
||||
list.defer_copy(to, from, a.min(b) as usize);
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (this, dst, src);
|
||||
}
|
||||
|
||||
extern "system" fn copy_resource_x(this: This, dst: This, src: This, _flags: u32) {
|
||||
copy_resource(this, dst, src);
|
||||
}
|
||||
|
||||
/// A copy location as titles pass it, laid out as the host's: a resource,
|
||||
/// then a subresource index (type 0) or a placed footprint (type 1).
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct CopyLocation {
|
||||
resource: This,
|
||||
kind: u32,
|
||||
footprint: crate::resource::PlacedFootprint,
|
||||
}
|
||||
|
||||
/// Texture to texture on the GPU; buffer to texture through an upload
|
||||
/// buffer filled at submission. Texture to buffer (read back) is not done
|
||||
/// yet.
|
||||
extern "system" fn copy_texture_region(
|
||||
this: This,
|
||||
dst: *const CopyLocation,
|
||||
x: u32,
|
||||
y: u32,
|
||||
z: u32,
|
||||
src: *const CopyLocation,
|
||||
source_box: *const [u32; 6],
|
||||
) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows::Win32::Graphics::Direct3D12::{D3D12_BOX, D3D12_TEXTURE_COPY_LOCATION};
|
||||
use windows::core::Interface;
|
||||
const FOOTPRINT: u32 = 1;
|
||||
// SAFETY: the title passes both locations (null is tolerated).
|
||||
let (Some(list), Some(&dst), Some(&src)) =
|
||||
(host_list(this), unsafe { dst.as_ref() }, unsafe {
|
||||
src.as_ref()
|
||||
})
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(to) = crate::resource::host_resource(dst.resource) else {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| tracing::warn!("texture to buffer copies not implemented"));
|
||||
return;
|
||||
};
|
||||
let mut from = src;
|
||||
let _upload; // keeps the source alive while this call records it
|
||||
if src.kind == FOOTPRINT {
|
||||
let (Some(host), Some(bytes)) = (crate::host::host(), src.footprint.bytes()) else {
|
||||
return;
|
||||
};
|
||||
let Some(data) = buffer_range(src.resource, src.footprint.offset, bytes) else {
|
||||
return;
|
||||
};
|
||||
let Some((buffer, staging)) = list.upload(host, bytes) else {
|
||||
return;
|
||||
};
|
||||
list.defer_copy(staging, data, bytes as usize);
|
||||
from.resource = buffer.as_raw().cast_const().cast();
|
||||
from.footprint.offset = 0;
|
||||
_upload = buffer;
|
||||
} else {
|
||||
let Some(texture) = crate::resource::host_resource(src.resource) else {
|
||||
return;
|
||||
};
|
||||
ensure_state(list, src.resource, COPY_SOURCE);
|
||||
from.resource = texture.as_raw().cast_const().cast();
|
||||
}
|
||||
ensure_state(list, dst.resource, COPY_DEST);
|
||||
let mut to_location = dst;
|
||||
to_location.resource = to.as_raw().cast_const().cast();
|
||||
let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>());
|
||||
const _: () =
|
||||
assert!(size_of::<CopyLocation>() == size_of::<D3D12_TEXTURE_COPY_LOCATION>());
|
||||
// SAFETY: an open list; both locations in the host's layout, naming
|
||||
// live resources; the box is the title's (same layout).
|
||||
unsafe {
|
||||
list.list.CopyTextureRegion(
|
||||
(&raw const to_location).cast(),
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
(&raw const from).cast(),
|
||||
host_box,
|
||||
)
|
||||
};
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (this, dst, x, y, z, src, source_box);
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)] // the method's own arguments
|
||||
extern "system" fn copy_texture_region_x(
|
||||
this: This,
|
||||
dst: *const CopyLocation,
|
||||
x: u32,
|
||||
y: u32,
|
||||
z: u32,
|
||||
src: *const CopyLocation,
|
||||
source_box: *const [u32; 6],
|
||||
_flags: u32,
|
||||
) {
|
||||
copy_texture_region(this, dst, x, y, z, src, source_box);
|
||||
}
|
||||
|
||||
extern "system" fn resolve(
|
||||
this: This,
|
||||
dst: This,
|
||||
dst_sub: u32,
|
||||
src: This,
|
||||
src_sub: u32,
|
||||
format: u32,
|
||||
) {
|
||||
#[cfg(windows)]
|
||||
if let Some(list) = host_list(this)
|
||||
&& let (Some(to), Some(from)) = (
|
||||
crate::resource::host_resource(dst),
|
||||
crate::resource::host_resource(src),
|
||||
)
|
||||
{
|
||||
use windows::Win32::Foundation::RECT;
|
||||
use windows::Win32::Graphics::Direct3D12::{
|
||||
D3D12_RESOLVE_MODE_AVERAGE, ID3D12GraphicsCommandList1,
|
||||
};
|
||||
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
|
||||
use windows::core::Interface;
|
||||
const RESOLVE_DEST: u32 = 0x1000;
|
||||
const RESOLVE_SOURCE: u32 = 0x2000;
|
||||
ensure_state(list, dst, RESOLVE_DEST);
|
||||
ensure_state(list, src, RESOLVE_SOURCE);
|
||||
// SAFETY: an open list and live textures; the region is inside both.
|
||||
unsafe {
|
||||
let (a, b) = (to.GetDesc(), from.GetDesc());
|
||||
let format = DXGI_FORMAT(format as i32);
|
||||
if (a.Width, a.Height) == (b.Width, b.Height) {
|
||||
list.list
|
||||
.ResolveSubresource(to, dst_sub, from, src_sub, format);
|
||||
} else if let Ok(list1) = list.list.cast::<ID3D12GraphicsCommandList1>() {
|
||||
// The console clips a larger source to the destination.
|
||||
let rect = RECT {
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: a.Width.min(b.Width) as i32,
|
||||
bottom: a.Height.min(b.Height) as i32,
|
||||
};
|
||||
list1.ResolveSubresourceRegion(
|
||||
to,
|
||||
dst_sub,
|
||||
0,
|
||||
0,
|
||||
from,
|
||||
src_sub,
|
||||
Some(&rect),
|
||||
format,
|
||||
D3D12_RESOLVE_MODE_AVERAGE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (this, dst, dst_sub, src, src_sub, format);
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub(crate) struct Rect {
|
||||
left: i32,
|
||||
top: i32,
|
||||
right: i32,
|
||||
bottom: i32,
|
||||
}
|
||||
|
||||
extern "system" fn clear_rtv(
|
||||
this: This,
|
||||
handle: u64,
|
||||
color: *const [f32; 4],
|
||||
count: u32,
|
||||
rects: *const Rect,
|
||||
) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let (Some(list), Some(record)) = (host_list(this), crate::descriptor::rtv_record(handle))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let (Some(texture), Some(host)) = (
|
||||
crate::resource::host_resource(record.resource),
|
||||
crate::host::host(),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
// SAFETY: the title passes four floats (null is tolerated).
|
||||
let Some(color) = (unsafe { color.as_ref() }) else {
|
||||
return;
|
||||
};
|
||||
let rects = (count > 0 && !rects.is_null()).then(|| {
|
||||
// SAFETY: the title passes `count` rectangles, laid out as the host's.
|
||||
unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) }
|
||||
});
|
||||
const RENDER_TARGET: u32 = 0x4;
|
||||
let rtv = host.rtv(texture, record.desc().as_ref());
|
||||
// SAFETY: an open list, a fresh view of a live texture.
|
||||
unsafe {
|
||||
if let Some((_, before)) =
|
||||
crate::resource::host_transition(record.resource, RENDER_TARGET)
|
||||
{
|
||||
use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
|
||||
list.list.ResourceBarrier(&[crate::host::transition(
|
||||
texture,
|
||||
State(before as i32),
|
||||
State(RENDER_TARGET as i32),
|
||||
)]);
|
||||
}
|
||||
list.list.ClearRenderTargetView(rtv, color, rects);
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (this, handle, color, count, rects);
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, allocator 2.
|
||||
static ALLOCATOR_FUNCTIONS: Table<10> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<ALLOCATOR, 10>());
|
||||
f[0] = allocator_query as *const ();
|
||||
f[2] = allocator_release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
f[8] = allocator_reset as *const (); // 0x40
|
||||
f[9] = object::ignore as *const (); // 0x48 allocation callback
|
||||
Table(f)
|
||||
};
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, list 1, graphics list 96 (59 as
|
||||
/// on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3 + 13).
|
||||
static LIST_FUNCTIONS: Table<140> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<LIST, 140>());
|
||||
f[0] = list_query as *const ();
|
||||
f[2] = list_release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
f[8] = list_type as *const (); // 0x40
|
||||
f[9] = close as *const (); // 0x48
|
||||
f[10] = reset as *const (); // 0x50
|
||||
f[15] = copy_buffer_region as *const (); // 0x78
|
||||
f[16] = copy_texture_region as *const (); // 0x80
|
||||
f[17] = copy_resource as *const (); // 0x88
|
||||
f[19] = resolve as *const (); // 0x98
|
||||
f[26] = barrier as *const (); // 0xd0
|
||||
f[83] = copy_texture_region_x as *const (); // 0x298
|
||||
f[84] = copy_resource_x as *const (); // 0x2a0
|
||||
f[52] = clear_rtv as *const (); // 0x1a0
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::slot;
|
||||
|
||||
#[test]
|
||||
fn every_inline_command_falls_back_to_the_table() {
|
||||
let null = std::ptr::null();
|
||||
let mut allocator = null;
|
||||
assert_eq!(
|
||||
create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator),
|
||||
S_OK
|
||||
);
|
||||
let mut list = null;
|
||||
let hr = create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list);
|
||||
assert_eq!(hr, S_OK);
|
||||
// What the title's inline draw checks: put < draw limit.
|
||||
// SAFETY: the list is 0x560 bytes.
|
||||
let (put, draw_limit, api_limit) = unsafe {
|
||||
let at = |o: usize| list.cast::<u8>().add(o).cast::<u64>().read();
|
||||
(at(0x18), at(0x28), at(0x30))
|
||||
};
|
||||
assert!(put >= draw_limit && put >= api_limit);
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x40)(list), 0);
|
||||
assert_eq!(
|
||||
slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list),
|
||||
S_OK
|
||||
);
|
||||
let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o);
|
||||
assert_eq!(release(list), 0);
|
||||
assert_eq!(release(allocator), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
//! What every console graphics object starts with: a function table
|
||||
//! pointer, bookkeeping bits and a reference count. Tables begin with
|
||||
//! IUnknown's three slots. Our objects are static and never destroyed.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||
|
||||
pub type HRESULT = i32;
|
||||
pub const S_OK: HRESULT = 0;
|
||||
pub(crate) const S_FALSE: HRESULT = 1;
|
||||
pub(crate) const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32;
|
||||
pub(crate) const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32;
|
||||
pub(crate) const E_POINTER: HRESULT = 0x8000_4003_u32 as i32;
|
||||
pub(crate) const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32;
|
||||
pub(crate) const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
|
||||
/// What D3D and DXGI return for a missing item (adapter, output, private
|
||||
/// data).
|
||||
pub(crate) const NOT_FOUND: HRESULT = 0x887A_0002_u32 as i32;
|
||||
const MORE_DATA: HRESULT = 0x887A_0003_u32 as i32;
|
||||
|
||||
pub type Iid = [u8; 16];
|
||||
|
||||
/// An interface id from its text form's fields, in memory order.
|
||||
pub const fn guid(a: u32, b: u16, c: u16, d: [u8; 8]) -> Iid {
|
||||
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],
|
||||
]
|
||||
}
|
||||
|
||||
pub fn guid_text(g: &Iid) -> String {
|
||||
let a = u32::from_le_bytes([g[0], g[1], g[2], g[3]]);
|
||||
let b = u16::from_le_bytes([g[4], g[5]]);
|
||||
let c = u16::from_le_bytes([g[6], g[7]]);
|
||||
let d: String = g[8..].iter().map(|x| format!("{x:02x}")).collect();
|
||||
format!("{a:08x}-{b:04x}-{c:04x}-{}-{}", &d[..4], &d[4..])
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Object {
|
||||
functions: *const *const (),
|
||||
/// Device index (bits 0-2) and bookkeeping bits; all zero.
|
||||
bits: u32,
|
||||
refs: AtomicU32,
|
||||
}
|
||||
// SAFETY: the table is static and immutable; the count is atomic.
|
||||
unsafe impl Sync for Object {}
|
||||
|
||||
impl Object {
|
||||
pub(crate) const fn new<const N: usize>(table: &'static Table<N>) -> Self {
|
||||
Object {
|
||||
functions: table.0.as_ptr(),
|
||||
bits: 0,
|
||||
refs: AtomicU32::new(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) type This = *const Object;
|
||||
|
||||
#[repr(transparent)]
|
||||
pub(crate) struct Table<const N: usize>(pub [*const (); N]);
|
||||
// SAFETY: function addresses only.
|
||||
unsafe impl<const N: usize> Sync for Table<N> {}
|
||||
|
||||
pub(crate) extern "system" fn add_ref(this: This) -> u32 {
|
||||
// SAFETY: `this` is one of our objects.
|
||||
unsafe { &*this }.refs.fetch_add(1, Ordering::Relaxed) + 1
|
||||
}
|
||||
|
||||
pub(crate) extern "system" fn release(this: This) -> u32 {
|
||||
// SAFETY: `this` is one of our objects.
|
||||
let refs = &unsafe { &*this }.refs;
|
||||
let _ = refs.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_sub(1));
|
||||
refs.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Answers an interface query (or any call handing out an object): a new
|
||||
/// reference to `found`, or null and `E_NOINTERFACE`.
|
||||
pub(crate) fn answer(kind: usize, iid: *const Iid, found: Option<This>, out: *mut This) -> HRESULT {
|
||||
if out.is_null() {
|
||||
return E_POINTER;
|
||||
}
|
||||
let hr = match found {
|
||||
Some(object) => {
|
||||
add_ref(object);
|
||||
// SAFETY: checked non-null; the title passes room for a pointer.
|
||||
unsafe { out.write(object) };
|
||||
return S_OK;
|
||||
}
|
||||
None => E_NOINTERFACE,
|
||||
};
|
||||
// SAFETY: the title passes an interface id (null is tolerated).
|
||||
let iid = unsafe { iid.as_ref() }.map(guid_text).unwrap_or_default();
|
||||
tracing::warn!(object = KINDS[kind], %iid, "unknown interface");
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(std::ptr::null()) };
|
||||
hr
|
||||
}
|
||||
|
||||
/// Whether `iid` is one of `known`.
|
||||
pub(crate) fn is(iid: *const Iid, known: &[Iid]) -> bool {
|
||||
// SAFETY: the title passes an interface id (null is tolerated).
|
||||
unsafe { iid.as_ref() }.is_some_and(|i| known.contains(i))
|
||||
}
|
||||
|
||||
/// Hands a new object to the title as one of `known`, or drops it. `T`
|
||||
/// starts with its `Object`; its table's release slot is
|
||||
/// [`release_boxed::<T>`].
|
||||
pub(crate) fn hand_out<T>(
|
||||
kind: usize,
|
||||
object: Box<T>,
|
||||
iid: *const Iid,
|
||||
known: &[Iid],
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
if !is(iid, known) {
|
||||
return answer(kind, iid, None, out);
|
||||
}
|
||||
if out.is_null() {
|
||||
// Asked only whether creation would succeed.
|
||||
return S_FALSE;
|
||||
}
|
||||
answer(kind, iid, Some(Box::into_raw(object).cast()), out)
|
||||
}
|
||||
|
||||
/// Release for objects made by [`hand_out`]: the last reference frees it.
|
||||
pub(crate) fn release_boxed<T>(this: This) -> u32 {
|
||||
// SAFETY: `this` is the header of a boxed `T`.
|
||||
let refs = &unsafe { &*this }.refs;
|
||||
match refs.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1)) {
|
||||
Ok(1) => {
|
||||
private_data().retain(|&(object, _), _| object != this as usize);
|
||||
// SAFETY: that was the last reference to a `Box<T>`.
|
||||
drop(unsafe { Box::from_raw(this.cast_mut().cast::<T>()) });
|
||||
0
|
||||
}
|
||||
Ok(n) => n - 1,
|
||||
Err(_) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Private data of every object, by object address and id.
|
||||
static PRIVATE: Mutex<BTreeMap<(usize, Iid), Vec<u8>>> = Mutex::new(BTreeMap::new());
|
||||
|
||||
fn private_data() -> std::sync::MutexGuard<'static, BTreeMap<(usize, Iid), Vec<u8>>> {
|
||||
PRIVATE.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
extern "system" fn get_private_data(
|
||||
this: This,
|
||||
id: *const Iid,
|
||||
size: *mut u32,
|
||||
data: *mut u8,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes an id and its buffer size (null is tolerated).
|
||||
let (Some(id), Some(size)) = (unsafe { (id.as_ref(), size.as_mut()) }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
let map = private_data();
|
||||
let Some(value) = map.get(&(this as usize, *id)) else {
|
||||
*size = 0;
|
||||
return NOT_FOUND;
|
||||
};
|
||||
let len = value.len() as u32;
|
||||
let room = std::mem::replace(size, len);
|
||||
if data.is_null() {
|
||||
return S_OK;
|
||||
}
|
||||
if room < len {
|
||||
return MORE_DATA;
|
||||
}
|
||||
// SAFETY: the buffer holds `room` >= `len` bytes.
|
||||
unsafe { data.copy_from_nonoverlapping(value.as_ptr(), value.len()) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Null data removes the entry.
|
||||
extern "system" fn set_private_data(
|
||||
this: This,
|
||||
id: *const Iid,
|
||||
size: u32,
|
||||
data: *const u8,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes an id (null is tolerated).
|
||||
let Some(&id) = (unsafe { id.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
let mut map = private_data();
|
||||
if data.is_null() {
|
||||
map.remove(&(this as usize, id));
|
||||
} else {
|
||||
// SAFETY: the title passes `size` bytes.
|
||||
let value = unsafe { std::slice::from_raw_parts(data, size as usize) };
|
||||
map.insert((this as usize, id), value.to_vec());
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Fills a D3D12 table's object methods: private data and name (setting
|
||||
/// an interface as private data stays unwritten).
|
||||
pub(crate) const fn d3d12_object<const N: usize>(mut f: [*const (); N]) -> [*const (); N] {
|
||||
f[3] = get_private_data as *const (); // 0x18
|
||||
f[4] = set_private_data as *const (); // 0x20
|
||||
f[6] = set_name as *const (); // 0x30
|
||||
f
|
||||
}
|
||||
|
||||
/// The object methods' name setter: names only reach our log.
|
||||
pub(crate) extern "system" fn set_name(this: This, name: *const u16) -> HRESULT {
|
||||
let name = if name.is_null() {
|
||||
String::new()
|
||||
} else {
|
||||
// SAFETY: a non-null name is NUL-terminated UTF-16.
|
||||
let len = (0..).take_while(|&i| unsafe { *name.add(i) } != 0).count();
|
||||
// SAFETY: `len` units were just read.
|
||||
String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(name, len) })
|
||||
};
|
||||
tracing::debug!(object = ?this, %name, "named");
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// The device-child method: the device that made the object.
|
||||
pub(crate) extern "system" fn parent_device(_: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let device = crate::device::device();
|
||||
answer(
|
||||
DEVICE,
|
||||
iid,
|
||||
is(iid, &[crate::device::IID]).then_some(device),
|
||||
out,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) const DEVICE: usize = 0;
|
||||
pub(crate) const DXGI_DEVICE: usize = 1;
|
||||
pub(crate) const ADAPTER: usize = 2;
|
||||
pub(crate) const FACTORY: usize = 3;
|
||||
pub(crate) const OUTPUT: usize = 4;
|
||||
pub(crate) const HEAP: usize = 5;
|
||||
pub(crate) const RESOURCE: usize = 6;
|
||||
pub(crate) const FENCE: usize = 7;
|
||||
pub(crate) const QUEUE: usize = 8;
|
||||
pub(crate) const ALLOCATOR: usize = 9;
|
||||
pub(crate) const LIST: usize = 10;
|
||||
pub(crate) const DESCRIPTOR_HEAP: usize = 11;
|
||||
pub(crate) const ROOT_SIGNATURE: usize = 12;
|
||||
pub(crate) const QUERY_HEAP: usize = 13;
|
||||
pub(crate) const COMMAND_SIGNATURE: usize = 14;
|
||||
pub(crate) const PIPELINE: usize = 15;
|
||||
const KINDS: [&str; 16] = [
|
||||
"device",
|
||||
"DXGI device",
|
||||
"adapter",
|
||||
"factory",
|
||||
"output",
|
||||
"heap",
|
||||
"resource",
|
||||
"fence",
|
||||
"command queue",
|
||||
"command allocator",
|
||||
"command list",
|
||||
"descriptor heap",
|
||||
"root signature",
|
||||
"query heap",
|
||||
"command signature",
|
||||
"pipeline state",
|
||||
];
|
||||
|
||||
const MAX_SLOTS: usize = 160;
|
||||
|
||||
/// Which unwritten slots have been reported; each is logged once.
|
||||
static REPORTED: [[AtomicBool; MAX_SLOTS]; KINDS.len()] =
|
||||
[const { [const { AtomicBool::new(false) }; MAX_SLOTS] }; KINDS.len()];
|
||||
|
||||
/// Logged once per slot. Wrong for a slot that returns a value instead of
|
||||
/// an `HRESULT`.
|
||||
extern "system" fn missing<const KIND: usize, const SLOT: usize>() -> HRESULT {
|
||||
if !REPORTED[KIND][SLOT].swap(true, Ordering::Relaxed) {
|
||||
tracing::warn!(
|
||||
object = KINDS[KIND],
|
||||
slot = format_args!("{:#x}", SLOT * 8),
|
||||
"method not implemented"
|
||||
);
|
||||
}
|
||||
E_NOTIMPL
|
||||
}
|
||||
|
||||
/// Accepts and ignores (debug-only settings).
|
||||
pub(crate) extern "system" fn ignore() -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
|
||||
macro_rules! missing {
|
||||
($kind:ident; $($slot:literal)*) => { [$(missing::<$kind, $slot> as *const ()),*] };
|
||||
}
|
||||
|
||||
/// A table of `N` slots that log and fail; callers fill in what they have.
|
||||
pub(crate) const fn missing_table<const KIND: usize, const N: usize>() -> [*const (); N] {
|
||||
let all = missing!(KIND;
|
||||
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
||||
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
||||
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
||||
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
|
||||
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
|
||||
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
|
||||
158 159
|
||||
);
|
||||
assert!(N <= all.len());
|
||||
let mut table = [std::ptr::null(); N];
|
||||
let mut i = 0;
|
||||
while i < N {
|
||||
table[i] = all[i];
|
||||
i += 1;
|
||||
}
|
||||
table[1] = add_ref as *const ();
|
||||
table[2] = release as *const ();
|
||||
table
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn slot<F: Copy>(object: This, offset: usize) -> F {
|
||||
// SAFETY: `object` is ours and its table has the slot.
|
||||
let f = unsafe { *(*object).functions.add(offset / 8) };
|
||||
// SAFETY: the caller names the slot's signature.
|
||||
unsafe { std::mem::transmute_copy(&f) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn guids_round_trip_through_text() {
|
||||
let g = guid(
|
||||
0x189819f1,
|
||||
0x1db6,
|
||||
0x4b57,
|
||||
[0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7],
|
||||
);
|
||||
assert_eq!(g[..4], [0xf1, 0x19, 0x98, 0x18]);
|
||||
assert_eq!(guid_text(&g), "189819f1-1db6-4b57-be54-1821339b85f7");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
//! Pipeline states. Both descriptions start as on PC: the root signature,
|
||||
//! then the shader stages (five for graphics, one for compute); only those
|
||||
//! are read so far.
|
||||
//!
|
||||
//! shortcut: the console shader containers are kept, not translated, and
|
||||
//! the rest of the description is ignored. Translate through the cache
|
||||
//! here (TODO.md, GPU: pipeline creation, decision 0003). The 32-byte
|
||||
//! packet after the header stays zero: titles only copy it inline, which
|
||||
//! our null command-list limits keep from running.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::mem::offset_of;
|
||||
|
||||
use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, PIPELINE, Table, This, guid};
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
|
||||
const PIPELINE_IIDS: [Iid; 4] = [
|
||||
guid(
|
||||
0x765a30f3,
|
||||
0xf624,
|
||||
0x4c6f,
|
||||
[0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45],
|
||||
),
|
||||
PAGEABLE_IIDS[0],
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
#[repr(C)]
|
||||
pub(crate) struct Bytecode {
|
||||
code: *const u8,
|
||||
size: usize,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub(crate) struct GraphicsHead {
|
||||
root: This,
|
||||
/// Vertex, pixel, domain, hull, geometry.
|
||||
stages: [Bytecode; 5],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub(crate) struct ComputeHead {
|
||||
root: This,
|
||||
stage: Bytecode,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Pipeline {
|
||||
object: Object,
|
||||
packet: [u32; 8],
|
||||
/// Each stage's container, empty when the stage is unused.
|
||||
shaders: Vec<Vec<u8>>,
|
||||
}
|
||||
const _: () = assert!(offset_of!(Pipeline, packet) == 0x10);
|
||||
|
||||
fn copy(stage: &Bytecode) -> Vec<u8> {
|
||||
if stage.code.is_null() || stage.size == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
// SAFETY: the title passes `size` bytes of shader code.
|
||||
unsafe { std::slice::from_raw_parts(stage.code, stage.size) }.to_vec()
|
||||
}
|
||||
|
||||
fn hand_out(shaders: Vec<Vec<u8>>, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let sizes: Vec<usize> = shaders.iter().map(Vec::len).collect();
|
||||
tracing::debug!(?sizes, "pipeline state");
|
||||
let pipeline = Box::new(Pipeline {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
packet: [0; 8],
|
||||
shaders,
|
||||
});
|
||||
object::hand_out(PIPELINE, pipeline, iid, &PIPELINE_IIDS, out)
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create_graphics(
|
||||
_: This,
|
||||
desc: *const GraphicsHead,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
hand_out(desc.stages.iter().map(copy).collect(), iid, out)
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create_compute(
|
||||
_: This,
|
||||
desc: *const ComputeHead,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
hand_out(vec![copy(&desc.stage)], iid, out)
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let found = object::is(iid, &PIPELINE_IIDS).then_some(this);
|
||||
object::answer(PIPELINE, iid, found, out)
|
||||
}
|
||||
extern "system" fn release(this: This) -> u32 {
|
||||
object::release_boxed::<Pipeline>(this)
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, pipeline 3.
|
||||
static FUNCTIONS: Table<11> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<PIPELINE, 11>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::{S_OK, slot};
|
||||
|
||||
#[test]
|
||||
fn pipelines_keep_their_shaders() {
|
||||
let (vs, ps) = ([1u8, 2, 3], [4u8; 5]);
|
||||
let none = || Bytecode {
|
||||
code: std::ptr::null(),
|
||||
size: 0,
|
||||
};
|
||||
let desc = GraphicsHead {
|
||||
root: std::ptr::null(),
|
||||
stages: [
|
||||
Bytecode {
|
||||
code: vs.as_ptr(),
|
||||
size: vs.len(),
|
||||
},
|
||||
Bytecode {
|
||||
code: ps.as_ptr(),
|
||||
size: ps.len(),
|
||||
},
|
||||
none(),
|
||||
none(),
|
||||
none(),
|
||||
],
|
||||
};
|
||||
let mut p = std::ptr::null();
|
||||
assert_eq!(
|
||||
create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p),
|
||||
S_OK
|
||||
);
|
||||
// SAFETY: one of our pipelines.
|
||||
let shaders = unsafe { &(*p.cast::<Pipeline>()).shaders };
|
||||
assert_eq!(shaders[0], vs);
|
||||
assert_eq!(shaders[1], ps);
|
||||
assert!(shaders[2].is_empty());
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(p, 0x10)(p), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Query heaps. Nothing runs on a GPU yet, so no query ever produces a
|
||||
//! result; the heap only remembers its description.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUERY_HEAP, Table, This, guid};
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
|
||||
const HEAP_IIDS: [Iid; 4] = [
|
||||
guid(
|
||||
0x0d9658ae,
|
||||
0xed45,
|
||||
0x469e,
|
||||
[0xa6, 0x1d, 0x97, 0x0e, 0xc5, 0x83, 0xca, 0xb4],
|
||||
),
|
||||
PAGEABLE_IIDS[0],
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Desc {
|
||||
kind: u32,
|
||||
count: u32,
|
||||
nodes: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Heap {
|
||||
object: Object,
|
||||
desc: Desc,
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create(
|
||||
_: This,
|
||||
desc: *const Desc,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(&desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
tracing::debug!(?desc, "query heap");
|
||||
let heap = Box::new(Heap {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
desc,
|
||||
});
|
||||
object::hand_out(QUERY_HEAP, heap, iid, &HEAP_IIDS, out)
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
object::answer(
|
||||
QUERY_HEAP,
|
||||
iid,
|
||||
object::is(iid, &HEAP_IIDS).then_some(this),
|
||||
out,
|
||||
)
|
||||
}
|
||||
extern "system" fn release(this: This) -> u32 {
|
||||
object::release_boxed::<Heap>(this)
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1.
|
||||
static FUNCTIONS: Table<8> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<QUERY_HEAP, 8>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
Table(f)
|
||||
};
|
||||
@@ -0,0 +1,220 @@
|
||||
//! Command queues. Nothing is executed yet: submitted lists are dropped and
|
||||
//! fence signals complete at once, as if the GPU were infinitely fast.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
|
||||
use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUEUE, S_OK, Table, This, guid};
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
|
||||
const QUEUE_IIDS: [Iid; 4] = [
|
||||
guid(
|
||||
0x0ec870a6,
|
||||
0x5d7e,
|
||||
0x4c22,
|
||||
[0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed],
|
||||
),
|
||||
PAGEABLE_IIDS[0],
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct QueueDesc {
|
||||
kind: u32,
|
||||
priority: i32,
|
||||
flags: u32,
|
||||
nodes: u32,
|
||||
}
|
||||
|
||||
/// The title reads the list type right after the header.
|
||||
#[repr(C)]
|
||||
struct Queue {
|
||||
object: Object,
|
||||
kind: u32,
|
||||
desc: QueueDesc,
|
||||
}
|
||||
const _: () = assert!(std::mem::offset_of!(Queue, kind) == 0x10);
|
||||
|
||||
fn queue<'a>(this: This) -> &'a Queue {
|
||||
// SAFETY: called from queue methods only.
|
||||
unsafe { &*this.cast::<Queue>() }
|
||||
}
|
||||
|
||||
pub(crate) extern "system" fn create(
|
||||
_: This,
|
||||
desc: *const QueueDesc,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(&desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
tracing::debug!(?desc, "command queue");
|
||||
let queue = Box::new(Queue {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
kind: desc.kind,
|
||||
desc,
|
||||
});
|
||||
object::hand_out(QUEUE, queue, iid, &QUEUE_IIDS, out)
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
object::answer(
|
||||
QUEUE,
|
||||
iid,
|
||||
object::is(iid, &QUEUE_IIDS).then_some(this),
|
||||
out,
|
||||
)
|
||||
}
|
||||
extern "system" fn release(this: This) -> u32 {
|
||||
object::release_boxed::<Queue>(this)
|
||||
}
|
||||
|
||||
/// Runs the lists' host lists and waits for them (decision 0007).
|
||||
extern "system" fn execute(_: This, count: u32, lists: *const This) {
|
||||
if lists.is_null() {
|
||||
return;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if let Some(host) = crate::host::host() {
|
||||
// SAFETY: the title passes `count` lists.
|
||||
let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) };
|
||||
let host_lists: Vec<_> = lists
|
||||
.iter()
|
||||
.filter_map(|&l| crate::list::host_list(l))
|
||||
.collect();
|
||||
host.execute(&host_lists);
|
||||
return;
|
||||
}
|
||||
static ONCE: AtomicBool = AtomicBool::new(false);
|
||||
if !ONCE.swap(true, Ordering::Relaxed) {
|
||||
tracing::warn!(count, "command lists submitted; no host GPU runs them");
|
||||
}
|
||||
}
|
||||
|
||||
/// The start of a present plane: frame token, then the plane's resources.
|
||||
#[repr(C)]
|
||||
pub(crate) struct Plane {
|
||||
token: u64,
|
||||
count: u32,
|
||||
resources: *const This,
|
||||
}
|
||||
/// Markers and events only matter to profilers.
|
||||
extern "system" fn marker(_: This) {}
|
||||
extern "system" fn signal(_: This, fence: This, value: u64) -> HRESULT {
|
||||
if fence.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
crate::fence::signal(fence, value)
|
||||
}
|
||||
/// Nothing runs on the queue, so waiting for a fence never blocks it.
|
||||
extern "system" fn wait(_: This, fence: This, _value: u64) -> HRESULT {
|
||||
if fence.is_null() { E_INVALIDARG } else { S_OK }
|
||||
}
|
||||
/// Ticks per second of GPU timestamps; none are written yet.
|
||||
extern "system" fn timestamp_frequency(_: This, out: *mut u64) -> HRESULT {
|
||||
if out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(100_000_000) };
|
||||
S_OK
|
||||
}
|
||||
/// Shows the first plane's first resource in our window.
|
||||
///
|
||||
/// shortcut: one plane, no scaling or placement, the source expected in
|
||||
/// the common state.
|
||||
extern "system" fn present(
|
||||
_: This,
|
||||
planes: u32,
|
||||
plane_parameters: *const Plane,
|
||||
_parameters: *const u8,
|
||||
) -> HRESULT {
|
||||
static FRAMES: AtomicU64 = AtomicU64::new(0);
|
||||
let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if frame.is_power_of_two() {
|
||||
tracing::info!(frame, "frame presented");
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if planes > 0
|
||||
// SAFETY: the title passes `planes` plane descriptions.
|
||||
&& let Some(plane) = unsafe { plane_parameters.as_ref() }
|
||||
&& plane.count > 0
|
||||
&& !plane.resources.is_null()
|
||||
// SAFETY: the plane lists `count` resources.
|
||||
&& let resource = unsafe { *plane.resources }
|
||||
&& let Some(texture) = crate::resource::host_resource(resource)
|
||||
&& let Some(host) = crate::host::host()
|
||||
{
|
||||
const COPY_SOURCE: u32 = 0x800;
|
||||
let state = crate::resource::host_transition(resource, COPY_SOURCE)
|
||||
.map_or(COPY_SOURCE, |(_, before)| before);
|
||||
host.present(texture, state);
|
||||
crate::resource::host_transition(resource, state);
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (planes, plane_parameters);
|
||||
S_OK
|
||||
}
|
||||
extern "system" fn desc(this: This, out: *mut QueueDesc) {
|
||||
if !out.is_null() {
|
||||
// SAFETY: checked non-null; the title passes room for a description.
|
||||
unsafe { out.write(queue(this).desc) };
|
||||
}
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, queue 26 (12 as on PC, then
|
||||
/// console ones).
|
||||
static FUNCTIONS: Table<34> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<QUEUE, 34>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
f[10] = execute as *const (); // 0x50
|
||||
f[11] = marker as *const (); // 0x58 set marker
|
||||
f[12] = marker as *const (); // 0x60 begin event
|
||||
f[13] = marker as *const (); // 0x68 end event
|
||||
f[14] = signal as *const (); // 0x70
|
||||
f[15] = wait as *const (); // 0x78
|
||||
f[16] = timestamp_frequency as *const (); // 0x80
|
||||
f[26] = desc as *const (); // 0xd0
|
||||
f[30] = present as *const (); // 0xf0
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::slot;
|
||||
|
||||
#[test]
|
||||
fn queue_signals_complete_at_once() {
|
||||
let null = std::ptr::null();
|
||||
let desc = QueueDesc {
|
||||
kind: 0,
|
||||
priority: 0,
|
||||
flags: 0,
|
||||
nodes: 0,
|
||||
};
|
||||
let mut q = null;
|
||||
assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK);
|
||||
// SAFETY: the title reads the type at +0x10.
|
||||
assert_eq!(unsafe { q.cast::<u8>().add(0x10).cast::<u32>().read() }, 0);
|
||||
let mut fence = null;
|
||||
let fence_iid = &crate::fence::FENCE_IIDS[0];
|
||||
assert_eq!(
|
||||
crate::fence::create(null, 0, 0, fence_iid, &mut fence),
|
||||
S_OK
|
||||
);
|
||||
let signal = slot::<extern "system" fn(This, This, u64) -> HRESULT>(q, 0x70);
|
||||
assert_eq!(signal(q, fence, 7), S_OK);
|
||||
assert_eq!(
|
||||
slot::<extern "system" fn(This) -> u64>(fence, 0x40)(fence),
|
||||
7
|
||||
);
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(q, 0x10)(q), 0);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,196 @@
|
||||
//! Root signatures.
|
||||
//!
|
||||
//! Serializing goes to the host's `D3D12SerializeRootSignature`: the
|
||||
//! description is laid out as on PC, and the blob it returns works as the
|
||||
//! console's, whose two methods sit in the same slots. The console's own
|
||||
//! flags (bit 24 and up) are dropped first.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use crate::object::{
|
||||
self, E_INVALIDARG, E_NOTIMPL, HRESULT, Iid, Object, ROOT_SIGNATURE, Table, This, guid,
|
||||
};
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
|
||||
const ROOT_SIGNATURE_IIDS: [Iid; 3] = [
|
||||
guid(
|
||||
0xc54a6b66,
|
||||
0x72df,
|
||||
0x4ee8,
|
||||
[0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14],
|
||||
),
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
const CONSOLE_FLAGS: u32 = 0xff00_0000;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Desc {
|
||||
parameter_count: u32,
|
||||
parameters: *const c_void,
|
||||
sampler_count: u32,
|
||||
samplers: *const c_void,
|
||||
flags: u32,
|
||||
}
|
||||
|
||||
type Serialize =
|
||||
unsafe extern "system" fn(*const Desc, u32, *mut *mut c_void, *mut *mut c_void) -> HRESULT;
|
||||
|
||||
/// The host's serializer, from `d3d12.dll` in System32.
|
||||
fn host_serializer() -> Option<Serialize> {
|
||||
static FUNCTION: OnceLock<Option<usize>> = OnceLock::new();
|
||||
let address = *FUNCTION.get_or_init(|| {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows_sys::Win32::System::LibraryLoader::{
|
||||
GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
|
||||
};
|
||||
let name: Vec<u16> = "d3d12.dll".encode_utf16().chain([0]).collect();
|
||||
// SAFETY: a NUL-terminated name; System32 only.
|
||||
let module = unsafe {
|
||||
LoadLibraryExW(
|
||||
name.as_ptr(),
|
||||
std::ptr::null_mut(),
|
||||
LOAD_LIBRARY_SEARCH_SYSTEM32,
|
||||
)
|
||||
};
|
||||
if module.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: a loaded module and a NUL-terminated name.
|
||||
unsafe { GetProcAddress(module, c"D3D12SerializeRootSignature".as_ptr().cast()) }
|
||||
.map(|f| f as usize)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
None
|
||||
});
|
||||
// SAFETY: the export has this signature.
|
||||
address.map(|a| unsafe { std::mem::transmute::<usize, Serialize>(a) })
|
||||
}
|
||||
|
||||
/// `d3d12_xs!D3D12SerializeRootSignature`.
|
||||
pub extern "system" fn serialize(
|
||||
desc: *const Desc,
|
||||
version: u32,
|
||||
blob: *mut *mut c_void,
|
||||
error: *mut *mut c_void,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(&desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if desc.flags & CONSOLE_FLAGS != 0 {
|
||||
tracing::debug!(
|
||||
flags = format_args!("{:#x}", desc.flags),
|
||||
"console root signature flags dropped"
|
||||
);
|
||||
}
|
||||
let desc = Desc {
|
||||
flags: desc.flags & !CONSOLE_FLAGS,
|
||||
..desc
|
||||
};
|
||||
let Some(serialize) = host_serializer() else {
|
||||
tracing::warn!("no host d3d12.dll to serialize root signatures");
|
||||
return E_NOTIMPL;
|
||||
};
|
||||
// SAFETY: the host function takes the same arguments the title passed.
|
||||
unsafe { serialize(&desc, version, blob, error) }
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct RootSignature {
|
||||
object: Object,
|
||||
/// The serialized form, kept for translating pipelines later.
|
||||
blob: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create(
|
||||
_: This,
|
||||
_nodes: u32,
|
||||
blob: *const u8,
|
||||
size: usize,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
if blob.is_null() || size == 0 {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: the title passes `size` bytes.
|
||||
let blob = unsafe { std::slice::from_raw_parts(blob, size) }.to_vec();
|
||||
tracing::debug!(size, "root signature");
|
||||
let root = Box::new(RootSignature {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
blob,
|
||||
});
|
||||
object::hand_out(ROOT_SIGNATURE, root, iid, &ROOT_SIGNATURE_IIDS, out)
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let found = object::is(iid, &ROOT_SIGNATURE_IIDS).then_some(this);
|
||||
object::answer(ROOT_SIGNATURE, iid, found, out)
|
||||
}
|
||||
extern "system" fn release(this: This) -> u32 {
|
||||
object::release_boxed::<RootSignature>(this)
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1.
|
||||
static FUNCTIONS: Table<8> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<ROOT_SIGNATURE, 8>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::{S_OK, slot};
|
||||
|
||||
/// One 32-bit constant at b0, serialized by the host, then created.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn host_serialized_blobs_create_root_signatures() {
|
||||
#[repr(C)]
|
||||
struct Constants {
|
||||
kind: u32,
|
||||
register: u32,
|
||||
space: u32,
|
||||
count: u32,
|
||||
visibility: u32,
|
||||
}
|
||||
let parameter = Constants {
|
||||
kind: 1,
|
||||
register: 0,
|
||||
space: 0,
|
||||
count: 1,
|
||||
visibility: 0,
|
||||
};
|
||||
let desc = Desc {
|
||||
parameter_count: 1,
|
||||
parameters: (&raw const parameter).cast(),
|
||||
sampler_count: 0,
|
||||
samplers: std::ptr::null(),
|
||||
flags: 0x0100_0001,
|
||||
};
|
||||
let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut());
|
||||
assert_eq!(serialize(&desc, 1, &mut blob, &mut error), S_OK);
|
||||
let blob = blob.cast_const().cast::<Object>();
|
||||
let data = slot::<extern "system" fn(This) -> *const u8>(blob, 0x18)(blob);
|
||||
let size = slot::<extern "system" fn(This) -> usize>(blob, 0x20)(blob);
|
||||
assert!(size > 0);
|
||||
let null = std::ptr::null();
|
||||
let mut root = null;
|
||||
assert_eq!(
|
||||
create(null, 0, data, size, &ROOT_SIGNATURE_IIDS[0], &mut root),
|
||||
S_OK
|
||||
);
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(root, 0x10)(root), 0);
|
||||
slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Command signatures: the record layout of indirect execution. Kept for
|
||||
//! translating it later.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use crate::object::{
|
||||
self, COMMAND_SIGNATURE, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid,
|
||||
};
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
|
||||
const SIGNATURE_IIDS: [Iid; 4] = [
|
||||
guid(
|
||||
0xc36a797c,
|
||||
0xec80,
|
||||
0x4f0a,
|
||||
[0x89, 0x85, 0xa7, 0xb2, 0x47, 0x50, 0x82, 0xd1],
|
||||
),
|
||||
PAGEABLE_IIDS[0],
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
#[repr(C)]
|
||||
pub(crate) struct Desc {
|
||||
stride: u32,
|
||||
count: u32,
|
||||
/// Each a type and up to three 32-bit fields.
|
||||
arguments: *const [u32; 4],
|
||||
nodes: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Signature {
|
||||
object: Object,
|
||||
stride: u32,
|
||||
arguments: Vec<[u32; 4]>,
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create(
|
||||
_: This,
|
||||
desc: *const Desc,
|
||||
_root: This,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if desc.arguments.is_null() && desc.count > 0 {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let arguments = if desc.count == 0 {
|
||||
Vec::new()
|
||||
} else {
|
||||
// SAFETY: the title passes `count` argument descriptions.
|
||||
unsafe { std::slice::from_raw_parts(desc.arguments, desc.count as usize) }.to_vec()
|
||||
};
|
||||
tracing::debug!(stride = desc.stride, ?arguments, "command signature");
|
||||
let signature = Box::new(Signature {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
stride: desc.stride,
|
||||
arguments,
|
||||
});
|
||||
object::hand_out(COMMAND_SIGNATURE, signature, iid, &SIGNATURE_IIDS, out)
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let found = object::is(iid, &SIGNATURE_IIDS).then_some(this);
|
||||
object::answer(COMMAND_SIGNATURE, iid, found, out)
|
||||
}
|
||||
extern "system" fn release(this: This) -> u32 {
|
||||
object::release_boxed::<Signature>(this)
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1.
|
||||
static FUNCTIONS: Table<8> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<COMMAND_SIGNATURE, 8>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
Table(f)
|
||||
};
|
||||
@@ -8,6 +8,7 @@ license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
victory-gpu.workspace = true
|
||||
victory-loader.workspace = true
|
||||
victory-pe.workspace = true
|
||||
tracing.workspace = true
|
||||
@@ -15,7 +16,14 @@ tracing.workspace = true
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { workspace = true, features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Globalization",
|
||||
"Win32_Storage_FileSystem",
|
||||
"Win32_System_Diagnostics_Debug",
|
||||
"Win32_System_LibraryLoader",
|
||||
"Win32_System_Memory",
|
||||
"Win32_System_ProcessStatus",
|
||||
"Win32_System_Threading",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -36,6 +36,14 @@ impl Default for HostPolicy {
|
||||
"sspicli.dll",
|
||||
"cabinet.dll",
|
||||
"avrt.dll",
|
||||
// Window, message and shell APIs: the host's desktop window
|
||||
// stands in for the console's single core window.
|
||||
"ext-ms-win-rtcore-ntuser-*",
|
||||
"api-ms-win-shcore-*",
|
||||
"msvcp_win.dll",
|
||||
"ole32.dll",
|
||||
"advapi32.dll",
|
||||
"iphlpapi.dll",
|
||||
];
|
||||
HostPolicy {
|
||||
allow: allow.iter().map(|s| s.to_string()).collect(),
|
||||
@@ -67,6 +75,16 @@ impl HostPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
/// The host's own `name` from the System32 DLL `dll`: what a title import
|
||||
/// of it is bound to when we do not override it.
|
||||
pub(crate) fn function(dll: &str, name: &str) -> Option<usize> {
|
||||
let name = ImportSymbol::Name {
|
||||
hint: 0,
|
||||
name: name.into(),
|
||||
};
|
||||
imp::resolve(dll, &name)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -44,9 +44,8 @@ impl HleResolver {
|
||||
|
||||
impl ImportResolver for HleResolver {
|
||||
fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution {
|
||||
if let ImportSymbol::Name { name, .. } = symbol
|
||||
&& let Some(address) = registry::lookup(dll, name)
|
||||
{
|
||||
// Ordinal imports look up `#n`.
|
||||
if let Some(address) = registry::lookup(dll, &symbol.to_string()) {
|
||||
return Resolution::Found {
|
||||
address,
|
||||
provenance: Provenance::Hle,
|
||||
|
||||
@@ -0,0 +1,551 @@
|
||||
//! The console's audio hardware (`AcpHal.dll`, `xapu.dll`), enough for
|
||||
//! middleware to start and then mix in software:
|
||||
//!
|
||||
//! * the APU heap: host memory with 32-bit device addresses;
|
||||
//! * SHAPE context arrays allocated from it;
|
||||
//! * the audio coprocessor's command and message queues, where every
|
||||
//! command completes at once and is acknowledged as the hardware would;
|
||||
//! * the APU decoder's connections, which accept no work.
|
||||
//!
|
||||
//! What the hardware computes (XMA decoding, hardware rate conversion, EQ,
|
||||
//! mixing, Opus decoding) is not emulated, so voices that need it stay
|
||||
//! silent. Software-decoded audio plays through the host's WASAPI, which
|
||||
//! middleware reaches through COM like on PC. fmod's console build sets
|
||||
//! all of this up inside `System_Create` and waits there for its first
|
||||
//! command to be acknowledged.
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::alloc::Layout;
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::ffi::c_void;
|
||||
use std::sync::{Mutex, MutexGuard};
|
||||
use std::time::Instant;
|
||||
|
||||
use super::xasync::E_INVALIDARG;
|
||||
use super::xgameruntime::{HRESULT, S_OK};
|
||||
use crate::{HleModule, hle_export};
|
||||
|
||||
const E_FAIL: HRESULT = 0x8000_4005_u32 as i32;
|
||||
const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
|
||||
/// The decoder's "no result yet", which fmod checks for.
|
||||
const PENDING_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32;
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
// The APU heap.
|
||||
|
||||
struct Block {
|
||||
size: usize,
|
||||
apu: u32,
|
||||
layout: Layout,
|
||||
}
|
||||
|
||||
struct Heap {
|
||||
/// By host address.
|
||||
blocks: BTreeMap<usize, Block>,
|
||||
next_apu: u32,
|
||||
}
|
||||
|
||||
static HEAP: Mutex<Heap> = Mutex::new(Heap {
|
||||
blocks: BTreeMap::new(),
|
||||
next_apu: 0x0001_0000,
|
||||
});
|
||||
|
||||
/// Zeroed host memory and its device address.
|
||||
// shortcut: device addresses are handed out once and never reused, so the
|
||||
// 32-bit space runs out after 4 GiB of allocations in total; reuse freed
|
||||
// ranges if a title streams that much through the heap.
|
||||
fn heap_alloc(size: usize, align: usize) -> Option<(*mut u8, u32)> {
|
||||
let layout = Layout::from_size_align(size.max(1), align.max(16)).ok()?;
|
||||
let mut heap = lock(&HEAP);
|
||||
let apu = heap.next_apu.checked_next_multiple_of(align as u32)?;
|
||||
let next = apu.checked_add(u32::try_from(layout.size()).ok()?)?;
|
||||
// SAFETY: non-zero size.
|
||||
let ptr = unsafe { std::alloc::alloc_zeroed(layout) };
|
||||
if ptr.is_null() {
|
||||
return None;
|
||||
}
|
||||
heap.next_apu = next;
|
||||
heap.blocks
|
||||
.insert(ptr as usize, Block { size, apu, layout });
|
||||
Some((ptr, apu))
|
||||
}
|
||||
|
||||
fn heap_free(ptr: *mut u8) {
|
||||
let block = lock(&HEAP).blocks.remove(&(ptr as usize));
|
||||
if let Some(block) = block {
|
||||
// SAFETY: allocated by `heap_alloc` with this layout.
|
||||
unsafe { std::alloc::dealloc(ptr, block.layout) };
|
||||
}
|
||||
}
|
||||
|
||||
/// The device address of any byte of a heap block, 0 elsewhere.
|
||||
fn heap_map(ptr: usize) -> u32 {
|
||||
let heap = lock(&HEAP);
|
||||
match heap.blocks.range(..=ptr).next_back() {
|
||||
Some((&start, block)) if ptr < start + block.size.max(1) => {
|
||||
block.apu + (ptr - start) as u32
|
||||
}
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The host address of a device address, if a heap block holds it.
|
||||
fn heap_unmap(apu: u32) -> Option<*mut u8> {
|
||||
let heap = lock(&HEAP);
|
||||
heap.blocks
|
||||
.iter()
|
||||
.find(|(_, b)| (b.apu..b.apu.saturating_add(b.size as u32)).contains(&apu))
|
||||
.map(|(&start, b)| (start + (apu - b.apu) as usize) as *mut u8)
|
||||
}
|
||||
|
||||
pub extern "system" fn ApuAlloc(
|
||||
out: *mut *mut c_void,
|
||||
apu: *mut u32,
|
||||
size: u32,
|
||||
align: u32,
|
||||
_flags: u32,
|
||||
) -> HRESULT {
|
||||
if out.is_null() || size == 0 || align < 4 || !align.is_power_of_two() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let Some((ptr, address)) = heap_alloc(size as usize, align as usize) else {
|
||||
return E_OUTOFMEMORY;
|
||||
};
|
||||
// SAFETY: checked non-null; optional out parameter checked below.
|
||||
unsafe {
|
||||
out.write(ptr.cast());
|
||||
if !apu.is_null() {
|
||||
apu.write(address);
|
||||
}
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn ApuFree(ptr: *mut c_void) {
|
||||
heap_free(ptr.cast());
|
||||
}
|
||||
|
||||
pub extern "system" fn ApuMapVirtualAddress(ptr: *const c_void) -> u32 {
|
||||
heap_map(ptr as usize)
|
||||
}
|
||||
|
||||
pub extern "system" fn ApuIsVirtualAddressValid(ptr: *const c_void, align: u32) -> bool {
|
||||
let apu = heap_map(ptr as usize);
|
||||
apu != 0 && (align == 0 || apu.is_multiple_of(align))
|
||||
}
|
||||
|
||||
// SHAPE context arrays.
|
||||
|
||||
/// Six counts (rate conversion, EQ/compression, filter/volume, DMA, XMA,
|
||||
/// PCM), then the six arrays and their device addresses.
|
||||
#[repr(C, packed)]
|
||||
pub struct ShapeContexts {
|
||||
counts: [u32; 6],
|
||||
arrays: [*mut c_void; 6],
|
||||
apu: [u32; 6],
|
||||
}
|
||||
|
||||
/// Bytes per context: rate conversion, DMA and XMA as fmod clears them;
|
||||
/// the others (not seen yet) get a generous upper bound.
|
||||
const CONTEXT_BYTES: [usize; 6] = [32, 256, 256, 16, 64, 256];
|
||||
|
||||
static CONTEXTS: Mutex<Option<[usize; 6]>> = Mutex::new(None);
|
||||
|
||||
pub extern "system" fn AcpHalAllocateShapeContexts(contexts: *mut ShapeContexts) -> HRESULT {
|
||||
if contexts.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let mut allocated = lock(&CONTEXTS);
|
||||
if allocated.is_some() {
|
||||
return E_FAIL;
|
||||
}
|
||||
// SAFETY: the title passes its request; packed fields are copied out.
|
||||
let counts = unsafe { std::ptr::addr_of!((*contexts).counts).read_unaligned() };
|
||||
let mut arrays: [*mut c_void; 6] = [std::ptr::null_mut(); 6];
|
||||
let mut addresses = [0u32; 6];
|
||||
for i in 0..6 {
|
||||
if counts[i] == 0 {
|
||||
continue;
|
||||
}
|
||||
let Some((ptr, apu)) = heap_alloc(counts[i] as usize * CONTEXT_BYTES[i], 256) else {
|
||||
arrays.iter().for_each(|&p| heap_free(p.cast()));
|
||||
return E_OUTOFMEMORY;
|
||||
};
|
||||
(arrays[i], addresses[i]) = (ptr.cast(), apu);
|
||||
}
|
||||
// SAFETY: as above.
|
||||
unsafe {
|
||||
std::ptr::addr_of_mut!((*contexts).arrays).write_unaligned(arrays);
|
||||
std::ptr::addr_of_mut!((*contexts).apu).write_unaligned(addresses);
|
||||
}
|
||||
*allocated = Some(arrays.map(|p| p as usize));
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn AcpHalReleaseShapeContexts() -> HRESULT {
|
||||
match lock(&CONTEXTS).take() {
|
||||
Some(arrays) => {
|
||||
arrays.iter().for_each(|&p| heap_free(p as *mut u8));
|
||||
S_OK
|
||||
}
|
||||
None => E_FAIL,
|
||||
}
|
||||
}
|
||||
|
||||
// The audio coprocessor.
|
||||
|
||||
const LOAD_FLOWGRAPH: u32 = 1;
|
||||
const REGISTER_MESSAGES: u32 = 2;
|
||||
const UNREGISTER_MESSAGES: u32 = 3;
|
||||
|
||||
const FLOWGRAPH_COMPLETED: u32 = 0x02;
|
||||
const COMMAND_COMPLETED: u32 = 0x10;
|
||||
const DISCONNECTED: u32 = 0x80;
|
||||
|
||||
/// Audio frames of 128 samples at 48 kHz.
|
||||
const FRAMES_PER_SECOND: u64 = 375;
|
||||
|
||||
#[repr(C, packed)]
|
||||
#[derive(Clone, Copy)]
|
||||
struct Message {
|
||||
kind: u32,
|
||||
dropped: u32,
|
||||
usec: u32,
|
||||
data: [u8; 16],
|
||||
}
|
||||
|
||||
struct State {
|
||||
connected: bool,
|
||||
/// Message kinds the title registered for.
|
||||
mask: u32,
|
||||
messages: VecDeque<Message>,
|
||||
since: Instant,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn usec(&self) -> u64 {
|
||||
self.since.elapsed().as_micros() as u64
|
||||
}
|
||||
|
||||
fn frame(&self) -> u32 {
|
||||
(self.usec() * FRAMES_PER_SECOND / 1_000_000) as u32
|
||||
}
|
||||
|
||||
// shortcut: the queue is unbounded and never reports dropped messages;
|
||||
// bound it at the size given to `connect` if a title relies on drops.
|
||||
fn post(&mut self, kind: u32, data: &[u8]) {
|
||||
if self.mask & kind == 0 {
|
||||
return;
|
||||
}
|
||||
let mut message = Message {
|
||||
kind,
|
||||
dropped: 0,
|
||||
usec: self.usec() as u32,
|
||||
data: [0; 16],
|
||||
};
|
||||
message.data[..data.len()].copy_from_slice(data);
|
||||
self.messages.push_back(message);
|
||||
}
|
||||
}
|
||||
|
||||
/// The interface object: its method table, then our state.
|
||||
#[repr(C)]
|
||||
pub struct Acp {
|
||||
vtable: &'static AcpMethods,
|
||||
state: Mutex<State>,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct AcpMethods {
|
||||
connect: extern "system" fn(*mut Acp, u32, u32) -> HRESULT,
|
||||
disconnect: extern "system" fn(*mut Acp) -> HRESULT,
|
||||
submit: extern "system" fn(*mut Acp, u32, u64, u32, *const c_void, u32) -> HRESULT,
|
||||
pop_message: extern "system" fn(*mut Acp, *mut Message) -> bool,
|
||||
message_count: extern "system" fn(*mut Acp) -> u32,
|
||||
release: extern "system" fn(*mut Acp),
|
||||
}
|
||||
|
||||
static ACP_METHODS: AcpMethods = AcpMethods {
|
||||
connect,
|
||||
disconnect,
|
||||
submit,
|
||||
pop_message,
|
||||
message_count,
|
||||
release,
|
||||
};
|
||||
|
||||
fn state(this: *mut Acp) -> MutexGuard<'static, State> {
|
||||
// SAFETY: title code calls methods on the object `AcpHalCreate` made,
|
||||
// which lives until `release`.
|
||||
lock(unsafe { &(*this).state })
|
||||
}
|
||||
|
||||
extern "system" fn connect(this: *mut Acp, commands: u32, _messages: u32) -> HRESULT {
|
||||
if commands == 0 {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
state(this).connected = true;
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn disconnect(this: *mut Acp) -> HRESULT {
|
||||
let mut state = state(this);
|
||||
if !state.connected {
|
||||
return E_FAIL;
|
||||
}
|
||||
state.post(DISCONNECTED, &[]);
|
||||
state.connected = false;
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Done at once: message registrations take effect, a flowgraph completes
|
||||
/// unprocessed, a command with an id is acknowledged, and its notification
|
||||
/// word is set.
|
||||
extern "system" fn submit(
|
||||
this: *mut Acp,
|
||||
command: u32,
|
||||
id: u64,
|
||||
_frame: u32,
|
||||
data: *const c_void,
|
||||
notification: u32,
|
||||
) -> HRESULT {
|
||||
static SEEN: Mutex<u64> = Mutex::new(0);
|
||||
if command < 64 && *lock(&SEEN) & 1 << command == 0 {
|
||||
*lock(&SEEN) |= 1 << command;
|
||||
tracing::info!(command, "first coprocessor command of this kind");
|
||||
}
|
||||
let mut state = state(this);
|
||||
let word = |at: usize| -> Option<u32> {
|
||||
// SAFETY: the command's data starts with these u32 fields.
|
||||
(!data.is_null()).then(|| unsafe { data.cast::<u32>().add(at).read_unaligned() })
|
||||
};
|
||||
match command {
|
||||
REGISTER_MESSAGES => state.mask |= word(0).unwrap_or(0),
|
||||
UNREGISTER_MESSAGES => state.mask &= !word(0).unwrap_or(0),
|
||||
LOAD_FLOWGRAPH => {
|
||||
let flowgraph = word(1).unwrap_or(0);
|
||||
state.post(FLOWGRAPH_COMPLETED, &flowgraph.to_le_bytes());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if id != 0 {
|
||||
let mut done = [0u8; 16];
|
||||
done[..4].copy_from_slice(&command.to_le_bytes());
|
||||
done[4..12].copy_from_slice(&id.to_le_bytes());
|
||||
done[12..].copy_from_slice(&state.frame().to_le_bytes());
|
||||
state.post(COMMAND_COMPLETED, &done);
|
||||
}
|
||||
if notification != 0
|
||||
&& let Some(word) = heap_unmap(notification)
|
||||
{
|
||||
// SAFETY: a u32 in a heap block, which the title reads as volatile.
|
||||
unsafe { word.cast::<u32>().write_volatile(1) };
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn pop_message(this: *mut Acp, out: *mut Message) -> bool {
|
||||
let Some(message) = state(this).messages.pop_front() else {
|
||||
return false;
|
||||
};
|
||||
if !out.is_null() {
|
||||
// SAFETY: the title passes room for one message.
|
||||
unsafe { out.write_unaligned(message) };
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
extern "system" fn message_count(this: *mut Acp) -> u32 {
|
||||
state(this).messages.len() as u32
|
||||
}
|
||||
|
||||
extern "system" fn release(this: *mut Acp) {
|
||||
// SAFETY: made by `AcpHalCreate` with `Box::into_raw`; released once.
|
||||
drop(unsafe { Box::from_raw(this) });
|
||||
}
|
||||
|
||||
pub extern "system" fn AcpHalCreate(out: *mut *mut Acp) -> HRESULT {
|
||||
if out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let acp = Box::new(Acp {
|
||||
vtable: &ACP_METHODS,
|
||||
state: Mutex::new(State {
|
||||
connected: false,
|
||||
mask: 0,
|
||||
messages: VecDeque::new(),
|
||||
since: Instant::now(),
|
||||
}),
|
||||
});
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(Box::into_raw(acp)) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
// The APU decoder: connections get their memory, commands are refused.
|
||||
|
||||
#[repr(C)]
|
||||
pub struct ConnectInput {
|
||||
process: u32,
|
||||
streams: u32,
|
||||
commands_per_stream: u32,
|
||||
memory: u32,
|
||||
frames_per_output: u32,
|
||||
options: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct ConnectOutput {
|
||||
memory: *mut c_void,
|
||||
result_event: *mut c_void,
|
||||
}
|
||||
|
||||
/// The memory a connection hands out.
|
||||
pub struct Connection(*mut u8, Layout);
|
||||
|
||||
pub extern "system" fn XApuConnect(
|
||||
input: *const ConnectInput,
|
||||
output: *mut ConnectOutput,
|
||||
handle: *mut *mut Connection,
|
||||
) -> HRESULT {
|
||||
const RESULT_READY_EVENT: u32 = 8;
|
||||
if input.is_null() || output.is_null() || handle.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: checked non-null.
|
||||
let input = unsafe { &*input };
|
||||
if input.options & RESULT_READY_EVENT != 0 {
|
||||
// shortcut: no event to signal, since no result ever comes; create
|
||||
// one if a title asks for it.
|
||||
return E_FAIL;
|
||||
}
|
||||
let Ok(layout) = Layout::from_size_align(input.memory.max(16) as usize, 16) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
// SAFETY: non-zero size.
|
||||
let memory = unsafe { std::alloc::alloc_zeroed(layout) };
|
||||
if memory.is_null() {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
// SAFETY: checked non-null.
|
||||
unsafe {
|
||||
output.write(ConnectOutput {
|
||||
memory: memory.cast(),
|
||||
result_event: std::ptr::null_mut(),
|
||||
});
|
||||
handle.write(Box::into_raw(Box::new(Connection(memory, layout))));
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Nothing is decoded: the stream fails instead of waiting forever.
|
||||
pub extern "system" fn XApuEnqueueCommand() -> HRESULT {
|
||||
E_FAIL
|
||||
}
|
||||
|
||||
pub extern "system" fn XApuDequeueResult() -> HRESULT {
|
||||
PENDING_RESULTS
|
||||
}
|
||||
|
||||
pub extern "system" fn XApuDisconnect(handle: *mut Connection) -> HRESULT {
|
||||
if handle.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: made by `XApuConnect`; disconnected once.
|
||||
let Connection(memory, layout) = *unsafe { Box::from_raw(handle) };
|
||||
// SAFETY: allocated in `XApuConnect` with this layout.
|
||||
unsafe { std::alloc::dealloc(memory, layout) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "audio",
|
||||
dlls: &["acphal.dll", "xapu.dll"],
|
||||
exports: vec![
|
||||
hle_export!(AcpHalAllocateShapeContexts),
|
||||
hle_export!(AcpHalReleaseShapeContexts),
|
||||
hle_export!(AcpHalCreate),
|
||||
hle_export!(ApuAlloc),
|
||||
hle_export!(ApuFree),
|
||||
hle_export!(ApuIsVirtualAddressValid),
|
||||
hle_export!(ApuMapVirtualAddress),
|
||||
hle_export!(XApuConnect),
|
||||
hle_export!(XApuEnqueueCommand),
|
||||
hle_export!(XApuDequeueResult),
|
||||
hle_export!(XApuDisconnect),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn heap_maps_every_byte_of_a_block() {
|
||||
let (mut ptr, mut apu) = (std::ptr::null_mut(), 0);
|
||||
assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 128, 1), S_OK);
|
||||
assert!(apu != 0 && apu.is_multiple_of(128));
|
||||
let inner = ptr.cast::<u8>().wrapping_add(0x40).cast_const().cast();
|
||||
assert_eq!(ApuMapVirtualAddress(inner), apu + 0x40);
|
||||
assert!(ApuIsVirtualAddressValid(ptr, 128));
|
||||
assert_eq!(heap_unmap(apu + 4), Some(ptr.cast::<u8>().wrapping_add(4)));
|
||||
ApuFree(ptr);
|
||||
assert_eq!(ApuMapVirtualAddress(ptr), 0);
|
||||
assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 6, 1), E_INVALIDARG);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_as_fmod_does_it() {
|
||||
// Context arrays: rate conversion, DMA and XMA.
|
||||
let mut request = ShapeContexts {
|
||||
counts: [0x200, 0, 0, 0x400, 0x200, 0],
|
||||
arrays: [std::ptr::null_mut(); 6],
|
||||
apu: [0; 6],
|
||||
};
|
||||
assert_eq!(size_of::<ShapeContexts>(), 0x60);
|
||||
assert_eq!(AcpHalAllocateShapeContexts(&mut request), S_OK);
|
||||
let arrays = request.arrays;
|
||||
assert!(!arrays[0].is_null() && !arrays[3].is_null() && !arrays[4].is_null());
|
||||
assert!(arrays[1].is_null());
|
||||
// SAFETY: 0x200 rate-conversion contexts of 32 bytes were allocated.
|
||||
unsafe { arrays[0].cast::<u8>().write_bytes(0, 0x200 << 5) };
|
||||
|
||||
// Connect, register every message but frame starts, then wait for
|
||||
// the registration to be acknowledged.
|
||||
let mut acp = std::ptr::null_mut();
|
||||
assert_eq!(AcpHalCreate(&mut acp), S_OK);
|
||||
// SAFETY: just created.
|
||||
let m = unsafe { (*acp).vtable };
|
||||
assert_eq!((m.connect)(acp, 0x804, 0x804), S_OK);
|
||||
let mask = 0xfe_u32;
|
||||
let data = (&raw const mask).cast();
|
||||
assert_eq!(
|
||||
(m.submit)(acp, REGISTER_MESSAGES, 1, u32::MAX, data, 0),
|
||||
S_OK
|
||||
);
|
||||
let mut message = Message {
|
||||
kind: 0,
|
||||
dropped: 0,
|
||||
usec: 0,
|
||||
data: [0; 16],
|
||||
};
|
||||
assert!((m.pop_message)(acp, &mut message));
|
||||
let (kind, dropped) = (message.kind, message.dropped);
|
||||
assert_eq!((kind, dropped), (COMMAND_COMPLETED, 0));
|
||||
assert_eq!(
|
||||
u64::from_le_bytes(message.data[4..12].try_into().unwrap()),
|
||||
1
|
||||
);
|
||||
assert!(!(m.pop_message)(acp, &mut message));
|
||||
assert_eq!((m.disconnect)(acp), S_OK);
|
||||
assert_eq!((m.message_count)(acp), 1, "disconnected");
|
||||
(m.release)(acp);
|
||||
assert_eq!(AcpHalReleaseShapeContexts(), S_OK);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! `d3d12_xs.dll`: device creation. The device and everything it creates
|
||||
//! live in `victory-gpu`.
|
||||
|
||||
use victory_gpu::device;
|
||||
|
||||
use crate::{HleExport, HleModule};
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "d3d12x",
|
||||
dlls: &["d3d12_xs.dll"],
|
||||
exports: vec![
|
||||
HleExport {
|
||||
name: "D3D12XboxCreateDevice",
|
||||
address: device::create as *const () as usize,
|
||||
},
|
||||
HleExport {
|
||||
name: "D3D12SerializeRootSignature",
|
||||
address: victory_gpu::root::serialize as *const () as usize,
|
||||
},
|
||||
// A data import: the title reads the id at this address.
|
||||
HleExport {
|
||||
name: "IID_ID3D12Device",
|
||||
address: (&raw const device::IID) as usize,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{HleResolver, HostPolicy};
|
||||
use victory_loader::ImportResolver;
|
||||
use victory_loader::Resolution;
|
||||
use victory_pe::ImportSymbol;
|
||||
|
||||
#[test]
|
||||
fn the_interface_id_import_is_bound_to_data() {
|
||||
let symbol = ImportSymbol::Name {
|
||||
hint: 0,
|
||||
name: "IID_ID3D12Device".into(),
|
||||
};
|
||||
let r = HleResolver::new(HostPolicy::none());
|
||||
let Resolution::Found { address, .. } = r.resolve("d3d12_xs.dll", &symbol) else {
|
||||
panic!("not bound");
|
||||
};
|
||||
// SAFETY: the address is our static id.
|
||||
assert_eq!(unsafe { *(address as *const [u8; 16]) }, device::IID);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,587 @@
|
||||
//! Virtual drives over host folders: on the console, title storage is a
|
||||
//! drive of its own, and titles build paths on that assumption.
|
||||
//!
|
||||
//! Every title import that takes a path is bound here. A path on a virtual
|
||||
//! drive (`X:\..`, `X:/..`, `X:`, `\\?\X:\..`) is rewritten to the host
|
||||
//! folder behind it and handed to the host's own function; any other path
|
||||
//! goes to the host unchanged. A rewritten narrow path goes to the wide
|
||||
//! twin, so host folders outside the ANSI code page work. Letters are
|
||||
//! chosen among those the host does not use, so no host drive is hidden.
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
|
||||
use std::ffi::{CStr, c_char, c_void};
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
use std::sync::{Mutex, MutexGuard};
|
||||
|
||||
use windows_sys::Win32::Globalization::{CP_ACP, MultiByteToWideChar};
|
||||
use windows_sys::Win32::Storage::FileSystem::GetLogicalDrives;
|
||||
|
||||
use crate::{HleExport, HleModule, hle_export};
|
||||
|
||||
/// The host's own function: what the import would have been bound to.
|
||||
macro_rules! host {
|
||||
($dll:literal, $name:literal: $ty:ty) => {{
|
||||
static ADDRESS: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
|
||||
let address = *ADDRESS.get_or_init(|| {
|
||||
crate::host::function($dll, $name)
|
||||
.unwrap_or_else(|| panic!("the host lacks {}!{}", $dll, $name))
|
||||
});
|
||||
// SAFETY: the host exports this function with this signature.
|
||||
unsafe { std::mem::transmute::<usize, $ty>(address) }
|
||||
}};
|
||||
}
|
||||
|
||||
/// Mounted drives: upper-case letter and host root (UTF-16, no trailing
|
||||
/// separator, no NUL).
|
||||
static DRIVES: Mutex<Vec<(u16, Vec<u16>)>> = Mutex::new(Vec::new());
|
||||
|
||||
fn drives() -> MutexGuard<'static, Vec<(u16, Vec<u16>)>> {
|
||||
DRIVES.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Gives the host folder `root` a drive letter (the same one if it already
|
||||
/// has one): the highest letter neither the host nor another mount uses.
|
||||
pub fn mount(root: &Path) -> Option<char> {
|
||||
let mut wide: Vec<u16> = root.as_os_str().encode_wide().collect();
|
||||
while wide.len() > 3 && wide.last().is_some_and(|c| SEPARATORS.contains(c)) {
|
||||
wide.pop();
|
||||
}
|
||||
let mut drives = drives();
|
||||
if let Some(&(letter, _)) = drives.iter().find(|(_, r)| *r == wide) {
|
||||
return char::from_u32(letter.into());
|
||||
}
|
||||
// SAFETY: no arguments.
|
||||
let host = unsafe { GetLogicalDrives() };
|
||||
let letter = (b'D'..=b'Z').rev().find(|&l| {
|
||||
host >> (l - b'A') & 1 == 0 && !drives.iter().any(|(m, _)| *m == u16::from(l))
|
||||
})?;
|
||||
tracing::info!(drive = %char::from(letter), root = %root.display(), "virtual drive");
|
||||
drives.push((letter.into(), wide));
|
||||
Some(letter.into())
|
||||
}
|
||||
|
||||
const SEPARATORS: [u16; 2] = [b'\\' as u16, b'/' as u16];
|
||||
const VERBATIM: [u16; 4] = [b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16];
|
||||
|
||||
/// The host path, NUL-terminated, for `path` (without its NUL) if it is on
|
||||
/// a virtual drive.
|
||||
// shortcut: host roots are not made verbatim, so a long host root can push a
|
||||
// title path past MAX_PATH; switch to `\\?\` paths (normalising `..` and `/`
|
||||
// ourselves) if a title's paths get that long.
|
||||
fn translate(path: &[u16]) -> Option<Vec<u16>> {
|
||||
let (prefix, rest) = match path.strip_prefix(&VERBATIM[..]) {
|
||||
Some(rest) => (&VERBATIM[..], rest),
|
||||
None => (&[][..], path),
|
||||
};
|
||||
let &[letter, colon, ..] = rest else {
|
||||
return None;
|
||||
};
|
||||
if colon != u16::from(b':') {
|
||||
return None;
|
||||
}
|
||||
let letter = u8::try_from(letter).ok().filter(u8::is_ascii_alphabetic)?;
|
||||
let letter = u16::from(letter.to_ascii_uppercase());
|
||||
let drives = drives();
|
||||
let (_, root) = drives.iter().find(|(l, _)| *l == letter)?;
|
||||
let tail = &rest[2..];
|
||||
let mut out = prefix.to_vec();
|
||||
out.extend_from_slice(root);
|
||||
// `X:` and `X:name` are relative to the root.
|
||||
if !tail.first().is_some_and(|c| SEPARATORS.contains(c)) {
|
||||
out.push(b'\\'.into());
|
||||
}
|
||||
let verbatim = !prefix.is_empty();
|
||||
out.extend(tail.iter().map(|&c| {
|
||||
if verbatim && c == u16::from(b'/') {
|
||||
b'\\'.into()
|
||||
} else {
|
||||
c
|
||||
}
|
||||
}));
|
||||
out.push(0);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A title's wide path: the host path when it is on a virtual drive, else
|
||||
/// the title's own pointer.
|
||||
struct Wide(*const u16, Option<Vec<u16>>);
|
||||
|
||||
impl Wide {
|
||||
fn ptr(&self) -> *const u16 {
|
||||
self.1.as_ref().map_or(self.0, |p| p.as_ptr())
|
||||
}
|
||||
}
|
||||
|
||||
fn wide(path: *const u16) -> Wide {
|
||||
if path.is_null() {
|
||||
return Wide(path, None);
|
||||
}
|
||||
// SAFETY: the title passes a NUL-terminated path.
|
||||
let path_slice = unsafe {
|
||||
let len = (0..).take_while(|&i| *path.add(i) != 0).count();
|
||||
std::slice::from_raw_parts(path, len)
|
||||
};
|
||||
Wide(path, translate(path_slice))
|
||||
}
|
||||
|
||||
/// A narrow path (ANSI code page, as the host decodes it) on a virtual
|
||||
/// drive, as a wide host path.
|
||||
fn narrow(path: *const c_char) -> Option<Vec<u16>> {
|
||||
if path.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the title passes a NUL-terminated path.
|
||||
let bytes = unsafe { CStr::from_ptr(path) }.to_bytes();
|
||||
// The drive part is ASCII in every code page; decode only candidates.
|
||||
match bytes.strip_prefix(br"\\?\").unwrap_or(bytes) {
|
||||
[letter, b':', ..] if letter.is_ascii_alphabetic() => {}
|
||||
_ => return None,
|
||||
}
|
||||
let len = i32::try_from(bytes.len()).ok()?;
|
||||
// SAFETY: sizing call, then a call with room for `n` units.
|
||||
let wide = unsafe {
|
||||
let n = MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, std::ptr::null_mut(), 0);
|
||||
let mut wide = vec![0u16; usize::try_from(n).ok()?];
|
||||
MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, wide.as_mut_ptr(), n);
|
||||
wide
|
||||
};
|
||||
translate(&wide)
|
||||
}
|
||||
|
||||
/// An ASCII mode string (`"rb"`, `"w, ccs=UTF-8"`) for a wide CRT call.
|
||||
fn widen(mode: *const c_char) -> Vec<u16> {
|
||||
if mode.is_null() {
|
||||
return vec![0];
|
||||
}
|
||||
// SAFETY: a NUL-terminated mode string.
|
||||
let bytes = unsafe { CStr::from_ptr(mode) }.to_bytes();
|
||||
bytes.iter().map(|&b| u16::from(b)).chain([0]).collect()
|
||||
}
|
||||
|
||||
type Handle = *mut c_void;
|
||||
type File = *mut c_void;
|
||||
|
||||
// kernel32 and its file API sets.
|
||||
|
||||
pub extern "system" fn CreateFileW(
|
||||
path: *const u16,
|
||||
access: u32,
|
||||
share: u32,
|
||||
security: *const c_void,
|
||||
disposition: u32,
|
||||
flags: u32,
|
||||
template: Handle,
|
||||
) -> Handle {
|
||||
let p = wide(path);
|
||||
host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)(
|
||||
p.ptr(),
|
||||
access,
|
||||
share,
|
||||
security,
|
||||
disposition,
|
||||
flags,
|
||||
template,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn CreateFileA(
|
||||
path: *const c_char,
|
||||
access: u32,
|
||||
share: u32,
|
||||
security: *const c_void,
|
||||
disposition: u32,
|
||||
flags: u32,
|
||||
template: Handle,
|
||||
) -> Handle {
|
||||
match narrow(path) {
|
||||
Some(p) => CreateFileW(
|
||||
p.as_ptr(),
|
||||
access,
|
||||
share,
|
||||
security,
|
||||
disposition,
|
||||
flags,
|
||||
template,
|
||||
),
|
||||
None => {
|
||||
host!("kernel32.dll", "CreateFileA": extern "system" fn(*const c_char, u32, u32, *const c_void, u32, u32, Handle) -> Handle)(
|
||||
path,
|
||||
access,
|
||||
share,
|
||||
security,
|
||||
disposition,
|
||||
flags,
|
||||
template,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "system" fn DeleteFileA(path: *const c_char) -> i32 {
|
||||
match narrow(path) {
|
||||
Some(p) => {
|
||||
host!("kernel32.dll", "DeleteFileW": extern "system" fn(*const u16) -> i32)(p.as_ptr())
|
||||
}
|
||||
None => {
|
||||
host!("kernel32.dll", "DeleteFileA": extern "system" fn(*const c_char) -> i32)(path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "system" fn CreateDirectoryW(path: *const u16, security: *const c_void) -> i32 {
|
||||
let p = wide(path);
|
||||
host!("kernel32.dll", "CreateDirectoryW": extern "system" fn(*const u16, *const c_void) -> i32)(
|
||||
p.ptr(),
|
||||
security,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn GetFileAttributesExW(
|
||||
path: *const u16,
|
||||
level: i32,
|
||||
info: *mut c_void,
|
||||
) -> i32 {
|
||||
let p = wide(path);
|
||||
host!("kernel32.dll", "GetFileAttributesExW": extern "system" fn(*const u16, i32, *mut c_void) -> i32)(
|
||||
p.ptr(),
|
||||
level,
|
||||
info,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn GetDiskFreeSpaceExW(
|
||||
path: *const u16,
|
||||
available: *mut u64,
|
||||
total: *mut u64,
|
||||
free: *mut u64,
|
||||
) -> i32 {
|
||||
let p = wide(path);
|
||||
host!("kernel32.dll", "GetDiskFreeSpaceExW": extern "system" fn(*const u16, *mut u64, *mut u64, *mut u64) -> i32)(
|
||||
p.ptr(),
|
||||
available,
|
||||
total,
|
||||
free,
|
||||
)
|
||||
}
|
||||
|
||||
/// Wants a volume root: a virtual drive answers for the host volume its
|
||||
/// folder is on.
|
||||
pub extern "system" fn GetDiskFreeSpaceW(
|
||||
root: *const u16,
|
||||
sectors_per_cluster: *mut u32,
|
||||
bytes_per_sector: *mut u32,
|
||||
free_clusters: *mut u32,
|
||||
clusters: *mut u32,
|
||||
) -> i32 {
|
||||
let mut p = wide(root);
|
||||
if let Some(host) = &mut p.1
|
||||
&& let [letter, colon, sep, ..] = host[..]
|
||||
&& colon == u16::from(b':')
|
||||
&& SEPARATORS.contains(&sep)
|
||||
{
|
||||
*host = vec![letter, colon, sep, 0];
|
||||
}
|
||||
host!("kernel32.dll", "GetDiskFreeSpaceW": extern "system" fn(*const u16, *mut u32, *mut u32, *mut u32, *mut u32) -> i32)(
|
||||
p.ptr(),
|
||||
sectors_per_cluster,
|
||||
bytes_per_sector,
|
||||
free_clusters,
|
||||
clusters,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn FindFirstFileW(path: *const u16, data: *mut c_void) -> Handle {
|
||||
let p = wide(path);
|
||||
host!("kernel32.dll", "FindFirstFileW": extern "system" fn(*const u16, *mut c_void) -> Handle)(
|
||||
p.ptr(),
|
||||
data,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn FindFirstFileExW(
|
||||
path: *const u16,
|
||||
level: i32,
|
||||
data: *mut c_void,
|
||||
search: i32,
|
||||
filter: *mut c_void,
|
||||
flags: u32,
|
||||
) -> Handle {
|
||||
let p = wide(path);
|
||||
host!("kernel32.dll", "FindFirstFileExW": extern "system" fn(*const u16, i32, *mut c_void, i32, *mut c_void, u32) -> Handle)(
|
||||
p.ptr(),
|
||||
level,
|
||||
data,
|
||||
search,
|
||||
filter,
|
||||
flags,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32 {
|
||||
let (from, to) = (wide(from), wide(to));
|
||||
host!("kernel32.dll", "MoveFileExW": extern "system" fn(*const u16, *const u16, u32) -> i32)(
|
||||
from.ptr(),
|
||||
to.ptr(),
|
||||
flags,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "system" fn SetCurrentDirectoryA(path: *const c_char) -> i32 {
|
||||
match narrow(path) {
|
||||
Some(p) => {
|
||||
host!("kernel32.dll", "SetCurrentDirectoryW": extern "system" fn(*const u16) -> i32)(
|
||||
p.as_ptr(),
|
||||
)
|
||||
}
|
||||
None => {
|
||||
host!("kernel32.dll", "SetCurrentDirectoryA": extern "system" fn(*const c_char) -> i32)(
|
||||
path,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The C runtime (ucrtbase, which the title's CRT imports bind to).
|
||||
|
||||
pub extern "C" fn _wfopen(path: *const u16, mode: *const u16) -> File {
|
||||
let p = wide(path);
|
||||
host!("ucrtbase.dll", "_wfopen": extern "C" fn(*const u16, *const u16) -> File)(p.ptr(), mode)
|
||||
}
|
||||
|
||||
pub extern "C" fn _wfopen_s(out: *mut File, path: *const u16, mode: *const u16) -> i32 {
|
||||
let p = wide(path);
|
||||
host!("ucrtbase.dll", "_wfopen_s": extern "C" fn(*mut File, *const u16, *const u16) -> i32)(
|
||||
out,
|
||||
p.ptr(),
|
||||
mode,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> File {
|
||||
let p = wide(path);
|
||||
host!("ucrtbase.dll", "_wfsopen": extern "C" fn(*const u16, *const u16, i32) -> File)(
|
||||
p.ptr(),
|
||||
mode,
|
||||
share,
|
||||
)
|
||||
}
|
||||
|
||||
pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File {
|
||||
match narrow(path) {
|
||||
Some(p) => _wfopen(p.as_ptr(), widen(mode).as_ptr()),
|
||||
None => {
|
||||
host!("ucrtbase.dll", "fopen": extern "C" fn(*const c_char, *const c_char) -> File)(
|
||||
path, mode,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "C" fn fopen_s(out: *mut File, path: *const c_char, mode: *const c_char) -> i32 {
|
||||
match narrow(path) {
|
||||
Some(p) => _wfopen_s(out, p.as_ptr(), widen(mode).as_ptr()),
|
||||
None => {
|
||||
host!("ucrtbase.dll", "fopen_s": extern "C" fn(*mut File, *const c_char, *const c_char) -> i32)(
|
||||
out, path, mode,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "C" fn _wstat64(path: *const u16, stat: *mut c_void) -> i32 {
|
||||
let p = wide(path);
|
||||
host!("ucrtbase.dll", "_wstat64": extern "C" fn(*const u16, *mut c_void) -> i32)(p.ptr(), stat)
|
||||
}
|
||||
|
||||
pub extern "C" fn _stat64i32(path: *const c_char, stat: *mut c_void) -> i32 {
|
||||
match narrow(path) {
|
||||
Some(p) => {
|
||||
host!("ucrtbase.dll", "_wstat64i32": extern "C" fn(*const u16, *mut c_void) -> i32)(
|
||||
p.as_ptr(),
|
||||
stat,
|
||||
)
|
||||
}
|
||||
None => {
|
||||
host!("ucrtbase.dll", "_stat64i32": extern "C" fn(*const c_char, *mut c_void) -> i32)(
|
||||
path, stat,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "C" fn remove(path: *const c_char) -> i32 {
|
||||
match narrow(path) {
|
||||
Some(p) => host!("ucrtbase.dll", "_wremove": extern "C" fn(*const u16) -> i32)(p.as_ptr()),
|
||||
None => host!("ucrtbase.dll", "remove": extern "C" fn(*const c_char) -> i32)(path),
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "C" fn _wchmod(path: *const u16, mode: i32) -> i32 {
|
||||
let p = wide(path);
|
||||
host!("ucrtbase.dll", "_wchmod": extern "C" fn(*const u16, i32) -> i32)(p.ptr(), mode)
|
||||
}
|
||||
|
||||
pub extern "C" fn _wutime64(path: *const u16, times: *mut c_void) -> i32 {
|
||||
let p = wide(path);
|
||||
host!("ucrtbase.dll", "_wutime64": extern "C" fn(*const u16, *mut c_void) -> i32)(
|
||||
p.ptr(),
|
||||
times,
|
||||
)
|
||||
}
|
||||
|
||||
// The C++ library: `std::basic_filebuf::open` goes through `_Fiopen`.
|
||||
|
||||
const FIOPEN: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z";
|
||||
|
||||
/// `_Fiopen(const char* path, ios_base::openmode, int protection)`.
|
||||
extern "C" fn fiopen(path: *const c_char, mode: i32, protection: i32) -> File {
|
||||
match narrow(path) {
|
||||
Some(p) => {
|
||||
host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)(
|
||||
p.as_ptr(),
|
||||
mode,
|
||||
protection,
|
||||
)
|
||||
}
|
||||
None => {
|
||||
host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z": extern "C" fn(*const c_char, i32, i32) -> File)(
|
||||
path, mode, protection,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "files",
|
||||
dlls: &[
|
||||
"kernel32.dll",
|
||||
"kernelbase.dll",
|
||||
"api-ms-win-core-file-*",
|
||||
"api-ms-win-core-processenvironment-*",
|
||||
"ucrtbase.dll",
|
||||
"api-ms-win-crt-stdio-*",
|
||||
"api-ms-win-crt-filesystem-*",
|
||||
"api-ms-win-crt-time-*",
|
||||
"msvcp140.dll",
|
||||
],
|
||||
exports: vec![
|
||||
hle_export!(CreateFileW),
|
||||
hle_export!(CreateFileA),
|
||||
hle_export!(DeleteFileA),
|
||||
hle_export!(CreateDirectoryW),
|
||||
hle_export!(GetFileAttributesExW),
|
||||
hle_export!(GetDiskFreeSpaceExW),
|
||||
hle_export!(GetDiskFreeSpaceW),
|
||||
hle_export!(FindFirstFileW),
|
||||
hle_export!(FindFirstFileExW),
|
||||
hle_export!(MoveFileExW),
|
||||
hle_export!(SetCurrentDirectoryA),
|
||||
hle_export!(_wfopen),
|
||||
hle_export!(_wfopen_s),
|
||||
hle_export!(_wfsopen),
|
||||
hle_export!(fopen),
|
||||
hle_export!(fopen_s),
|
||||
hle_export!(_wstat64),
|
||||
hle_export!(_stat64i32),
|
||||
hle_export!(remove),
|
||||
hle_export!(_wchmod),
|
||||
hle_export!(_wutime64),
|
||||
HleExport {
|
||||
name: FIOPEN,
|
||||
address: fiopen as *const () as usize,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn w(s: &str) -> Vec<u16> {
|
||||
s.encode_utf16().chain([0]).collect()
|
||||
}
|
||||
|
||||
fn text(v: &[u16]) -> String {
|
||||
String::from_utf16_lossy(&v[..v.len() - 1])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_only_paths_on_mounted_drives() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().to_string_lossy().into_owned();
|
||||
let letter = mount(dir.path()).unwrap();
|
||||
assert_eq!(
|
||||
mount(dir.path()),
|
||||
Some(letter),
|
||||
"mounting twice reuses the letter"
|
||||
);
|
||||
let tr = |s: String| translate(&w(&s)[..s.encode_utf16().count()]).map(|v| text(&v));
|
||||
assert_eq!(
|
||||
tr(format!("{letter}:/a/b.txt")),
|
||||
Some(format!("{root}/a/b.txt"))
|
||||
);
|
||||
let lower = letter.to_ascii_lowercase();
|
||||
assert_eq!(tr(format!("{lower}:\\a")), Some(format!("{root}\\a")));
|
||||
assert_eq!(tr(format!("{letter}:")), Some(format!("{root}\\")));
|
||||
assert_eq!(
|
||||
tr(format!(r"\\?\{letter}:/a/b")),
|
||||
Some(format!(r"\\?\{root}\a\b"))
|
||||
);
|
||||
assert_eq!(tr(r"C:\Windows".into()), None);
|
||||
assert_eq!(tr("relative/path".into()), None);
|
||||
assert_eq!(tr(String::new()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn title_file_calls_land_in_the_host_folder() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let letter = mount(dir.path()).unwrap();
|
||||
const GENERIC_WRITE: u32 = 0x4000_0000;
|
||||
const CREATE_ALWAYS: u32 = 2;
|
||||
let close = host!("kernel32.dll", "CloseHandle": extern "system" fn(Handle) -> i32);
|
||||
let fclose = host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32);
|
||||
|
||||
let path = w(&format!(r"{letter}:\created.bin"));
|
||||
let null = std::ptr::null_mut();
|
||||
let h = CreateFileW(
|
||||
path.as_ptr(),
|
||||
GENERIC_WRITE,
|
||||
0,
|
||||
null,
|
||||
CREATE_ALWAYS,
|
||||
0,
|
||||
null,
|
||||
);
|
||||
assert_ne!(h as isize, -1);
|
||||
close(h);
|
||||
assert!(dir.path().join("created.bin").is_file());
|
||||
|
||||
let path = format!("{letter}:/opened.txt\0");
|
||||
let f = fopen(path.as_ptr().cast(), c"wb".as_ptr());
|
||||
assert!(!f.is_null());
|
||||
fclose(f);
|
||||
assert!(dir.path().join("opened.txt").is_file());
|
||||
|
||||
let path = format!("{letter}:/stream.txt\0");
|
||||
const OUT: i32 = 2;
|
||||
let f = fiopen(path.as_ptr().cast(), OUT, 0x40);
|
||||
assert!(!f.is_null());
|
||||
fclose(f);
|
||||
assert!(dir.path().join("stream.txt").is_file());
|
||||
|
||||
assert_eq!(remove(path.as_ptr().cast()), 0);
|
||||
assert!(!dir.path().join("stream.txt").exists());
|
||||
|
||||
// Other paths pass through untouched.
|
||||
let host_path = format!("{}\0", dir.path().join("plain.txt").display());
|
||||
let f = fopen(host_path.as_ptr().cast(), c"wb".as_ptr());
|
||||
assert!(!f.is_null());
|
||||
fclose(f);
|
||||
assert!(dir.path().join("plain.txt").is_file());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
//! `gameinput.dll`: input devices. For now nothing is ever connected:
|
||||
//! readings and device lookups fail as they do with no device plugged in,
|
||||
//! callbacks are accepted and never called.
|
||||
#![allow(non_snake_case)]
|
||||
// Title code calls these through the object, passing pointers the real API
|
||||
// would trust.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use super::xasync::{E_INVALIDARG, E_NOTIMPL};
|
||||
use super::xgameruntime::{HRESULT, S_OK};
|
||||
use crate::{HleExport, HleModule};
|
||||
|
||||
/// The documented "no such reading" and "no such device" errors.
|
||||
pub const READING_NOT_FOUND: HRESULT = 0x838A_0003_u32 as i32;
|
||||
pub const DEVICE_NOT_FOUND: HRESULT = 0x838A_0002_u32 as i32;
|
||||
const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32;
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Object {
|
||||
vtable: &'static Vtable,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Vtable([*const (); 22]);
|
||||
// SAFETY: function addresses only.
|
||||
unsafe impl Sync for Vtable {}
|
||||
|
||||
static OBJECT: Object = Object { vtable: &VTABLE };
|
||||
|
||||
type This = *const Object;
|
||||
type Out = *mut *const c_void;
|
||||
|
||||
/// The DLL's only export (ordinal 1): the input object, static and shared.
|
||||
pub extern "system" fn GameInputCreate(out: *mut This) -> HRESULT {
|
||||
tracing::info!("GameInputCreate: no input devices");
|
||||
if out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: checked non-null; the title passes room for a pointer.
|
||||
unsafe { out.write(&OBJECT) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Clears a COM out pointer and returns `hr`.
|
||||
fn fail(out: Out, hr: HRESULT) -> HRESULT {
|
||||
if !out.is_null() {
|
||||
// SAFETY: checked non-null; the title passes room for a pointer.
|
||||
unsafe { out.write(std::ptr::null()) };
|
||||
}
|
||||
hr
|
||||
}
|
||||
|
||||
extern "system" fn query_interface(_: This, _iid: *const c_void, out: Out) -> HRESULT {
|
||||
tracing::warn!("input QueryInterface not implemented");
|
||||
fail(out, E_NOINTERFACE)
|
||||
}
|
||||
extern "system" fn add_ref(_: This) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
static START: LazyLock<Instant> = LazyLock::new(Instant::now);
|
||||
|
||||
/// Microseconds; only ever compared with readings, and there are none.
|
||||
extern "system" fn timestamp(_: This) -> u64 {
|
||||
START.elapsed().as_micros() as u64
|
||||
}
|
||||
|
||||
extern "system" fn current_reading(
|
||||
_: This,
|
||||
_kind: u32,
|
||||
_device: *const c_void,
|
||||
out: Out,
|
||||
) -> HRESULT {
|
||||
fail(out, READING_NOT_FOUND)
|
||||
}
|
||||
extern "system" fn relative_reading(
|
||||
_: This,
|
||||
_reference: *const c_void,
|
||||
_kind: u32,
|
||||
_device: *const c_void,
|
||||
out: Out,
|
||||
) -> HRESULT {
|
||||
fail(out, READING_NOT_FOUND)
|
||||
}
|
||||
extern "system" fn temporal_reading(
|
||||
_: This,
|
||||
_time: u64,
|
||||
_device: *const c_void,
|
||||
out: Out,
|
||||
) -> HRESULT {
|
||||
fail(out, READING_NOT_FOUND)
|
||||
}
|
||||
|
||||
static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
fn token(out: *mut u64) -> HRESULT {
|
||||
if !out.is_null() {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(NEXT_TOKEN.fetch_add(1, Ordering::Relaxed)) };
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn register_reading(
|
||||
_: This,
|
||||
_device: *const c_void,
|
||||
_kind: u32,
|
||||
_threshold: f32,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
out: *mut u64,
|
||||
) -> HRESULT {
|
||||
token(out)
|
||||
}
|
||||
/// Enumerating existing devices finds none, so the callback never runs.
|
||||
extern "system" fn register_device(
|
||||
_: This,
|
||||
_device: *const c_void,
|
||||
kind: u32,
|
||||
_status: u32,
|
||||
_enumeration: u32,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
out: *mut u64,
|
||||
) -> HRESULT {
|
||||
tracing::info!(
|
||||
kind = format_args!("{kind:#x}"),
|
||||
"input device callback: no devices"
|
||||
);
|
||||
token(out)
|
||||
}
|
||||
/// Guide button and keyboard layout callbacks.
|
||||
extern "system" fn register_other(
|
||||
_: This,
|
||||
_device: *const c_void,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
out: *mut u64,
|
||||
) -> HRESULT {
|
||||
token(out)
|
||||
}
|
||||
extern "system" fn stop_callback(_: This, _token: u64) {}
|
||||
extern "system" fn unregister_callback(_: This, _token: u64, _timeout: u64) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Dispatcher and aggregate device: not needed while nothing is connected.
|
||||
extern "system" fn create_dispatcher(_: This, out: Out) -> HRESULT {
|
||||
tracing::warn!("input dispatcher not implemented");
|
||||
fail(out, E_NOTIMPL)
|
||||
}
|
||||
extern "system" fn create_aggregate(_: This, _kind: u32, out: Out) -> HRESULT {
|
||||
tracing::warn!("aggregate input device not implemented");
|
||||
fail(out, E_NOTIMPL)
|
||||
}
|
||||
/// Lookup by id, object, platform handle or platform string.
|
||||
extern "system" fn find_device(_: This, _value: *const c_void, out: Out) -> HRESULT {
|
||||
fail(out, DEVICE_NOT_FOUND)
|
||||
}
|
||||
extern "system" fn enable_oem_device(
|
||||
_: This,
|
||||
_vendor: u16,
|
||||
_product: u16,
|
||||
_interface: u8,
|
||||
_collection: u8,
|
||||
) -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
extern "system" fn set_focus_policy(_: This, _policy: u32) {}
|
||||
|
||||
static VTABLE: Vtable = Vtable([
|
||||
query_interface as *const (), // 0x00
|
||||
add_ref as *const (), // 0x08 AddRef
|
||||
add_ref as *const (), // 0x10 Release: the object is static
|
||||
timestamp as *const (), // 0x18
|
||||
current_reading as *const (), // 0x20
|
||||
relative_reading as *const (), // 0x28 next
|
||||
relative_reading as *const (), // 0x30 previous
|
||||
temporal_reading as *const (), // 0x38
|
||||
register_reading as *const (), // 0x40
|
||||
register_device as *const (), // 0x48
|
||||
register_other as *const (), // 0x50 guide button
|
||||
register_other as *const (), // 0x58 keyboard layout
|
||||
stop_callback as *const (), // 0x60
|
||||
unregister_callback as *const (), // 0x68
|
||||
create_dispatcher as *const (), // 0x70
|
||||
create_aggregate as *const (), // 0x78
|
||||
find_device as *const (), // 0x80 by id
|
||||
find_device as *const (), // 0x88 by object
|
||||
find_device as *const (), // 0x90 by platform handle
|
||||
find_device as *const (), // 0x98 by platform string
|
||||
enable_oem_device as *const (), // 0xa0
|
||||
set_focus_policy as *const (), // 0xa8
|
||||
]);
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "gameinput",
|
||||
dlls: &["gameinput.dll"],
|
||||
// Titles import it by ordinal only.
|
||||
exports: vec![HleExport {
|
||||
name: "#1",
|
||||
address: GameInputCreate as *const () as usize,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::HleResolver;
|
||||
use crate::HostPolicy;
|
||||
use victory_loader::Provenance;
|
||||
use victory_pe::ImportSymbol;
|
||||
|
||||
fn slot<F: Copy>(object: This, offset: usize) -> F {
|
||||
// SAFETY: `object` is ours.
|
||||
let f = unsafe { (*object).vtable.0[offset / 8] };
|
||||
// SAFETY: the caller names the slot's signature.
|
||||
unsafe { std::mem::transmute_copy(&f) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinal_one_resolves_to_create() {
|
||||
let r = HleResolver::new(HostPolicy::none());
|
||||
assert_eq!(
|
||||
r.classify("GameInput.dll", &ImportSymbol::Ordinal(1)),
|
||||
Some(Provenance::Hle)
|
||||
);
|
||||
assert_eq!(r.classify("GameInput.dll", &ImportSymbol::Ordinal(2)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_sees_no_devices() {
|
||||
type Register = extern "system" fn(
|
||||
This,
|
||||
*const c_void,
|
||||
u32,
|
||||
u32,
|
||||
u32,
|
||||
*mut c_void,
|
||||
*const c_void,
|
||||
*mut u64,
|
||||
) -> HRESULT;
|
||||
type Reading = extern "system" fn(This, u32, *const c_void, Out) -> HRESULT;
|
||||
type Find = extern "system" fn(This, *const c_void, Out) -> HRESULT;
|
||||
|
||||
let mut input = std::ptr::null();
|
||||
assert_eq!(GameInputCreate(&mut input), S_OK);
|
||||
assert!(!input.is_null());
|
||||
|
||||
let mut token = 0;
|
||||
let register = slot::<Register>(input, 0x48);
|
||||
let null = std::ptr::null_mut();
|
||||
assert_eq!(
|
||||
register(input, null, 0x40130, 1, 1, null, null, &mut token),
|
||||
S_OK
|
||||
);
|
||||
assert_ne!(token, 0);
|
||||
|
||||
let mut out = 0x1234 as *const c_void;
|
||||
let reading = slot::<Reading>(input, 0x20);
|
||||
assert_eq!(reading(input, 4, null, &mut out), READING_NOT_FOUND);
|
||||
assert!(out.is_null());
|
||||
out = 0x1234 as *const c_void;
|
||||
let find = slot::<Find>(input, 0x80);
|
||||
assert_eq!(find(input, null, &mut out), DEVICE_NOT_FOUND);
|
||||
assert!(out.is_null());
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,13 @@
|
||||
//! Only the differences live here; everything else passes through to the
|
||||
//! host (see `HostPolicy`).
|
||||
#![allow(non_snake_case)]
|
||||
// Title code calls these through its import table, passing pointers the real
|
||||
// API would trust.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::ffi::{CStr, c_void};
|
||||
|
||||
use crate::{HleModule, hle_export, runtime};
|
||||
use crate::{HleModule, HostPolicy, hle_export, registry, runtime};
|
||||
|
||||
/// `GetModuleHandleW(NULL)` must return the title's image, not our exe.
|
||||
pub extern "system" fn GetModuleHandleW(name: *const u16) -> *mut c_void {
|
||||
@@ -24,6 +27,207 @@ pub extern "system" fn GetModuleHandleA(name: *const u8) -> *mut c_void {
|
||||
host::get_module_handle_a(name)
|
||||
}
|
||||
|
||||
/// A title image's path is its original file, not our cache copy;
|
||||
/// `NULL` means the title's exe.
|
||||
pub extern "system" fn GetModuleFileNameW(module: *mut c_void, out: *mut u16, size: u32) -> u32 {
|
||||
let Some(path) = title_path(module) else {
|
||||
return host::get_module_file_name_w(module, out, size);
|
||||
};
|
||||
let wide: Vec<u16> = path.encode_utf16().collect();
|
||||
// SAFETY: the title passes a buffer of `size` characters.
|
||||
copy_truncated(&wide, unsafe {
|
||||
std::slice::from_raw_parts_mut(out, size as usize)
|
||||
})
|
||||
}
|
||||
|
||||
/// See [`GetModuleFileNameW`].
|
||||
pub extern "system" fn GetModuleFileNameA(module: *mut c_void, out: *mut u8, size: u32) -> u32 {
|
||||
let Some(path) = title_path(module) else {
|
||||
return host::get_module_file_name_a(module, out, size);
|
||||
};
|
||||
// SAFETY: the title passes a buffer of `size` bytes.
|
||||
copy_truncated(path.as_bytes(), unsafe {
|
||||
std::slice::from_raw_parts_mut(out, size as usize)
|
||||
})
|
||||
}
|
||||
|
||||
fn title_path(module: *mut c_void) -> Option<String> {
|
||||
let base = if module.is_null() {
|
||||
runtime::main_image()?
|
||||
} else {
|
||||
module as usize
|
||||
};
|
||||
Some(runtime::image_path(base)?.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
/// `GetModuleFileName`'s contract: copy with a NUL; if it does not fit,
|
||||
/// truncate to the buffer, report `ERROR_INSUFFICIENT_BUFFER` and return
|
||||
/// the buffer size.
|
||||
fn copy_truncated<T: Copy + Default>(text: &[T], out: &mut [T]) -> u32 {
|
||||
let Some(room) = out.len().checked_sub(1) else {
|
||||
host::set_last_error(ERROR_INSUFFICIENT_BUFFER);
|
||||
return 0;
|
||||
};
|
||||
let n = text.len().min(room);
|
||||
out[..n].copy_from_slice(&text[..n]);
|
||||
out[n] = T::default();
|
||||
if n < text.len() {
|
||||
host::set_last_error(ERROR_INSUFFICIENT_BUFFER);
|
||||
return out.len() as u32;
|
||||
}
|
||||
n as u32
|
||||
}
|
||||
|
||||
const ERROR_INSUFFICIENT_BUFFER: u32 = 122;
|
||||
|
||||
/// Console-only DLLs we implement load as a pseudo handle (titles load
|
||||
/// `xgameruntime.dll` this way); anything else loads on the host.
|
||||
pub extern "system" fn LoadLibraryExA(
|
||||
name: *const u8,
|
||||
file: *mut c_void,
|
||||
flags: u32,
|
||||
) -> *mut c_void {
|
||||
if !name.is_null() {
|
||||
// SAFETY: the title passes a NUL-terminated file name.
|
||||
let text = unsafe { CStr::from_ptr(name.cast()) }.to_string_lossy();
|
||||
if let Some(handle) = console_module(&text) {
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
host::load_library_ex_a(name, file, flags)
|
||||
}
|
||||
|
||||
/// See [`LoadLibraryExA`].
|
||||
pub extern "system" fn LoadLibraryExW(
|
||||
name: *const u16,
|
||||
file: *mut c_void,
|
||||
flags: u32,
|
||||
) -> *mut c_void {
|
||||
if !name.is_null() {
|
||||
// SAFETY: the title passes a NUL-terminated file name.
|
||||
let text = unsafe {
|
||||
let len = (0..).take_while(|&i| *name.add(i) != 0).count();
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(name, len))
|
||||
};
|
||||
if let Some(handle) = console_module(&text) {
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
host::load_library_ex_w(name, file, flags)
|
||||
}
|
||||
|
||||
pub extern "system" fn LoadLibraryA(name: *const u8) -> *mut c_void {
|
||||
LoadLibraryExA(name, std::ptr::null_mut(), 0)
|
||||
}
|
||||
|
||||
pub extern "system" fn LoadLibraryW(name: *const u16) -> *mut c_void {
|
||||
LoadLibraryExW(name, std::ptr::null_mut(), 0)
|
||||
}
|
||||
|
||||
/// Looks up our implementations behind a pseudo handle; real modules go to
|
||||
/// the host.
|
||||
pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void {
|
||||
let Some(m) = registry().iter().find(|m| handle(m) == module) else {
|
||||
return host::get_proc_address(module, name);
|
||||
};
|
||||
// Values below 0x10000 are ordinals; we export by name only.
|
||||
if (name as usize) < 0x1_0000 {
|
||||
tracing::warn!(
|
||||
module = m.name,
|
||||
ordinal = name as usize,
|
||||
"GetProcAddress by ordinal"
|
||||
);
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
// SAFETY: not an ordinal, so the title passes a NUL-terminated name.
|
||||
let name = unsafe { CStr::from_ptr(name.cast()) }.to_string_lossy();
|
||||
match m.exports.iter().find(|e| e.name == name) {
|
||||
Some(e) => e.address as *mut c_void,
|
||||
None => {
|
||||
tracing::warn!(module = m.name, %name, "GetProcAddress: not implemented");
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub extern "system" fn FreeLibrary(module: *mut c_void) -> i32 {
|
||||
if registry().iter().any(|m| handle(m) == module) {
|
||||
return 1;
|
||||
}
|
||||
host::free_library(module)
|
||||
}
|
||||
|
||||
/// Title debug output goes to our log (no debugger needs to be attached).
|
||||
pub extern "system" fn OutputDebugStringA(text: *const u8) {
|
||||
if !text.is_null() {
|
||||
// SAFETY: the title passes a NUL-terminated string.
|
||||
let text = unsafe { CStr::from_ptr(text.cast()) }.to_string_lossy();
|
||||
tracing::info!(target: "title", "{}", text.trim_end());
|
||||
}
|
||||
}
|
||||
|
||||
/// See [`OutputDebugStringA`].
|
||||
pub extern "system" fn OutputDebugStringW(text: *const u16) {
|
||||
if !text.is_null() {
|
||||
// SAFETY: the title passes a NUL-terminated string.
|
||||
let text = unsafe {
|
||||
let len = (0..).take_while(|&i| *text.add(i) != 0).count();
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(text, len))
|
||||
};
|
||||
tracing::info!(target: "title", "{}", text.trim_end());
|
||||
}
|
||||
}
|
||||
|
||||
/// The CRT's `exit`, through which the title's entry point returns: logs
|
||||
/// the code and the caller, then exits on the host.
|
||||
pub extern "C" fn exit(code: i32) -> ! {
|
||||
tracing::warn!(code, from = %host::callers(), "title exits");
|
||||
host::exit(code)
|
||||
}
|
||||
|
||||
/// The CRT's `abort` (also reached from `terminate`): logged like [`exit`].
|
||||
pub extern "C" fn abort() -> ! {
|
||||
tracing::error!(from = %host::callers(), "title aborts");
|
||||
host::abort()
|
||||
}
|
||||
|
||||
/// The CRT's `terminate` and the STL's invalid-argument exit: logged, then
|
||||
/// the host's `abort`.
|
||||
pub extern "C" fn terminate() -> ! {
|
||||
tracing::error!(from = %host::callers(), "title calls terminate");
|
||||
host::abort()
|
||||
}
|
||||
|
||||
/// See [`terminate`].
|
||||
pub extern "C" fn _invalid_parameter_noinfo_noreturn() -> ! {
|
||||
tracing::error!(from = %host::callers(), "title passed an invalid parameter");
|
||||
host::abort()
|
||||
}
|
||||
|
||||
/// See [`exit`]; only the current process is logged.
|
||||
pub extern "system" fn TerminateProcess(process: *mut c_void, code: u32) -> i32 {
|
||||
if process as isize == -1 {
|
||||
tracing::warn!(code, from = %host::callers(), "title terminates the process");
|
||||
}
|
||||
host::terminate_process(process, code)
|
||||
}
|
||||
|
||||
/// The pseudo handle of one of our modules: its address, never a real image.
|
||||
fn handle(m: &HleModule) -> *mut c_void {
|
||||
m as *const HleModule as *mut c_void
|
||||
}
|
||||
|
||||
fn console_module(path: &str) -> Option<*mut c_void> {
|
||||
let file = path.rsplit(['\\', '/']).next().unwrap_or(path);
|
||||
// DLLs the host has too are real host modules, whatever `--strict` says.
|
||||
if HostPolicy::default().allows(file) {
|
||||
return None;
|
||||
}
|
||||
let m = registry().iter().find(|m| m.serves(file))?;
|
||||
tracing::info!(dll = file, "loaded as a pseudo module");
|
||||
Some(handle(m))
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "kernel",
|
||||
@@ -31,8 +235,29 @@ pub(crate) fn module() -> HleModule {
|
||||
"kernel32.dll",
|
||||
"kernelbase.dll",
|
||||
"api-ms-win-core-libraryloader-*",
|
||||
"api-ms-win-core-processthreads-*",
|
||||
"api-ms-win-core-debug-*",
|
||||
"api-ms-win-crt-runtime-*",
|
||||
],
|
||||
exports: vec![
|
||||
hle_export!(GetModuleHandleW),
|
||||
hle_export!(GetModuleHandleA),
|
||||
hle_export!(GetModuleFileNameW),
|
||||
hle_export!(GetModuleFileNameA),
|
||||
hle_export!(LoadLibraryExA),
|
||||
hle_export!(LoadLibraryExW),
|
||||
hle_export!(LoadLibraryA),
|
||||
hle_export!(LoadLibraryW),
|
||||
hle_export!(GetProcAddress),
|
||||
hle_export!(FreeLibrary),
|
||||
hle_export!(OutputDebugStringA),
|
||||
hle_export!(OutputDebugStringW),
|
||||
hle_export!(exit),
|
||||
hle_export!(abort),
|
||||
hle_export!(terminate),
|
||||
hle_export!(_invalid_parameter_noinfo_noreturn),
|
||||
hle_export!(TerminateProcess),
|
||||
],
|
||||
exports: vec![hle_export!(GetModuleHandleW), hle_export!(GetModuleHandleA)],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,14 +265,105 @@ pub(crate) fn module() -> HleModule {
|
||||
mod host {
|
||||
use std::ffi::c_void;
|
||||
|
||||
use windows_sys::Win32::Foundation::{FreeLibrary, SetLastError};
|
||||
use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace;
|
||||
use windows_sys::Win32::System::LibraryLoader::{
|
||||
GetModuleFileNameA, GetModuleFileNameW, GetModuleHandleA, GetModuleHandleW, GetProcAddress,
|
||||
LoadLibraryExA, LoadLibraryExW,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::TerminateProcess;
|
||||
|
||||
unsafe extern "C" {
|
||||
#[link_name = "exit"]
|
||||
fn crt_exit(code: i32) -> !;
|
||||
#[link_name = "abort"]
|
||||
fn crt_abort() -> !;
|
||||
}
|
||||
|
||||
// SAFETY (every function): forwarding the title's own arguments to the
|
||||
// host API of the same name.
|
||||
|
||||
pub(super) fn get_module_handle_w(name: *const u16) -> *mut c_void {
|
||||
// SAFETY: forwarding the title's own argument to the host API.
|
||||
unsafe { windows_sys::Win32::System::LibraryLoader::GetModuleHandleW(name) }
|
||||
// SAFETY: see above.
|
||||
unsafe { GetModuleHandleW(name) }
|
||||
}
|
||||
|
||||
pub(super) fn get_module_handle_a(name: *const u8) -> *mut c_void {
|
||||
// SAFETY: forwarding the title's own argument to the host API.
|
||||
unsafe { windows_sys::Win32::System::LibraryLoader::GetModuleHandleA(name) }
|
||||
// SAFETY: see above.
|
||||
unsafe { GetModuleHandleA(name) }
|
||||
}
|
||||
|
||||
pub(super) fn get_module_file_name_w(module: *mut c_void, out: *mut u16, size: u32) -> u32 {
|
||||
// SAFETY: see above.
|
||||
unsafe { GetModuleFileNameW(module, out, size) }
|
||||
}
|
||||
|
||||
pub(super) fn get_module_file_name_a(module: *mut c_void, out: *mut u8, size: u32) -> u32 {
|
||||
// SAFETY: see above.
|
||||
unsafe { GetModuleFileNameA(module, out, size) }
|
||||
}
|
||||
|
||||
pub(super) fn set_last_error(code: u32) {
|
||||
// SAFETY: see above.
|
||||
unsafe { SetLastError(code) }
|
||||
}
|
||||
|
||||
pub(super) fn load_library_ex_a(name: *const u8, file: *mut c_void, flags: u32) -> *mut c_void {
|
||||
// SAFETY: see above.
|
||||
unsafe { LoadLibraryExA(name, file, flags) }
|
||||
}
|
||||
|
||||
pub(super) fn load_library_ex_w(
|
||||
name: *const u16,
|
||||
file: *mut c_void,
|
||||
flags: u32,
|
||||
) -> *mut c_void {
|
||||
// SAFETY: see above.
|
||||
unsafe { LoadLibraryExW(name, file, flags) }
|
||||
}
|
||||
|
||||
pub(super) fn get_proc_address(module: *mut c_void, name: *const u8) -> *mut c_void {
|
||||
// SAFETY: see above.
|
||||
unsafe { GetProcAddress(module, name) }.map_or(std::ptr::null_mut(), |f| f as *mut c_void)
|
||||
}
|
||||
|
||||
pub(super) fn free_library(module: *mut c_void) -> i32 {
|
||||
// SAFETY: see above.
|
||||
unsafe { FreeLibrary(module) }
|
||||
}
|
||||
|
||||
pub(super) fn exit(code: i32) -> ! {
|
||||
// SAFETY: see above.
|
||||
unsafe { crt_exit(code) }
|
||||
}
|
||||
|
||||
pub(super) fn abort() -> ! {
|
||||
// SAFETY: see above.
|
||||
unsafe { crt_abort() }
|
||||
}
|
||||
|
||||
pub(super) fn terminate_process(process: *mut c_void, code: u32) -> i32 {
|
||||
// SAFETY: see above.
|
||||
unsafe { TerminateProcess(process, code) }
|
||||
}
|
||||
|
||||
/// Our caller's callers, as `module+rva`.
|
||||
pub(super) fn callers() -> String {
|
||||
let mut frames = [std::ptr::null_mut(); 12];
|
||||
// SAFETY: fills at most `frames.len()` return addresses.
|
||||
let n = unsafe {
|
||||
RtlCaptureStackBackTrace(
|
||||
2,
|
||||
frames.len() as u32,
|
||||
frames.as_mut_ptr(),
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
let names: Vec<_> = frames[..usize::from(n)]
|
||||
.iter()
|
||||
.map(|&f| victory_loader::locate(f as usize))
|
||||
.collect();
|
||||
names.join(" < ")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,4 +378,70 @@ mod host {
|
||||
pub(super) fn get_module_handle_a(_: *const u8) -> *mut c_void {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
|
||||
pub(super) fn load_library_ex_a(_: *const u8, _: *mut c_void, _: u32) -> *mut c_void {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
|
||||
pub(super) fn get_module_file_name_w(_: *mut c_void, _: *mut u16, _: u32) -> u32 {
|
||||
0
|
||||
}
|
||||
|
||||
pub(super) fn get_module_file_name_a(_: *mut c_void, _: *mut u8, _: u32) -> u32 {
|
||||
0
|
||||
}
|
||||
|
||||
pub(super) fn set_last_error(_: u32) {}
|
||||
|
||||
pub(super) fn load_library_ex_w(_: *const u16, _: *mut c_void, _: u32) -> *mut c_void {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
|
||||
pub(super) fn get_proc_address(_: *mut c_void, _: *const u8) -> *mut c_void {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
|
||||
pub(super) fn free_library(_: *mut c_void) -> i32 {
|
||||
0
|
||||
}
|
||||
|
||||
pub(super) fn exit(code: i32) -> ! {
|
||||
std::process::exit(code)
|
||||
}
|
||||
|
||||
pub(super) fn abort() -> ! {
|
||||
std::process::abort()
|
||||
}
|
||||
|
||||
pub(super) fn terminate_process(_: *mut c_void, code: u32) -> i32 {
|
||||
std::process::exit(code as i32)
|
||||
}
|
||||
|
||||
pub(super) fn callers() -> String {
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn title_images_report_their_original_path() {
|
||||
let base = 0x7000_0000_0000;
|
||||
runtime::set_image_path(base, std::path::Path::new(r"C:\title\game.exe"));
|
||||
let module = base as *mut c_void;
|
||||
let mut buf = [0xFFFFu16; 32];
|
||||
let n = GetModuleFileNameW(module, buf.as_mut_ptr(), buf.len() as u32);
|
||||
assert_eq!(
|
||||
String::from_utf16_lossy(&buf[..n as usize]),
|
||||
r"C:\title\game.exe"
|
||||
);
|
||||
assert_eq!(buf[n as usize], 0);
|
||||
|
||||
// Too small: truncated, NUL-terminated, the buffer size returned.
|
||||
let mut small = [0u8; 4];
|
||||
assert_eq!(GetModuleFileNameA(module, small.as_mut_ptr(), 4), 4);
|
||||
assert_eq!(&small, &[b'C', b':', b'\\', 0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
//! The title's life cycle. A console title is never told it is closing:
|
||||
//! quitting it first suspends it (its suspend routines run, and it has a
|
||||
//! second to save) and then ends the process. Closing the title's window
|
||||
//! does the same here.
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Mutex, MutexGuard};
|
||||
use std::time::Duration;
|
||||
|
||||
use windows_sys::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, WPARAM};
|
||||
use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, HMENU};
|
||||
use windows_sys::core::{PCSTR, PCWSTR, w};
|
||||
|
||||
use crate::{HleModule, hle_export};
|
||||
|
||||
type Routine = extern "system" fn(quiesced: u8, context: *mut c_void);
|
||||
|
||||
/// Registration id, routine and context of each suspend routine.
|
||||
static ROUTINES: Mutex<Vec<(usize, Routine, usize)>> = Mutex::new(Vec::new());
|
||||
|
||||
fn routines() -> MutexGuard<'static, Vec<(usize, Routine, usize)>> {
|
||||
ROUTINES.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// How long the console lets suspend routines run before it ends the title.
|
||||
const SUSPEND_DEADLINE: Duration = Duration::from_secs(1);
|
||||
|
||||
const ERROR_INVALID_PARAMETER: u32 = 87;
|
||||
|
||||
pub extern "system" fn RegisterAppStateChangeNotification(
|
||||
routine: Option<Routine>,
|
||||
context: *mut c_void,
|
||||
registration: *mut usize,
|
||||
) -> u32 {
|
||||
let Some(routine) = routine else {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
};
|
||||
if registration.is_null() {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
}
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(1);
|
||||
let id = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
routines().push((id, routine, context as usize));
|
||||
// SAFETY: checked non-null; the title passes room for its registration.
|
||||
unsafe { registration.write(id) };
|
||||
0
|
||||
}
|
||||
|
||||
pub extern "system" fn UnregisterAppStateChangeNotification(registration: usize) {
|
||||
routines().retain(|&(id, ..)| id != registration);
|
||||
}
|
||||
|
||||
/// The window procedure a title window had before ours.
|
||||
const TITLE_PROC: PCWSTR = w!("victory.wndproc");
|
||||
|
||||
pub extern "system" fn CreateWindowExW(
|
||||
ex_style: u32,
|
||||
class: PCWSTR,
|
||||
name: PCWSTR,
|
||||
style: u32,
|
||||
x: i32,
|
||||
y: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
parent: HWND,
|
||||
menu: HMENU,
|
||||
instance: HINSTANCE,
|
||||
param: *const c_void,
|
||||
) -> HWND {
|
||||
// SAFETY: the title's own arguments, forwarded.
|
||||
let hwnd = unsafe {
|
||||
wm::CreateWindowExW(
|
||||
ex_style, class, name, style, x, y, width, height, parent, menu, instance, param,
|
||||
)
|
||||
};
|
||||
hook(hwnd);
|
||||
hwnd
|
||||
}
|
||||
|
||||
/// See [`CreateWindowExW`].
|
||||
pub extern "system" fn CreateWindowExA(
|
||||
ex_style: u32,
|
||||
class: PCSTR,
|
||||
name: PCSTR,
|
||||
style: u32,
|
||||
x: i32,
|
||||
y: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
parent: HWND,
|
||||
menu: HMENU,
|
||||
instance: HINSTANCE,
|
||||
param: *const c_void,
|
||||
) -> HWND {
|
||||
// SAFETY: the title's own arguments, forwarded.
|
||||
let hwnd = unsafe {
|
||||
wm::CreateWindowExA(
|
||||
ex_style, class, name, style, x, y, width, height, parent, menu, instance, param,
|
||||
)
|
||||
};
|
||||
hook(hwnd);
|
||||
hwnd
|
||||
}
|
||||
|
||||
/// Puts our procedure in front of the title's.
|
||||
fn hook(hwnd: HWND) {
|
||||
if hwnd.is_null() {
|
||||
return;
|
||||
}
|
||||
// SAFETY: a window this thread just created. The title's procedure is
|
||||
// stored before ours can run.
|
||||
unsafe {
|
||||
let title = wm::GetWindowLongPtrW(hwnd, wm::GWLP_WNDPROC);
|
||||
wm::SetPropW(hwnd, TITLE_PROC, title as *mut c_void);
|
||||
wm::SetWindowLongPtrW(hwnd, wm::GWLP_WNDPROC, window_proc as *const () as isize);
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn window_proc(
|
||||
hwnd: HWND,
|
||||
message: u32,
|
||||
wparam: WPARAM,
|
||||
lparam: LPARAM,
|
||||
) -> LRESULT {
|
||||
// A user close (close button, Alt+F4, window or taskbar menu); a
|
||||
// console title never sees one, nor a WM_CLOSE from it.
|
||||
if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_CLOSE as usize {
|
||||
quit();
|
||||
return 0;
|
||||
}
|
||||
// SAFETY: the procedure `hook` stored, called the way the system would.
|
||||
unsafe {
|
||||
let title = wm::GetPropW(hwnd, TITLE_PROC);
|
||||
if message == wm::WM_NCDESTROY {
|
||||
wm::RemovePropW(hwnd, TITLE_PROC);
|
||||
}
|
||||
let title = std::mem::transmute::<*mut c_void, wm::WNDPROC>(title);
|
||||
wm::CallWindowProcW(title, hwnd, message, wparam, lparam)
|
||||
}
|
||||
}
|
||||
|
||||
/// Suspends the title as the console would on quit, then ends the process.
|
||||
fn quit() {
|
||||
static QUITTING: AtomicBool = AtomicBool::new(false);
|
||||
if QUITTING.swap(true, Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let suspend = routines().clone();
|
||||
tracing::info!(routines = suspend.len(), "window closed: suspending the title");
|
||||
// Not on the window thread: titles hand the suspend to that thread and
|
||||
// wait for it inside the routine.
|
||||
std::thread::spawn(move || {
|
||||
for (_, routine, context) in suspend {
|
||||
routine(1, context as *mut c_void);
|
||||
}
|
||||
tracing::info!("title suspended; ending it");
|
||||
end();
|
||||
});
|
||||
std::thread::spawn(|| {
|
||||
std::thread::sleep(SUSPEND_DEADLINE);
|
||||
tracing::warn!("title did not finish suspending in time; ending it");
|
||||
end();
|
||||
});
|
||||
}
|
||||
|
||||
fn end() {
|
||||
// SAFETY: ends this process, as the console ends a suspended title.
|
||||
unsafe { TerminateProcess(GetCurrentProcess(), 0) };
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "lifecycle",
|
||||
dlls: &[
|
||||
"api-ms-win-core-psm-appnotify-*",
|
||||
"ext-ms-win-rtcore-ntuser-window-*",
|
||||
],
|
||||
exports: vec![
|
||||
hle_export!(RegisterAppStateChangeNotification),
|
||||
hle_export!(UnregisterAppStateChangeNotification),
|
||||
hle_export!(CreateWindowExW),
|
||||
hle_export!(CreateWindowExA),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
extern "system" fn noop(_: u8, _: *mut c_void) {}
|
||||
|
||||
#[test]
|
||||
fn registrations_come_and_go() {
|
||||
let (mut a, mut b) = (0, 0);
|
||||
assert_eq!(
|
||||
RegisterAppStateChangeNotification(Some(noop), std::ptr::null_mut(), &mut a),
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
RegisterAppStateChangeNotification(Some(noop), std::ptr::null_mut(), &mut b),
|
||||
0
|
||||
);
|
||||
UnregisterAppStateChangeNotification(a);
|
||||
let left: Vec<_> = routines().iter().map(|r| r.0).collect();
|
||||
assert_eq!(left, [b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hooked_windows_still_reach_the_title_procedure() {
|
||||
let null = std::ptr::null_mut();
|
||||
let hwnd = CreateWindowExW(
|
||||
0,
|
||||
w!("STATIC"),
|
||||
w!("before"),
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
10,
|
||||
10,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
std::ptr::null(),
|
||||
);
|
||||
assert!(!hwnd.is_null());
|
||||
let mut text = [0u16; 16];
|
||||
// SAFETY: our window; the buffer holds 16 characters.
|
||||
unsafe {
|
||||
wm::SetWindowTextW(hwnd, w!("after"));
|
||||
let n = wm::GetWindowTextW(hwnd, text.as_mut_ptr(), 16);
|
||||
assert_eq!(String::from_utf16_lossy(&text[..n as usize]), "after");
|
||||
assert!(!wm::GetPropW(hwnd, TITLE_PROC).is_null());
|
||||
wm::DestroyWindow(hwnd);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,15 +5,41 @@
|
||||
//! Run `victory census` over your titles to see what is still missing.
|
||||
//!
|
||||
//! Planned areas (driven by census results, not by completeness):
|
||||
//! `xmem` (console memory types, GPU-visible allocations), `file` (package
|
||||
//! paths), `thread` (TLS callbacks for title threads), `d3d12x` (bridge to
|
||||
//! `victory-gpu`), `xaudio2`, `gameinput`, `xuser`/`xstore` stubs.
|
||||
//! `file` (package paths), `thread` (TLS callbacks for title threads),
|
||||
//! `xaudio2`, `xstore` stubs.
|
||||
|
||||
pub mod audio;
|
||||
pub mod d3d12x;
|
||||
#[cfg(windows)]
|
||||
pub mod files;
|
||||
pub mod gameinput;
|
||||
pub mod kernel;
|
||||
#[cfg(windows)]
|
||||
pub mod lifecycle;
|
||||
pub mod storage;
|
||||
pub mod xasync;
|
||||
pub mod xgame;
|
||||
pub mod xgameruntime;
|
||||
#[cfg(windows)]
|
||||
pub mod xmem;
|
||||
pub mod xsystem;
|
||||
pub mod xuser;
|
||||
|
||||
use crate::HleModule;
|
||||
|
||||
pub(crate) fn all() -> Vec<HleModule> {
|
||||
vec![kernel::module(), xgameruntime::module()]
|
||||
let mut all = vec![
|
||||
kernel::module(),
|
||||
xgameruntime::module(),
|
||||
gameinput::module(),
|
||||
d3d12x::module(),
|
||||
audio::module(),
|
||||
];
|
||||
#[cfg(windows)]
|
||||
all.push(files::module());
|
||||
#[cfg(windows)]
|
||||
all.push(lifecycle::module());
|
||||
#[cfg(windows)]
|
||||
all.push(xmem::module());
|
||||
all
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
//! Persistent local storage: a host folder of the title's own
|
||||
//! (`runtime::Title::storage`, under the data directory, never the cache)
|
||||
//! with the quota its manifest declares, seen by the title as a drive
|
||||
//! (`files`).
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use super::xasync::{self, AsyncBlock, E_ABORT};
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, S_OK, add_ref, missing, put,
|
||||
put_string,
|
||||
};
|
||||
use crate::runtime;
|
||||
|
||||
pub const PROVIDER: Guid = Guid::new(
|
||||
0xf4fa_f4d4,
|
||||
0x2d04,
|
||||
0x4fce,
|
||||
[0xb3, 0xe0, 0x47, 0x4a, 0x71, 0x3a, 0x3e, 0x84],
|
||||
);
|
||||
pub const IID: Guid = Guid::new(
|
||||
0xd294_11df,
|
||||
0x0794,
|
||||
0x4553,
|
||||
[0x8b, 0x27, 0x95, 0xfc, 0x02, 0xd0, 0xf7, 0x5d],
|
||||
);
|
||||
|
||||
pub static OBJECT: Object = Object::new("persistent local storage", &VTABLE);
|
||||
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT)];
|
||||
|
||||
type This = *const Object;
|
||||
|
||||
/// The path titles get: the root of a virtual drive over the folder. On the
|
||||
/// console storage is a drive of its own, and titles rely on it: Minecraft
|
||||
/// keeps only what precedes the path's last `:\` and mounts that as a
|
||||
/// drive, so a host folder such as `C:\Users\..` would make it write to the
|
||||
/// root of `C:`. None (the path calls fail) before the title is set.
|
||||
fn folder() -> Option<String> {
|
||||
let storage = runtime::title().storage;
|
||||
if storage.as_os_str().is_empty() {
|
||||
return None;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
return super::files::mount(&storage).map(|letter| format!("{letter}:\\"));
|
||||
#[cfg(not(windows))]
|
||||
None
|
||||
}
|
||||
|
||||
extern "system" fn path_size(_: This, out: *mut usize) -> HRESULT {
|
||||
match folder() {
|
||||
Some(path) => put(out, path.len() + 1),
|
||||
None => NOT_SUPPORTED,
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn path(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
|
||||
match folder() {
|
||||
Some(path) => put_string(&path, size, buffer, used),
|
||||
None => NOT_SUPPORTED,
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct SpaceInfo {
|
||||
/// Writable now.
|
||||
pub available_free: u64,
|
||||
/// Left in the quota.
|
||||
pub total_free: u64,
|
||||
pub used: u64,
|
||||
/// The quota.
|
||||
pub total: u64,
|
||||
}
|
||||
|
||||
fn used_bytes(dir: &Path) -> u64 {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return 0;
|
||||
};
|
||||
entries
|
||||
.flatten()
|
||||
.map(|e| match e.metadata() {
|
||||
Ok(m) if m.is_dir() => used_bytes(&e.path()),
|
||||
Ok(m) => m.len(),
|
||||
Err(_) => 0,
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn space() -> SpaceInfo {
|
||||
let title = runtime::title();
|
||||
let used = used_bytes(&title.storage);
|
||||
let free = title.storage_bytes.saturating_sub(used);
|
||||
// shortcut: the host disk's free space is not checked; do so if a title
|
||||
// fills its quota on a nearly full disk.
|
||||
SpaceInfo {
|
||||
available_free: free,
|
||||
total_free: free,
|
||||
used,
|
||||
total: title.storage_bytes,
|
||||
}
|
||||
}
|
||||
|
||||
extern "system" fn space_info(_: This, out: *mut SpaceInfo) -> HRESULT {
|
||||
put(out, space())
|
||||
}
|
||||
|
||||
/// Tells our prompts apart from other calls on the same block.
|
||||
static PROMPT: u8 = 0;
|
||||
|
||||
/// There is nobody to ask: granted when the quota has room, else declined.
|
||||
extern "system" fn prompt_for_space(_: This, bytes: u64, block: *mut AsyncBlock) -> HRESULT {
|
||||
let hr = if bytes <= space().total_free {
|
||||
S_OK
|
||||
} else {
|
||||
E_ABORT
|
||||
};
|
||||
xasync::finished(block, (&raw const PROMPT).cast(), hr)
|
||||
}
|
||||
|
||||
extern "system" fn prompt_result(_: This, block: *mut AsyncBlock) -> HRESULT {
|
||||
let none = std::ptr::null_mut();
|
||||
xasync::XAsyncGetResult(block, (&raw const PROMPT).cast(), 0, none, none.cast())
|
||||
}
|
||||
|
||||
static VTABLE: Methods<8> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
path_size as *const (), // 0x18
|
||||
path as *const (), // 0x20
|
||||
space_info as *const (), // 0x28
|
||||
prompt_for_space as *const (), // 0x30
|
||||
prompt_result as *const (), // 0x38
|
||||
]);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::modules::xgameruntime::method;
|
||||
|
||||
#[test]
|
||||
fn serves_a_drive_over_the_title_folder_and_its_quota() {
|
||||
type Size = extern "system" fn(This, *mut usize) -> HRESULT;
|
||||
type Get = extern "system" fn(This, usize, *mut u8, *mut usize) -> HRESULT;
|
||||
type Space = extern "system" fn(This, *mut SpaceInfo) -> HRESULT;
|
||||
type Prompt = extern "system" fn(This, u64, *mut AsyncBlock) -> HRESULT;
|
||||
type Result = extern "system" fn(This, *mut AsyncBlock) -> HRESULT;
|
||||
let this: This = &OBJECT;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("save.dat"), [0u8; 100]).unwrap();
|
||||
runtime::set_title(runtime::Title {
|
||||
id: 1,
|
||||
storage: dir.path().to_owned(),
|
||||
storage_bytes: 1000,
|
||||
});
|
||||
|
||||
// The path is a drive root, never the host folder.
|
||||
let mut size = 0;
|
||||
assert_eq!(method::<Size>(&OBJECT, 0x18)(this, &mut size), S_OK);
|
||||
assert_eq!(size, 4, "X:\\ and its NUL");
|
||||
let (mut buffer, mut used) = ([0u8; 4], 0);
|
||||
let get = method::<Get>(&OBJECT, 0x20);
|
||||
assert_eq!(get(this, 4, buffer.as_mut_ptr(), &mut used), S_OK);
|
||||
let drive = std::str::from_utf8(&buffer[..3]).unwrap();
|
||||
assert!(drive.ends_with(":\\"), "{drive}");
|
||||
// Title file calls on it reach the folder.
|
||||
let path = format!("{drive}save.dat\0");
|
||||
let mut attributes = [0u8; 36];
|
||||
let get_attributes = super::super::files::GetFileAttributesExW;
|
||||
let wide: Vec<u16> = path.encode_utf16().collect();
|
||||
assert_ne!(
|
||||
get_attributes(wide.as_ptr(), 0, attributes.as_mut_ptr().cast()),
|
||||
0
|
||||
);
|
||||
|
||||
let mut info = SpaceInfo {
|
||||
available_free: 0,
|
||||
total_free: 0,
|
||||
used: 0,
|
||||
total: 0,
|
||||
};
|
||||
assert_eq!(method::<Space>(&OBJECT, 0x28)(this, &mut info), S_OK);
|
||||
assert_eq!((info.used, info.total_free, info.total), (100, 900, 1000));
|
||||
|
||||
let prompt = method::<Prompt>(&OBJECT, 0x30);
|
||||
let result = method::<Result>(&OBJECT, 0x38);
|
||||
for (bytes, expect) in [(900, S_OK), (901, E_ABORT)] {
|
||||
let mut block = AsyncBlock {
|
||||
queue: std::ptr::null(),
|
||||
context: std::ptr::null_mut(),
|
||||
callback: None,
|
||||
internal: [0; 4],
|
||||
};
|
||||
assert_eq!(prompt(this, bytes, &mut block), S_OK);
|
||||
assert_eq!(xasync::XAsyncGetStatus(&mut block, true), expect);
|
||||
assert_eq!(result(this, &mut block), expect, "{bytes} bytes");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,959 @@
|
||||
//! XTaskQueue and XAsync: the runtime's callback queues and async-call
|
||||
//! blocks, served as the task-queue provider's object from `QueryApiImpl`.
|
||||
//!
|
||||
//! As documented for the public API: a queue has a work port and a
|
||||
//! completion port, each dispatched manually (the title calls dispatch),
|
||||
//! on a thread pool, serialised on one thread, or immediately on the
|
||||
//! submitting thread. A null queue handle means the process queue. An
|
||||
//! async block's system area holds its status and result size, so both
|
||||
//! stay readable after our state for the call is gone.
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::ffi::c_void;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard};
|
||||
use std::time::Duration;
|
||||
|
||||
use super::xgameruntime::{Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing};
|
||||
|
||||
/// The task-queue provider; it is also the interface id titles ask for.
|
||||
pub const PROVIDER: Guid = Guid {
|
||||
data1: 0x073b_7dcb,
|
||||
data2: 0x1fcf,
|
||||
data3: 0x4030,
|
||||
data4: [0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28],
|
||||
};
|
||||
|
||||
pub const E_PENDING: HRESULT = 0x8000_000A_u32 as i32;
|
||||
pub const E_ABORT: HRESULT = 0x8000_4004_u32 as i32;
|
||||
pub const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32;
|
||||
pub const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32;
|
||||
pub const E_NOT_SUFFICIENT_BUFFER: HRESULT = 0x8007_007A_u32 as i32;
|
||||
pub const E_ILLEGAL_METHOD_CALL: HRESULT = 0x8000_000E_u32 as i32;
|
||||
|
||||
const WORK: u32 = 0;
|
||||
const COMPLETION: u32 = 1;
|
||||
const INFINITE: u32 = u32::MAX;
|
||||
|
||||
type Callback = extern "system" fn(*mut c_void, bool);
|
||||
type MonitorCallback = extern "system" fn(*mut c_void, *const Queue, u32);
|
||||
type TerminatedCallback = extern "system" fn(*mut c_void);
|
||||
type CompletionRoutine = extern "system" fn(*mut AsyncBlock);
|
||||
type Provider = extern "system" fn(u32, *const ProviderData) -> HRESULT;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
Manual,
|
||||
ThreadPool,
|
||||
Serialized,
|
||||
Immediate,
|
||||
}
|
||||
|
||||
impl Mode {
|
||||
fn from_raw(mode: u32) -> Option<Mode> {
|
||||
[
|
||||
Mode::Manual,
|
||||
Mode::ThreadPool,
|
||||
Mode::Serialized,
|
||||
Mode::Immediate,
|
||||
]
|
||||
.get(mode as usize)
|
||||
.copied()
|
||||
}
|
||||
}
|
||||
|
||||
/// A title callback and its context (addresses, so tasks can cross threads).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Task {
|
||||
context: usize,
|
||||
callback: usize,
|
||||
}
|
||||
|
||||
impl Task {
|
||||
fn new(context: *mut c_void, callback: Callback) -> Task {
|
||||
Task {
|
||||
context: context as usize,
|
||||
callback: callback as usize,
|
||||
}
|
||||
}
|
||||
|
||||
fn run(self, canceled: bool) {
|
||||
// SAFETY: built from a `Callback` in `new`.
|
||||
let callback: Callback = unsafe { std::mem::transmute(self.callback) };
|
||||
callback(self.context as *mut c_void, canceled);
|
||||
}
|
||||
}
|
||||
|
||||
struct Port {
|
||||
mode: Mode,
|
||||
tasks: Mutex<VecDeque<Task>>,
|
||||
ready: Condvar,
|
||||
}
|
||||
|
||||
impl Port {
|
||||
fn new(mode: Mode) -> Arc<Port> {
|
||||
let port = Arc::new(Port {
|
||||
mode,
|
||||
tasks: Mutex::default(),
|
||||
ready: Condvar::new(),
|
||||
});
|
||||
if mode == Mode::Serialized {
|
||||
// shortcut: the worker lives as long as the process, even after
|
||||
// the queue closes; join it on close if titles churn queues.
|
||||
let worker = port.clone();
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
if let Some(task) = worker.take(INFINITE) {
|
||||
task.run(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
port
|
||||
}
|
||||
|
||||
fn submit(&self, task: Task) {
|
||||
match self.mode {
|
||||
Mode::Immediate => task.run(false),
|
||||
// shortcut: a thread per callback, not a pool; fine at startup
|
||||
// rates, pool them if a title submits thousands per frame.
|
||||
Mode::ThreadPool => drop(std::thread::spawn(move || task.run(false))),
|
||||
Mode::Manual | Mode::Serialized => {
|
||||
lock(&self.tasks).push_back(task);
|
||||
self.ready.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The next queued task, waiting up to `timeout_ms`.
|
||||
fn take(&self, timeout_ms: u32) -> Option<Task> {
|
||||
let tasks = lock(&self.tasks);
|
||||
let mut tasks = if timeout_ms == INFINITE {
|
||||
self.ready
|
||||
.wait_while(tasks, |t| t.is_empty())
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
} else {
|
||||
let timeout = Duration::from_millis(timeout_ms.into());
|
||||
self.ready
|
||||
.wait_timeout_while(tasks, timeout, |t| t.is_empty())
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.0
|
||||
};
|
||||
tasks.pop_front()
|
||||
}
|
||||
}
|
||||
|
||||
/// A queue handle is `Arc::into_raw` of this; duplicating and closing a
|
||||
/// handle add and drop a reference.
|
||||
pub struct Queue {
|
||||
ports: [Arc<Port>; 2],
|
||||
monitors: Mutex<Vec<(u64, usize, usize)>>,
|
||||
terminated: AtomicBool,
|
||||
}
|
||||
|
||||
impl Queue {
|
||||
fn new(ports: [Arc<Port>; 2]) -> Arc<Queue> {
|
||||
Arc::new(Queue {
|
||||
ports,
|
||||
monitors: Mutex::default(),
|
||||
terminated: AtomicBool::new(false),
|
||||
})
|
||||
}
|
||||
|
||||
fn submit(self: &Arc<Self>, port: u32, delay_ms: u32, task: Task) -> HRESULT {
|
||||
if port > COMPLETION {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if self.terminated.load(Ordering::Acquire) {
|
||||
return E_ABORT;
|
||||
}
|
||||
if delay_ms == 0 {
|
||||
self.deliver(port, task);
|
||||
} else {
|
||||
let queue = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(delay_ms.into()));
|
||||
queue.deliver(port, task);
|
||||
});
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
fn deliver(self: &Arc<Self>, port: u32, task: Task) {
|
||||
self.ports[port as usize].submit(task);
|
||||
// Copied out: a monitor may unregister itself.
|
||||
let monitors = lock(&self.monitors).clone();
|
||||
for (_, context, callback) in monitors {
|
||||
// SAFETY: stored from a `MonitorCallback` in `register_monitor`.
|
||||
let callback: MonitorCallback = unsafe { std::mem::transmute(callback) };
|
||||
callback(context as *mut c_void, Arc::as_ptr(self), port);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// The process queue: `None` until first used (then a thread-pool queue),
|
||||
/// `Some(None)` once the title clears it.
|
||||
static PROCESS_QUEUE: Mutex<Option<Option<Arc<Queue>>>> = Mutex::new(None);
|
||||
|
||||
fn process_queue() -> Option<Arc<Queue>> {
|
||||
lock(&PROCESS_QUEUE)
|
||||
.get_or_insert_with(|| {
|
||||
Some(Queue::new([
|
||||
Port::new(Mode::ThreadPool),
|
||||
Port::new(Mode::ThreadPool),
|
||||
]))
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// A new reference to the queue behind `handle` (null: the process queue).
|
||||
fn queue(handle: *const Queue) -> Option<Arc<Queue>> {
|
||||
if handle.is_null() {
|
||||
return process_queue();
|
||||
}
|
||||
// SAFETY: a handle we returned, which the title has not closed.
|
||||
unsafe {
|
||||
Arc::increment_strong_count(handle);
|
||||
Some(Arc::from_raw(handle))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn XTaskQueueCreate(work: u32, completion: u32, out: *mut *const Queue) -> HRESULT {
|
||||
let (Some(work), Some(completion)) = (Mode::from_raw(work), Mode::from_raw(completion)) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let queue = Queue::new([Port::new(work), Port::new(completion)]);
|
||||
// SAFETY: checked non-null; the title passes room for a handle.
|
||||
unsafe { out.write(Arc::into_raw(queue)) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// A port handle points at the port, which its queue keeps alive.
|
||||
pub fn XTaskQueueGetPort(handle: *const Queue, port: u32, out: *mut *const c_void) -> HRESULT {
|
||||
let Some(queue) = queue(handle) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if port > COMPLETION || out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(Arc::as_ptr(&queue.ports[port as usize]).cast()) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub fn XTaskQueueCreateComposite(
|
||||
work: *const c_void,
|
||||
completion: *const c_void,
|
||||
out: *mut *const Queue,
|
||||
) -> HRESULT {
|
||||
if work.is_null() || completion.is_null() || out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let port = |p: *const c_void| {
|
||||
// SAFETY: a port handle from `XTaskQueueGetPort`, whose queue is open.
|
||||
unsafe {
|
||||
Arc::increment_strong_count(p.cast::<Port>());
|
||||
Arc::from_raw(p.cast::<Port>())
|
||||
}
|
||||
};
|
||||
let queue = Queue::new([port(work), port(completion)]);
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(Arc::into_raw(queue)) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub fn XTaskQueueDuplicateHandle(handle: *const Queue, out: *mut *const Queue) -> HRESULT {
|
||||
match queue(handle) {
|
||||
Some(queue) if !out.is_null() => {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(Arc::into_raw(queue)) };
|
||||
S_OK
|
||||
}
|
||||
_ => E_INVALIDARG,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn XTaskQueueCloseHandle(handle: *const Queue) {
|
||||
if !handle.is_null() {
|
||||
// SAFETY: a handle we returned; this drops its reference.
|
||||
unsafe { Arc::decrement_strong_count(handle) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one queued callback of a manual port; false if none came in time.
|
||||
pub fn XTaskQueueDispatch(handle: *const Queue, port: u32, timeout_ms: u32) -> bool {
|
||||
let Some(queue) = queue(handle) else {
|
||||
return false;
|
||||
};
|
||||
let Some(port) = queue.ports.get(port as usize) else {
|
||||
return false;
|
||||
};
|
||||
if port.mode != Mode::Manual {
|
||||
return false;
|
||||
}
|
||||
match port.take(timeout_ms) {
|
||||
Some(task) => {
|
||||
task.run(false);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn XTaskQueueSubmitDelayedCallback(
|
||||
handle: *const Queue,
|
||||
port: u32,
|
||||
delay_ms: u32,
|
||||
context: *mut c_void,
|
||||
callback: Option<Callback>,
|
||||
) -> HRESULT {
|
||||
match (queue(handle), callback) {
|
||||
(Some(queue), Some(callback)) => queue.submit(port, delay_ms, Task::new(context, callback)),
|
||||
_ => E_INVALIDARG,
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancels what is still queued (callbacks see `canceled`), refuses new
|
||||
/// work, then calls `callback`.
|
||||
pub fn XTaskQueueTerminate(
|
||||
handle: *const Queue,
|
||||
_wait: bool,
|
||||
context: *mut c_void,
|
||||
callback: Option<TerminatedCallback>,
|
||||
) -> HRESULT {
|
||||
let Some(queue) = queue(handle) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
queue.terminated.store(true, Ordering::Release);
|
||||
for port in &queue.ports {
|
||||
let pending: Vec<Task> = lock(&port.tasks).drain(..).collect();
|
||||
for task in pending {
|
||||
task.run(true);
|
||||
}
|
||||
}
|
||||
if let Some(callback) = callback {
|
||||
callback(context);
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
pub fn XTaskQueueRegisterMonitor(
|
||||
handle: *const Queue,
|
||||
context: *mut c_void,
|
||||
callback: Option<MonitorCallback>,
|
||||
token: *mut u64,
|
||||
) -> HRESULT {
|
||||
let (Some(queue), Some(callback)) = (queue(handle), callback) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if token.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let id = NEXT_TOKEN.fetch_add(1, Ordering::Relaxed);
|
||||
lock(&queue.monitors).push((id, context as usize, callback as usize));
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { token.write(id) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub fn XTaskQueueUnregisterMonitor(handle: *const Queue, token: u64) {
|
||||
if let Some(queue) = queue(handle) {
|
||||
lock(&queue.monitors).retain(|m| m.0 != token);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new handle to the process queue, if there is one.
|
||||
pub fn XTaskQueueGetCurrentProcessTaskQueue(out: *mut *const Queue) -> bool {
|
||||
let found = process_queue();
|
||||
if !out.is_null() {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(found.clone().map_or(std::ptr::null(), Arc::into_raw)) };
|
||||
}
|
||||
found.is_some()
|
||||
}
|
||||
|
||||
pub fn XTaskQueueSetCurrentProcessTaskQueue(handle: *const Queue) {
|
||||
let new = if handle.is_null() {
|
||||
None
|
||||
} else {
|
||||
queue(handle)
|
||||
};
|
||||
*lock(&PROCESS_QUEUE) = Some(new);
|
||||
}
|
||||
|
||||
/// An async block: what the title fills in, then the system area.
|
||||
#[repr(C)]
|
||||
pub struct AsyncBlock {
|
||||
pub queue: *const Queue,
|
||||
pub context: *mut c_void,
|
||||
pub callback: Option<CompletionRoutine>,
|
||||
/// Ours: [unused, status, result size, unused].
|
||||
pub internal: [usize; 4],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct ProviderData {
|
||||
pub block: *mut AsyncBlock,
|
||||
pub buffer_size: usize,
|
||||
pub buffer: *mut c_void,
|
||||
pub context: *mut c_void,
|
||||
}
|
||||
|
||||
const OP_BEGIN: u32 = 0;
|
||||
const OP_DO_WORK: u32 = 1;
|
||||
const OP_GET_RESULT: u32 = 2;
|
||||
const OP_CANCEL: u32 = 3;
|
||||
const OP_CLEANUP: u32 = 4;
|
||||
|
||||
/// One call in flight, until its result is taken or it fails.
|
||||
struct Call {
|
||||
provider: Provider,
|
||||
context: usize,
|
||||
identity: usize,
|
||||
done: Mutex<bool>,
|
||||
finished: Condvar,
|
||||
}
|
||||
|
||||
impl Call {
|
||||
fn provider(
|
||||
&self,
|
||||
op: u32,
|
||||
block: *mut AsyncBlock,
|
||||
size: usize,
|
||||
buffer: *mut c_void,
|
||||
) -> HRESULT {
|
||||
let data = ProviderData {
|
||||
block,
|
||||
buffer_size: size,
|
||||
buffer,
|
||||
context: self.context as *mut c_void,
|
||||
};
|
||||
(self.provider)(op, &data)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls by block address.
|
||||
static CALLS: LazyLock<Mutex<HashMap<usize, Arc<Call>>>> = LazyLock::new(Default::default);
|
||||
|
||||
fn call(block: *mut AsyncBlock) -> Option<Arc<Call>> {
|
||||
lock(&CALLS).get(&(block as usize)).cloned()
|
||||
}
|
||||
|
||||
/// The block's status and result-size words.
|
||||
fn words(block: *mut AsyncBlock) -> (&'static AtomicUsize, &'static AtomicUsize) {
|
||||
// SAFETY: the title's block outlives the call; its system area is ours.
|
||||
unsafe {
|
||||
let internal = std::ptr::addr_of_mut!((*block).internal).cast::<AtomicUsize>();
|
||||
(&*internal.add(1), &*internal.add(2))
|
||||
}
|
||||
}
|
||||
|
||||
fn status(block: *mut AsyncBlock) -> HRESULT {
|
||||
words(block).0.load(Ordering::Acquire) as u32 as i32
|
||||
}
|
||||
|
||||
fn release(block: *mut AsyncBlock) {
|
||||
// Unlocked before the provider runs: it may call back into us.
|
||||
let removed = lock(&CALLS).remove(&(block as usize));
|
||||
if let Some(call) = removed {
|
||||
call.provider(OP_CLEANUP, block, 0, std::ptr::null_mut());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn XAsyncBegin(
|
||||
block: *mut AsyncBlock,
|
||||
context: *mut c_void,
|
||||
identity: *const c_void,
|
||||
_identity_name: *const u8,
|
||||
provider: Option<Provider>,
|
||||
) -> HRESULT {
|
||||
let Some(provider) = provider else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if block.is_null() || call(block).is_some() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let (status, size) = words(block);
|
||||
status.store(E_PENDING as u32 as usize, Ordering::Release);
|
||||
size.store(0, Ordering::Release);
|
||||
let call = Arc::new(Call {
|
||||
provider,
|
||||
context: context as usize,
|
||||
identity: identity as usize,
|
||||
done: Mutex::new(false),
|
||||
finished: Condvar::new(),
|
||||
});
|
||||
lock(&CALLS).insert(block as usize, call.clone());
|
||||
// A failed begin fails the call, so the completion routine still runs.
|
||||
let hr = call.provider(OP_BEGIN, block, 0, std::ptr::null_mut());
|
||||
if hr < 0 {
|
||||
XAsyncComplete(block, hr, 0);
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Queues the provider's `DoWork` on the block's work port.
|
||||
pub fn XAsyncSchedule(block: *mut AsyncBlock, delay_ms: u32) -> HRESULT {
|
||||
extern "system" fn work(block: *mut c_void, canceled: bool) {
|
||||
let block = block.cast::<AsyncBlock>();
|
||||
let Some(call) = call(block) else { return };
|
||||
let hr = if canceled {
|
||||
E_ABORT
|
||||
} else {
|
||||
call.provider(OP_DO_WORK, block, 0, std::ptr::null_mut())
|
||||
};
|
||||
if hr != E_PENDING {
|
||||
XAsyncComplete(block, hr, 0);
|
||||
}
|
||||
}
|
||||
if block.is_null() || call(block).is_none() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: a block in flight is valid.
|
||||
let handle = unsafe { (*block).queue };
|
||||
match queue(handle) {
|
||||
Some(queue) => queue.submit(WORK, delay_ms, Task::new(block.cast(), work)),
|
||||
None => E_INVALIDARG,
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the result (the first one wins), wakes waiters and queues the
|
||||
/// completion routine on the block's completion port.
|
||||
pub fn XAsyncComplete(block: *mut AsyncBlock, result: HRESULT, required_size: usize) {
|
||||
extern "system" fn complete(block: *mut c_void, _canceled: bool) {
|
||||
let block = block.cast::<AsyncBlock>();
|
||||
// SAFETY: read before the status was published; see below.
|
||||
if let Some(routine) = unsafe { (*block).callback } {
|
||||
routine(block);
|
||||
}
|
||||
}
|
||||
let Some(call) = call(block) else { return };
|
||||
if result == E_PENDING {
|
||||
return;
|
||||
}
|
||||
let mut done = lock(&call.done);
|
||||
if *done {
|
||||
return;
|
||||
}
|
||||
// Read before publishing: once the status is set, the title may free
|
||||
// the block.
|
||||
// SAFETY: a block in flight is valid.
|
||||
let (handle, routine) = unsafe { ((*block).queue, (*block).callback) };
|
||||
let (status, size) = words(block);
|
||||
if result < 0 || required_size == 0 {
|
||||
release(block);
|
||||
}
|
||||
size.store(required_size, Ordering::Release);
|
||||
status.store(result as u32 as usize, Ordering::Release);
|
||||
*done = true;
|
||||
call.finished.notify_all();
|
||||
drop(done);
|
||||
if routine.is_some() {
|
||||
let task = Task::new(block.cast(), complete);
|
||||
match queue(handle) {
|
||||
Some(queue) if queue.submit(COMPLETION, 0, task) == S_OK => {}
|
||||
_ => task.run(true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn XAsyncGetStatus(block: *mut AsyncBlock, wait: bool) -> HRESULT {
|
||||
if block.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if wait && let Some(call) = call(block) {
|
||||
let done = lock(&call.done);
|
||||
drop(call.finished.wait_while(done, |d| !*d));
|
||||
}
|
||||
status(block)
|
||||
}
|
||||
|
||||
pub fn XAsyncGetResultSize(block: *mut AsyncBlock, out: *mut usize) -> HRESULT {
|
||||
if block.is_null() || out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let hr = status(block);
|
||||
if hr == S_OK {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(words(block).1.load(Ordering::Acquire)) };
|
||||
}
|
||||
hr
|
||||
}
|
||||
|
||||
/// Asks the provider to cancel; the call fails with `E_ABORT` unless the
|
||||
/// provider completed it first.
|
||||
pub fn XAsyncCancel(block: *mut AsyncBlock) {
|
||||
if let Some(call) = call(block) {
|
||||
call.provider(OP_CANCEL, block, 0, std::ptr::null_mut());
|
||||
XAsyncComplete(block, E_ABORT, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Has the provider write the result into `buffer`, then ends the call.
|
||||
pub fn XAsyncGetResult(
|
||||
block: *mut AsyncBlock,
|
||||
identity: *const c_void,
|
||||
buffer_size: usize,
|
||||
buffer: *mut c_void,
|
||||
used: *mut usize,
|
||||
) -> HRESULT {
|
||||
if block.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let hr = status(block);
|
||||
let size = words(block).1.load(Ordering::Acquire);
|
||||
if hr != S_OK || size == 0 {
|
||||
if hr == S_OK && !used.is_null() {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { used.write(0) };
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
let Some(call) = call(block) else {
|
||||
return E_ILLEGAL_METHOD_CALL;
|
||||
};
|
||||
if call.identity != identity as usize {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if buffer_size < size || buffer.is_null() {
|
||||
return E_NOT_SUFFICIENT_BUFFER;
|
||||
}
|
||||
let hr = call.provider(OP_GET_RESULT, block, buffer_size, buffer);
|
||||
if !used.is_null() {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { used.write(size) };
|
||||
}
|
||||
release(block);
|
||||
hr
|
||||
}
|
||||
|
||||
/// Starts a call on `block` that is already over: it completes with `hr`
|
||||
/// and no result data, through the block's completion port as usual.
|
||||
pub fn finished(block: *mut AsyncBlock, identity: *const c_void, hr: HRESULT) -> HRESULT {
|
||||
extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT {
|
||||
// SAFETY: the runtime passes valid provider data.
|
||||
let data = unsafe { &*data };
|
||||
if op == OP_BEGIN {
|
||||
XAsyncComplete(data.block, data.context as usize as u32 as i32, 0);
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
let context = hr as u32 as usize as *mut c_void;
|
||||
XAsyncBegin(block, context, identity, std::ptr::null(), Some(provider))
|
||||
}
|
||||
|
||||
// The object `QueryApiImpl` returns. Each method takes the object first,
|
||||
// then the API's arguments; slot offsets as titles call them.
|
||||
|
||||
pub static OBJECT: Object = Object::new("task queue", &VTABLE);
|
||||
|
||||
/// Its interface id is the provider's.
|
||||
pub const INTERFACES: &[Interface] = &[(PROVIDER, PROVIDER, &OBJECT)];
|
||||
|
||||
type This = *const Object;
|
||||
extern "system" fn m_get_status(_: This, b: *mut AsyncBlock, wait: u8) -> HRESULT {
|
||||
XAsyncGetStatus(b, wait != 0)
|
||||
}
|
||||
extern "system" fn m_get_result_size(_: This, b: *mut AsyncBlock, out: *mut usize) -> HRESULT {
|
||||
XAsyncGetResultSize(b, out)
|
||||
}
|
||||
extern "system" fn m_cancel(_: This, b: *mut AsyncBlock) {
|
||||
XAsyncCancel(b)
|
||||
}
|
||||
extern "system" fn m_begin(
|
||||
_: This,
|
||||
b: *mut AsyncBlock,
|
||||
context: *mut c_void,
|
||||
identity: *const c_void,
|
||||
name: *const u8,
|
||||
provider: Option<Provider>,
|
||||
) -> HRESULT {
|
||||
XAsyncBegin(b, context, identity, name, provider)
|
||||
}
|
||||
extern "system" fn m_schedule(_: This, b: *mut AsyncBlock, delay: u32) -> HRESULT {
|
||||
XAsyncSchedule(b, delay)
|
||||
}
|
||||
extern "system" fn m_complete(_: This, b: *mut AsyncBlock, hr: HRESULT, size: usize) {
|
||||
XAsyncComplete(b, hr, size)
|
||||
}
|
||||
extern "system" fn m_get_result(
|
||||
_: This,
|
||||
b: *mut AsyncBlock,
|
||||
identity: *const c_void,
|
||||
size: usize,
|
||||
buffer: *mut c_void,
|
||||
used: *mut usize,
|
||||
) -> HRESULT {
|
||||
XAsyncGetResult(b, identity, size, buffer, used)
|
||||
}
|
||||
extern "system" fn m_create(
|
||||
_: This,
|
||||
work: u32,
|
||||
completion: u32,
|
||||
out: *mut *const Queue,
|
||||
) -> HRESULT {
|
||||
XTaskQueueCreate(work, completion, out)
|
||||
}
|
||||
extern "system" fn m_create_composite(
|
||||
_: This,
|
||||
work: *const c_void,
|
||||
completion: *const c_void,
|
||||
out: *mut *const Queue,
|
||||
) -> HRESULT {
|
||||
XTaskQueueCreateComposite(work, completion, out)
|
||||
}
|
||||
extern "system" fn m_get_port(
|
||||
_: This,
|
||||
q: *const Queue,
|
||||
port: u32,
|
||||
out: *mut *const c_void,
|
||||
) -> HRESULT {
|
||||
XTaskQueueGetPort(q, port, out)
|
||||
}
|
||||
extern "system" fn m_duplicate(_: This, q: *const Queue, out: *mut *const Queue) -> HRESULT {
|
||||
XTaskQueueDuplicateHandle(q, out)
|
||||
}
|
||||
extern "system" fn m_dispatch(_: This, q: *const Queue, port: u32, timeout: u32) -> bool {
|
||||
XTaskQueueDispatch(q, port, timeout)
|
||||
}
|
||||
extern "system" fn m_close(_: This, q: *const Queue) {
|
||||
XTaskQueueCloseHandle(q)
|
||||
}
|
||||
extern "system" fn m_submit(
|
||||
_: This,
|
||||
q: *const Queue,
|
||||
port: u32,
|
||||
context: *mut c_void,
|
||||
callback: Option<Callback>,
|
||||
) -> HRESULT {
|
||||
XTaskQueueSubmitDelayedCallback(q, port, 0, context, callback)
|
||||
}
|
||||
extern "system" fn m_submit_delayed(
|
||||
_: This,
|
||||
q: *const Queue,
|
||||
port: u32,
|
||||
delay: u32,
|
||||
context: *mut c_void,
|
||||
callback: Option<Callback>,
|
||||
) -> HRESULT {
|
||||
XTaskQueueSubmitDelayedCallback(q, port, delay, context, callback)
|
||||
}
|
||||
extern "system" fn m_terminate(
|
||||
_: This,
|
||||
q: *const Queue,
|
||||
wait: u8,
|
||||
context: *mut c_void,
|
||||
callback: Option<TerminatedCallback>,
|
||||
) -> HRESULT {
|
||||
XTaskQueueTerminate(q, wait != 0, context, callback)
|
||||
}
|
||||
extern "system" fn m_register_monitor(
|
||||
_: This,
|
||||
q: *const Queue,
|
||||
context: *mut c_void,
|
||||
callback: Option<MonitorCallback>,
|
||||
token: *mut u64,
|
||||
) -> HRESULT {
|
||||
XTaskQueueRegisterMonitor(q, context, callback, token)
|
||||
}
|
||||
extern "system" fn m_unregister_monitor(_: This, q: *const Queue, token: u64) {
|
||||
XTaskQueueUnregisterMonitor(q, token)
|
||||
}
|
||||
extern "system" fn m_get_process_queue(_: This, out: *mut *const Queue) -> bool {
|
||||
XTaskQueueGetCurrentProcessTaskQueue(out)
|
||||
}
|
||||
extern "system" fn m_set_process_queue(_: This, q: *const Queue) {
|
||||
XTaskQueueSetCurrentProcessTaskQueue(q)
|
||||
}
|
||||
/// The runtime's debug check that the caller is not a time-critical thread,
|
||||
/// which every runtime call in a title makes first.
|
||||
extern "system" fn m_check_thread(_: This) {}
|
||||
|
||||
static VTABLE: Methods<31> = Methods([
|
||||
missing::<0> as *const (), // 0x00 QueryInterface
|
||||
add_ref as *const (), // 0x08 AddRef
|
||||
add_ref as *const (), // 0x10 Release: the object is static
|
||||
m_get_status as *const (), // 0x18
|
||||
m_get_result_size as *const (), // 0x20
|
||||
m_cancel as *const (), // 0x28
|
||||
missing::<6> as *const (), // 0x30 run a work callback as a call
|
||||
m_begin as *const (), // 0x38
|
||||
missing::<8> as *const (), // 0x40
|
||||
m_schedule as *const (), // 0x48
|
||||
m_complete as *const (), // 0x50
|
||||
m_get_result as *const (), // 0x58
|
||||
m_create as *const (), // 0x60
|
||||
m_create_composite as *const (), // 0x68
|
||||
m_get_port as *const (), // 0x70
|
||||
m_duplicate as *const (), // 0x78
|
||||
m_dispatch as *const (), // 0x80
|
||||
m_close as *const (), // 0x88
|
||||
m_submit as *const (), // 0x90
|
||||
m_submit_delayed as *const (), // 0x98
|
||||
missing::<20> as *const (), // 0xa0 register a wait handle
|
||||
missing::<21> as *const (), // 0xa8 unregister it
|
||||
m_terminate as *const (), // 0xb0
|
||||
m_register_monitor as *const (), // 0xb8
|
||||
m_unregister_monitor as *const (), // 0xc0
|
||||
m_get_process_queue as *const (), // 0xc8
|
||||
m_set_process_queue as *const (), // 0xd0
|
||||
missing::<27> as *const (), // 0xd8 thread time-sensitivity
|
||||
missing::<28> as *const (), // 0xe0
|
||||
m_check_thread as *const (), // 0xe8
|
||||
missing::<30> as *const (), // 0xf0
|
||||
]);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::AtomicU32;
|
||||
|
||||
fn slot<F: Copy>(offset: usize) -> F {
|
||||
crate::modules::xgameruntime::method(&OBJECT, offset)
|
||||
}
|
||||
|
||||
static RAN: AtomicU32 = AtomicU32::new(0);
|
||||
extern "system" fn count(context: *mut c_void, canceled: bool) {
|
||||
RAN.fetch_add(
|
||||
if canceled { 100 } else { context as u32 },
|
||||
Ordering::SeqCst,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_ports_run_callbacks_when_dispatched() {
|
||||
type Create = extern "system" fn(This, u32, u32, *mut *const Queue) -> HRESULT;
|
||||
type Submit = extern "system" fn(This, *const Queue, u32, *mut c_void, Callback) -> HRESULT;
|
||||
type Dispatch = extern "system" fn(This, *const Queue, u32, u32) -> bool;
|
||||
type Close = extern "system" fn(This, *const Queue);
|
||||
let this: This = &OBJECT;
|
||||
let mut q = std::ptr::null();
|
||||
assert_eq!(slot::<Create>(0x60)(this, 0, 0, &mut q), S_OK);
|
||||
assert_eq!(
|
||||
slot::<Submit>(0x90)(this, q, COMPLETION, 5 as *mut c_void, count),
|
||||
S_OK
|
||||
);
|
||||
assert_eq!(RAN.load(Ordering::SeqCst), 0, "manual: nothing runs yet");
|
||||
assert!(
|
||||
!slot::<Dispatch>(0x80)(this, q, WORK, 0),
|
||||
"work port is empty"
|
||||
);
|
||||
assert!(slot::<Dispatch>(0x80)(this, q, COMPLETION, 0));
|
||||
assert_eq!(RAN.load(Ordering::SeqCst), 5);
|
||||
assert!(!slot::<Dispatch>(0x80)(this, q, COMPLETION, 0));
|
||||
slot::<Close>(0x88)(this, q);
|
||||
}
|
||||
|
||||
/// A provider that schedules its work and returns a u64 result.
|
||||
extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT {
|
||||
// SAFETY: the runtime passes valid provider data.
|
||||
let data = unsafe { &*data };
|
||||
match op {
|
||||
OP_BEGIN => XAsyncSchedule(data.block, 0),
|
||||
OP_DO_WORK => {
|
||||
XAsyncComplete(data.block, S_OK, 8);
|
||||
S_OK
|
||||
}
|
||||
OP_GET_RESULT => {
|
||||
// SAFETY: at least 8 bytes, checked by the runtime.
|
||||
unsafe { data.buffer.cast::<u64>().write(data.context as u64) };
|
||||
S_OK
|
||||
}
|
||||
_ => S_OK,
|
||||
}
|
||||
}
|
||||
|
||||
static COMPLETED: AtomicU32 = AtomicU32::new(0);
|
||||
extern "system" fn completed(_: *mut AsyncBlock) {
|
||||
COMPLETED.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_calls_complete_and_return_results() {
|
||||
let mut q = std::ptr::null();
|
||||
// Work on a thread pool, completion dispatched by hand.
|
||||
assert_eq!(XTaskQueueCreate(1, 0, &mut q), S_OK);
|
||||
let mut block = AsyncBlock {
|
||||
queue: q,
|
||||
context: std::ptr::null_mut(),
|
||||
callback: Some(completed),
|
||||
internal: [0; 4],
|
||||
};
|
||||
let identity = 0x1d as *const c_void;
|
||||
assert_eq!(
|
||||
XAsyncBegin(
|
||||
&mut block,
|
||||
42 as *mut c_void,
|
||||
identity,
|
||||
std::ptr::null(),
|
||||
Some(provider)
|
||||
),
|
||||
S_OK
|
||||
);
|
||||
assert_eq!(XAsyncGetStatus(&mut block, true), S_OK);
|
||||
let mut size = 0;
|
||||
assert_eq!(XAsyncGetResultSize(&mut block, &mut size), S_OK);
|
||||
assert_eq!(size, 8);
|
||||
assert_eq!(COMPLETED.load(Ordering::SeqCst), 0, "completion is manual");
|
||||
assert!(XTaskQueueDispatch(q, COMPLETION, INFINITE));
|
||||
assert_eq!(COMPLETED.load(Ordering::SeqCst), 1);
|
||||
|
||||
let mut value = 0u64;
|
||||
let mut small = 0u32;
|
||||
let out = (&mut small as *mut u32).cast();
|
||||
assert_eq!(
|
||||
XAsyncGetResult(&mut block, identity, 4, out, std::ptr::null_mut()),
|
||||
E_NOT_SUFFICIENT_BUFFER
|
||||
);
|
||||
let out = (&mut value as *mut u64).cast();
|
||||
let mut used = 0;
|
||||
assert_eq!(
|
||||
XAsyncGetResult(&mut block, identity, 8, out, &mut used),
|
||||
S_OK
|
||||
);
|
||||
assert_eq!((value, used), (42, 8));
|
||||
assert!(call(&mut block).is_none(), "the call ends with its result");
|
||||
XTaskQueueCloseHandle(q);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminate_cancels_what_is_queued() {
|
||||
static TERMINATED: AtomicBool = AtomicBool::new(false);
|
||||
extern "system" fn terminated(_: *mut c_void) {
|
||||
TERMINATED.store(true, Ordering::SeqCst);
|
||||
}
|
||||
extern "system" fn note(context: *mut c_void, canceled: bool) {
|
||||
// SAFETY: the test passes a pointer to its flag.
|
||||
unsafe { *context.cast::<bool>() = canceled };
|
||||
}
|
||||
let mut q = std::ptr::null();
|
||||
assert_eq!(XTaskQueueCreate(0, 0, &mut q), S_OK);
|
||||
let mut canceled = false;
|
||||
let flag = (&mut canceled as *mut bool).cast();
|
||||
assert_eq!(
|
||||
XTaskQueueSubmitDelayedCallback(q, WORK, 0, flag, Some(note)),
|
||||
S_OK
|
||||
);
|
||||
assert_eq!(
|
||||
XTaskQueueTerminate(q, true, std::ptr::null_mut(), Some(terminated)),
|
||||
S_OK
|
||||
);
|
||||
assert!(canceled && TERMINATED.load(Ordering::SeqCst));
|
||||
assert_eq!(
|
||||
XTaskQueueSubmitDelayedCallback(q, WORK, 0, flag, Some(note)),
|
||||
E_ABORT
|
||||
);
|
||||
XTaskQueueCloseHandle(q);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
//! The title's own id (from its manifest), which runtime areas exist, and
|
||||
//! game invites and events. Offline no invite arrives and events go
|
||||
//! nowhere.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::{CStr, c_char, c_void};
|
||||
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, token,
|
||||
};
|
||||
use crate::runtime;
|
||||
|
||||
/// Title id and launching another title.
|
||||
pub const TITLE_PROVIDER: Guid = Guid::new(
|
||||
0x973a_344e,
|
||||
0x24bf,
|
||||
0x4d0f,
|
||||
[0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29],
|
||||
);
|
||||
/// As Minecraft (2022) asks for it.
|
||||
pub const TITLE_IID: Guid = Guid::new(
|
||||
0x2549_f142,
|
||||
0x6419,
|
||||
0x4a06,
|
||||
[0x97, 0xb5, 0x93, 0x1a, 0xab, 0x7c, 0x2f, 0x34],
|
||||
);
|
||||
/// Feature checks; the interface id is the provider's, as for the next two.
|
||||
pub const FEATURES: Guid = Guid::new(
|
||||
0x8836_fe87,
|
||||
0xedb9,
|
||||
0x4fe3,
|
||||
[0x8d, 0xad, 0x05, 0xf0, 0xd2, 0xcd, 0x5b, 0x40],
|
||||
);
|
||||
pub const INVITES: Guid = Guid::new(
|
||||
0x0651_aae2,
|
||||
0x4012,
|
||||
0x4077,
|
||||
[0xbf, 0x84, 0x8b, 0x90, 0x97, 0x09, 0x0e, 0x2c],
|
||||
);
|
||||
pub const EVENTS: Guid = Guid::new(
|
||||
0xbbfb_dcc7,
|
||||
0xbfe7,
|
||||
0x409b,
|
||||
[0xa5, 0xca, 0xed, 0xf0, 0x54, 0x96, 0x0b, 0x4d],
|
||||
);
|
||||
|
||||
pub static TITLE_OBJECT: Object = Object::new("title", &TITLE_VTABLE);
|
||||
pub static FEATURES_OBJECT: Object = Object::new("features", &FEATURES_VTABLE);
|
||||
pub static INVITES_OBJECT: Object = Object::new("invites", &INVITES_VTABLE);
|
||||
pub static EVENTS_OBJECT: Object = Object::new("events", &EVENTS_VTABLE);
|
||||
|
||||
pub const INTERFACES: &[Interface] = &[
|
||||
(TITLE_PROVIDER, TITLE_IID, &TITLE_OBJECT),
|
||||
(FEATURES, FEATURES, &FEATURES_OBJECT),
|
||||
(INVITES, INVITES, &INVITES_OBJECT),
|
||||
(EVENTS, EVENTS, &EVENTS_OBJECT),
|
||||
];
|
||||
|
||||
type This = *const Object;
|
||||
|
||||
extern "system" fn title_id(_: This, out: *mut u32) -> HRESULT {
|
||||
put(out, runtime::title().id)
|
||||
}
|
||||
|
||||
/// Runtime areas by number, in the public feature list's order, that we
|
||||
/// serve: async calls and providers (2, 3), game (5), invites (6),
|
||||
/// persistent local storage (12), system (15), task queues (16), users
|
||||
/// (18), error reports (19), game events (20). Not the others: store, game
|
||||
/// saves, UI, networking, packages, streaming, threads...
|
||||
const AVAILABLE: [u32; 10] = [2, 3, 5, 6, 12, 15, 16, 18, 19, 20];
|
||||
|
||||
extern "system" fn is_feature_available(_: This, feature: u32) -> bool {
|
||||
AVAILABLE.contains(&feature)
|
||||
}
|
||||
|
||||
/// Nothing raises these events offline, so the callback never runs.
|
||||
extern "system" fn register(
|
||||
_: This,
|
||||
_queue: *const c_void,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
out: *mut u64,
|
||||
) -> HRESULT {
|
||||
put(out, token())
|
||||
}
|
||||
extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Accepted and dropped; the name goes to the debug log.
|
||||
extern "system" fn write_event(
|
||||
_: This,
|
||||
_user: *const c_void,
|
||||
_service_config: *const c_char,
|
||||
_session: *const c_char,
|
||||
name: *const c_char,
|
||||
_dimensions: *const c_char,
|
||||
_measurements: *const c_char,
|
||||
) -> HRESULT {
|
||||
if !name.is_null() {
|
||||
// SAFETY: a non-null name is a NUL-terminated string.
|
||||
let name = unsafe { CStr::from_ptr(name) }.to_string_lossy();
|
||||
tracing::debug!(%name, "game event dropped");
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
static TITLE_VTABLE: Methods<5> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
title_id as *const (), // 0x18
|
||||
missing::<4> as *const (), // 0x20 launch another title (returns nothing)
|
||||
]);
|
||||
|
||||
static FEATURES_VTABLE: Methods<4> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
is_feature_available as *const (), // 0x18
|
||||
]);
|
||||
|
||||
static INVITES_VTABLE: Methods<5> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
register as *const (), // 0x18
|
||||
unregister as *const (), // 0x20
|
||||
]);
|
||||
|
||||
static EVENTS_VTABLE: Methods<4> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
write_event as *const (), // 0x18
|
||||
]);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::modules::xgameruntime::method;
|
||||
|
||||
#[test]
|
||||
fn served_areas_are_available_others_not() {
|
||||
type Check = extern "system" fn(This, u32) -> bool;
|
||||
let check = method::<Check>(&FEATURES_OBJECT, 0x18);
|
||||
assert!(check(&FEATURES_OBJECT, 18), "users");
|
||||
assert!(!check(&FEATURES_OBJECT, 14), "store");
|
||||
|
||||
type Register = extern "system" fn(
|
||||
This,
|
||||
*const c_void,
|
||||
*mut c_void,
|
||||
*const c_void,
|
||||
*mut u64,
|
||||
) -> HRESULT;
|
||||
type Unregister = extern "system" fn(This, u64, bool) -> bool;
|
||||
let null = std::ptr::null();
|
||||
let mut token = 0;
|
||||
let register = method::<Register>(&INVITES_OBJECT, 0x18);
|
||||
assert_eq!(
|
||||
register(&INVITES_OBJECT, null, null as _, null, &mut token),
|
||||
S_OK
|
||||
);
|
||||
assert_ne!(token, 0);
|
||||
assert!(method::<Unregister>(&INVITES_OBJECT, 0x20)(
|
||||
&INVITES_OBJECT,
|
||||
token,
|
||||
true
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,165 @@
|
||||
//! `xgameruntime.dll`: the console game runtime (XGame*, XUser*, XTaskQueue*...).
|
||||
//!
|
||||
//! The DLL names titles actually import these from are confirmed by running
|
||||
//! `victory census` on real titles; extend `dlls` accordingly.
|
||||
//! Titles rarely import it. A stub linked into the title loads the DLL with
|
||||
//! `LoadLibraryExA` (answered with a pseudo handle, see `kernel`), looks up
|
||||
//! the `*ApiImpl` functions and `XErrorReport` with `GetProcAddress`, and
|
||||
//! initialises. Each runtime API call then asks `QueryApiImpl` for a COM-style
|
||||
//! object of its area (provider and interface GUIDs), calls one method and
|
||||
//! releases it. Until an area is implemented its query fails, and the call
|
||||
//! returns that error without touching the object. An area's interface id
|
||||
//! changes when its method table does, so each object answers only the ids
|
||||
//! whose slots we know. Implemented: task queues and async blocks
|
||||
//! (`xasync`), one offline user (`xuser`), system information (`xsystem`),
|
||||
//! title id, feature checks, invites and events (`xgame`), persistent local
|
||||
//! storage (`storage`).
|
||||
#![allow(non_snake_case)]
|
||||
// Title code calls these through its import table, passing pointers the real
|
||||
// API would trust.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::{CStr, c_char, c_void};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use super::{storage, xasync, xgame, xsystem, xuser};
|
||||
use crate::{HleModule, hle_export};
|
||||
|
||||
pub type HRESULT = i32;
|
||||
pub const S_OK: HRESULT = 0;
|
||||
/// `HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)`.
|
||||
pub const NOT_SUPPORTED: HRESULT = 0x8007_0032_u32 as i32;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Guid {
|
||||
pub data1: u32,
|
||||
pub data2: u16,
|
||||
pub data3: u16,
|
||||
pub data4: [u8; 8],
|
||||
}
|
||||
|
||||
impl Guid {
|
||||
pub const fn new(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> Guid {
|
||||
Guid {
|
||||
data1,
|
||||
data2,
|
||||
data3,
|
||||
data4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Guid {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let d = self.data4;
|
||||
write!(
|
||||
f,
|
||||
"{:08x}-{:04x}-{:04x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
|
||||
self.data1, self.data2, self.data3, d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A runtime object as title code calls it: its first word points at the
|
||||
/// method table. Ours are static, so reference counting is a no-op.
|
||||
#[repr(C)]
|
||||
pub struct Object {
|
||||
vtable: *const *const (),
|
||||
/// Named in the log when a title calls a method we lack.
|
||||
area: &'static str,
|
||||
}
|
||||
|
||||
// SAFETY: the table is a static array of function addresses.
|
||||
unsafe impl Sync for Object {}
|
||||
|
||||
impl Object {
|
||||
pub const fn new<const N: usize>(area: &'static str, methods: &'static Methods<N>) -> Object {
|
||||
Object {
|
||||
vtable: methods.0.as_ptr(),
|
||||
area,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An object's method table, by slot (`QueryInterface`, `AddRef`,
|
||||
/// `Release`, then the area's methods from offset 0x18).
|
||||
pub struct Methods<const N: usize>(pub [*const (); N]);
|
||||
|
||||
// SAFETY: function addresses only.
|
||||
unsafe impl<const N: usize> Sync for Methods<N> {}
|
||||
|
||||
/// A (provider, interface id) pair a title may ask for, and our object.
|
||||
pub type Interface = (Guid, Guid, &'static Object);
|
||||
|
||||
const AREAS: [&[Interface]; 5] = [
|
||||
xasync::INTERFACES,
|
||||
xuser::INTERFACES,
|
||||
xsystem::INTERFACES,
|
||||
xgame::INTERFACES,
|
||||
storage::INTERFACES,
|
||||
];
|
||||
|
||||
/// `AddRef` and `Release`.
|
||||
pub extern "system" fn add_ref(_: *const Object) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
/// A slot nobody has needed yet; logged with its area. Wrong for a slot
|
||||
/// that returns `bool` or a value.
|
||||
pub extern "system" fn missing<const SLOT: usize>(this: *const Object) -> HRESULT {
|
||||
// SAFETY: title code calls methods on objects we handed out.
|
||||
let area = unsafe { (*this).area };
|
||||
tracing::warn!(
|
||||
area,
|
||||
slot = format_args!("{:#x}", SLOT * 8),
|
||||
"runtime method not implemented"
|
||||
);
|
||||
xasync::E_NOTIMPL
|
||||
}
|
||||
|
||||
/// Writes `value` through `out` if it is non-null.
|
||||
pub fn put<T>(out: *mut T, value: T) -> HRESULT {
|
||||
if out.is_null() {
|
||||
return xasync::E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: checked non-null; the title passes room for a `T`.
|
||||
unsafe { out.write(value) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Copies `text` and a NUL into the title's `size`-byte buffer and reports
|
||||
/// the bytes used, as the runtime's string getters do.
|
||||
pub fn put_string(text: &str, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
|
||||
let len = text.len() + 1;
|
||||
if buffer.is_null() || size < len {
|
||||
return xasync::E_NOT_SUFFICIENT_BUFFER;
|
||||
}
|
||||
// SAFETY: the buffer holds `size` bytes, checked above.
|
||||
unsafe {
|
||||
buffer.copy_from_nonoverlapping(text.as_ptr(), text.len());
|
||||
buffer.add(text.len()).write(0);
|
||||
}
|
||||
if !used.is_null() {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { used.write(len) };
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// A new registration token for callbacks we never call (events nobody
|
||||
/// raises offline).
|
||||
pub fn token() -> u64 {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Calls method `slot` (byte offset) of `object` as title code would.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn method<F: Copy>(object: &Object, slot: usize) -> F {
|
||||
// SAFETY: the caller names the slot's signature; tables cover the slots
|
||||
// tests use.
|
||||
unsafe { std::mem::transmute_copy(&*object.vtable.add(slot / 8)) }
|
||||
}
|
||||
|
||||
pub extern "system" fn XGameRuntimeInitialize() -> HRESULT {
|
||||
tracing::info!("XGameRuntimeInitialize");
|
||||
@@ -18,6 +170,63 @@ pub extern "system" fn XGameRuntimeUninitialize() {
|
||||
tracing::info!("XGameRuntimeUninitialize");
|
||||
}
|
||||
|
||||
/// The arguments identify the title's build of the stub; not checked.
|
||||
pub extern "system" fn InitializeApiImpl(version: u64, build: u64) -> HRESULT {
|
||||
tracing::info!(version, build, "InitializeApiImpl");
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn InitializeApiImplEx(version: u64, build: u64, flags: u64) -> HRESULT {
|
||||
tracing::info!(version, build, flags, "InitializeApiImplEx");
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn UninitializeApiImpl() {
|
||||
tracing::info!("UninitializeApiImpl");
|
||||
}
|
||||
|
||||
/// The object for an implemented (provider, interface id); others fail,
|
||||
/// each pair logged once.
|
||||
pub extern "system" fn QueryApiImpl(
|
||||
provider: *const Guid,
|
||||
iid: *const Guid,
|
||||
out: *mut *mut c_void,
|
||||
) -> HRESULT {
|
||||
static QUERIED: Mutex<Vec<(Guid, Guid)>> = Mutex::new(Vec::new());
|
||||
// SAFETY: the title passes pointers to GUIDs (null is tolerated).
|
||||
let (Some(&provider), Some(&iid)) = (unsafe { provider.as_ref() }, unsafe { iid.as_ref() })
|
||||
else {
|
||||
return NOT_SUPPORTED;
|
||||
};
|
||||
let found = AREAS
|
||||
.iter()
|
||||
.flat_map(|area| area.iter())
|
||||
.find(|(p, i, _)| (*p, *i) == (provider, iid));
|
||||
if let Some(&(_, _, object)) = found
|
||||
&& !out.is_null()
|
||||
{
|
||||
// SAFETY: checked non-null; the title passes room for a pointer.
|
||||
unsafe { out.write((object as *const Object).cast_mut().cast()) };
|
||||
return S_OK;
|
||||
}
|
||||
let mut queried = QUERIED.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !queried.contains(&(provider, iid)) {
|
||||
queried.push((provider, iid));
|
||||
tracing::warn!(%provider, %iid, "runtime API area not implemented");
|
||||
}
|
||||
NOT_SUPPORTED
|
||||
}
|
||||
|
||||
pub extern "system" fn XErrorReport(hr: HRESULT, message: *const c_char) {
|
||||
let message = if message.is_null() {
|
||||
"".into()
|
||||
} else {
|
||||
// SAFETY: a non-null message is a NUL-terminated string.
|
||||
unsafe { CStr::from_ptr(message) }.to_string_lossy()
|
||||
};
|
||||
tracing::warn!(hr = format_args!("{:#010x}", hr as u32), %message, "XErrorReport");
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "xgameruntime",
|
||||
@@ -25,6 +234,66 @@ pub(crate) fn module() -> HleModule {
|
||||
exports: vec![
|
||||
hle_export!(XGameRuntimeInitialize),
|
||||
hle_export!(XGameRuntimeUninitialize),
|
||||
hle_export!(InitializeApiImpl),
|
||||
hle_export!(InitializeApiImplEx),
|
||||
hle_export!(UninitializeApiImpl),
|
||||
hle_export!(QueryApiImpl),
|
||||
hle_export!(XErrorReport),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::modules::kernel::{FreeLibrary, GetProcAddress, LoadLibraryExA};
|
||||
|
||||
#[test]
|
||||
fn title_stub_loads_the_runtime_dynamically() {
|
||||
let load = |name: &CStr| LoadLibraryExA(name.as_ptr().cast(), std::ptr::null_mut(), 0x800);
|
||||
let runtime = load(c"xgameruntime.dll");
|
||||
assert!(!runtime.is_null());
|
||||
let proc = |name: &CStr| GetProcAddress(runtime, name.as_ptr().cast());
|
||||
for name in [
|
||||
c"InitializeApiImpl",
|
||||
c"InitializeApiImplEx",
|
||||
c"QueryApiImpl",
|
||||
c"UninitializeApiImpl",
|
||||
c"XErrorReport",
|
||||
] {
|
||||
assert!(!proc(name).is_null(), "{name:?}");
|
||||
}
|
||||
assert!(proc(c"NotAnExport").is_null());
|
||||
let ordinal = std::ptr::without_provenance::<u8>(1);
|
||||
assert!(GetProcAddress(runtime, ordinal).is_null());
|
||||
|
||||
type Init = extern "system" fn(u64, u64, u64) -> HRESULT;
|
||||
type Query = extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> HRESULT;
|
||||
// SAFETY: the addresses are our functions with these signatures.
|
||||
let (init, query) = unsafe {
|
||||
(
|
||||
std::mem::transmute::<*mut c_void, Init>(proc(c"InitializeApiImplEx")),
|
||||
std::mem::transmute::<*mut c_void, Query>(proc(c"QueryApiImpl")),
|
||||
)
|
||||
};
|
||||
assert_eq!(init(1, 2, 2), S_OK);
|
||||
let guid = Guid {
|
||||
data1: 1,
|
||||
data2: 2,
|
||||
data3: 3,
|
||||
data4: [4; 8],
|
||||
};
|
||||
let untouched = 0x1234 as *mut c_void;
|
||||
let mut out = untouched;
|
||||
assert!(query(&guid, &guid, &mut out) < 0);
|
||||
assert_eq!(out, untouched);
|
||||
assert_eq!(FreeLibrary(runtime), 1);
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let kernel32 = load(c"kernel32.dll");
|
||||
assert!(!kernel32.is_null(), "host DLLs still load from the host");
|
||||
assert!(!GetProcAddress(kernel32, c"GetTickCount".as_ptr().cast()).is_null());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
//! `xmem.dll`: console memory, served from host memory. The GPU side works
|
||||
//! from CPU addresses (unified memory), so memory types and bandwidth
|
||||
//! classes change nothing here; what constrains addresses (alignment,
|
||||
//! 2 MiB pages, address-bit limits) is honoured.
|
||||
#![allow(non_snake_case)]
|
||||
// Title code calls these through its import table, passing pointers the real
|
||||
// API would trust.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::alloc::{Layout, alloc, dealloc};
|
||||
use std::ffi::c_void;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, MEM_RELEASE, MEM_RESERVE,
|
||||
MEMORY_BASIC_INFORMATION, MemExtendedParameterAddressRequirements, PAGE_NOACCESS,
|
||||
PAGE_READWRITE, VirtualAlloc2, VirtualFree, VirtualQueryEx,
|
||||
};
|
||||
use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
|
||||
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||
use windows_sys::core::BOOL;
|
||||
|
||||
use crate::{HleModule, hle_export};
|
||||
|
||||
const MIB: usize = 1 << 20;
|
||||
const GIB: usize = 1 << 30;
|
||||
/// Title memory of an Xbox Series X in the advanced mode: 10 GiB of
|
||||
/// GPU-optimal and 3.5 GiB of standard memory.
|
||||
const GPU_OPTIMAL_LIMIT: usize = 10 * GIB;
|
||||
const STANDARD_LIMIT: usize = 7 * GIB / 2;
|
||||
|
||||
/// Standard memory the title has handed to the system.
|
||||
static TRANSFERRED: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
// Console additions to the host's flags.
|
||||
/// 2 MiB pages; the host reads this bit as large pages, which need a
|
||||
/// privilege.
|
||||
const PAGES_2M: u32 = 0x2000_0000;
|
||||
/// With `PAGES_2M`: 64 KiB pages; the host reads it as AWE memory.
|
||||
const PAGES_64K_BIT: u32 = 0x40_0000;
|
||||
/// The host's protection constants and `PAGE_GUARD`. Above them the console
|
||||
/// adds GPU access bits (0x800-0x40000). Write-combining and uncached are
|
||||
/// dropped too: our GPU side reads this memory through the CPU.
|
||||
const HOST_PROTECTION: u32 = 0x1ff;
|
||||
/// XMem flags of memory both processors reach: all of ours.
|
||||
const GRAPHICS: u64 = 3;
|
||||
/// XMem flag bit of 32-bit graphics memory.
|
||||
const ADDRESS_32BIT: u64 = 4;
|
||||
|
||||
/// The highest address XMem `flags` allow, 0 for no limit: 32 bits, or
|
||||
/// 46 down to 40 bits from the field at bit 12.
|
||||
fn highest_address(flags: u64) -> usize {
|
||||
let bits = match (flags & ADDRESS_32BIT, flags >> 12 & 7) {
|
||||
(0, 0) => return 0,
|
||||
(0, field) => 47 - field,
|
||||
_ => 32,
|
||||
};
|
||||
(1 << bits) - 1
|
||||
}
|
||||
|
||||
pub extern "system" fn XMemVirtualAlloc(
|
||||
base: *mut c_void,
|
||||
size: usize,
|
||||
kind: u32,
|
||||
flags: u64,
|
||||
protect: u32,
|
||||
) -> *mut c_void {
|
||||
let mut requirements = MEM_ADDRESS_REQUIREMENTS {
|
||||
HighestEndingAddress: highest_address(flags) as *mut c_void,
|
||||
Alignment: if kind & (PAGES_2M | PAGES_64K_BIT) == PAGES_2M {
|
||||
2 * MIB
|
||||
} else {
|
||||
0
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let mut kind = kind & !(PAGES_2M | PAGES_64K_BIT);
|
||||
let protect = match protect & HOST_PROTECTION {
|
||||
0 => PAGE_NOACCESS,
|
||||
p => p,
|
||||
};
|
||||
let mut parameter = MEM_EXTENDED_PARAMETER::default();
|
||||
parameter.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64;
|
||||
parameter.Anonymous2.Pointer = (&raw mut requirements).cast();
|
||||
// Address requirements apply to reservations at an address of our choice.
|
||||
let constrained = base.is_null()
|
||||
&& (!requirements.HighestEndingAddress.is_null() || requirements.Alignment != 0);
|
||||
if constrained {
|
||||
kind |= MEM_RESERVE;
|
||||
}
|
||||
// SAFETY: the title's own arguments, cleaned of console bits; the
|
||||
// parameter points at `requirements`, which outlives the call.
|
||||
unsafe {
|
||||
VirtualAlloc2(
|
||||
GetCurrentProcess(),
|
||||
base,
|
||||
size,
|
||||
kind,
|
||||
protect,
|
||||
if constrained { &mut parameter } else { std::ptr::null_mut() },
|
||||
constrained.into(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the
|
||||
/// same), then the XMem flags and tag.
|
||||
#[repr(C)]
|
||||
pub struct BasicInformation {
|
||||
host: MEMORY_BASIC_INFORMATION,
|
||||
flags: u64,
|
||||
tag_code: u32,
|
||||
tag: [u8; 4],
|
||||
}
|
||||
|
||||
// shortcut: every committed page reports graphics memory and no tag, since
|
||||
// all of it is GPU-reachable here; remember the flags of `XMemVirtualAlloc`
|
||||
// regions if a title tells CPU-only memory apart.
|
||||
pub extern "system" fn XMemVirtualQuery(
|
||||
process: HANDLE,
|
||||
address: *const c_void,
|
||||
out: *mut BasicInformation,
|
||||
) -> BOOL {
|
||||
let size = size_of::<MEMORY_BASIC_INFORMATION>();
|
||||
// SAFETY: the title passes room for the whole structure; the host
|
||||
// fails on a null one.
|
||||
unsafe {
|
||||
if VirtualQueryEx(process, address, out.cast(), size) == 0 {
|
||||
return 0;
|
||||
}
|
||||
let info = &mut *out;
|
||||
info.flags = if info.host.State == MEM_COMMIT { GRAPHICS } else { 0 };
|
||||
info.tag_code = 0;
|
||||
info.tag = [0; 4];
|
||||
}
|
||||
1
|
||||
}
|
||||
|
||||
// `XMemAlloc` attributes: alignment as log2 (5 bits at 24, 4 bytes and up
|
||||
// from 2), then the memory type, then bit 33: a 32-bit address.
|
||||
const ALIGNMENT_SHIFT: u64 = 24;
|
||||
const ALLOC_32BIT: u64 = 1 << 33;
|
||||
/// Our block header: the block's size and alignment, just below the
|
||||
/// pointer handed out.
|
||||
const HEADER: usize = 2 * size_of::<usize>();
|
||||
|
||||
fn layout(size: usize, attributes: u64) -> Option<Layout> {
|
||||
// An alignment of at least 16 leaves room for the header.
|
||||
let align = 1usize << (attributes >> ALIGNMENT_SHIFT & 0x1f).max(4);
|
||||
Layout::from_size_align(size.checked_add(align)?, align).ok()
|
||||
}
|
||||
|
||||
/// The title's general allocator, for middleware too.
|
||||
// shortcut: allocation hooks (`XMemSetAllocationHooks`, or hooks the title
|
||||
// exports) are not called; no title we have sets them.
|
||||
pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void {
|
||||
if attributes & ALLOC_32BIT != 0 {
|
||||
return XMemVirtualAlloc(
|
||||
std::ptr::null_mut(),
|
||||
size,
|
||||
MEM_RESERVE | MEM_COMMIT,
|
||||
GRAPHICS | ADDRESS_32BIT,
|
||||
PAGE_READWRITE,
|
||||
);
|
||||
}
|
||||
let Some(layout) = layout(size, attributes) else {
|
||||
return std::ptr::null_mut();
|
||||
};
|
||||
// SAFETY: the layout has a non-zero size.
|
||||
let block = unsafe { alloc(layout) };
|
||||
if block.is_null() {
|
||||
return block.cast();
|
||||
}
|
||||
// SAFETY: the block holds the alignment (at least the header) and then
|
||||
// `size` bytes.
|
||||
unsafe {
|
||||
let user = block.add(layout.align());
|
||||
user.sub(HEADER)
|
||||
.cast::<[usize; 2]>()
|
||||
.write([layout.size(), layout.align()]);
|
||||
user.cast()
|
||||
}
|
||||
}
|
||||
|
||||
/// Frees what [`XMemAlloc`] returned, given the same attributes.
|
||||
pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) {
|
||||
if address.is_null() {
|
||||
return;
|
||||
}
|
||||
// SAFETY: the address came from `XMemAlloc` with these attributes: a
|
||||
// whole reservation, or a header-prefixed block.
|
||||
unsafe {
|
||||
if attributes & ALLOC_32BIT != 0 {
|
||||
VirtualFree(address, 0, MEM_RELEASE);
|
||||
return;
|
||||
}
|
||||
let user = address.cast::<u8>();
|
||||
let [size, align] = user.sub(HEADER).cast::<[usize; 2]>().read();
|
||||
dealloc(
|
||||
user.sub(align),
|
||||
Layout::from_size_align_unchecked(size, align),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The oldest layout we know; newer titles pass other flag values (Minecraft
|
||||
/// 0x20000001) and read the same leading fields.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Default)]
|
||||
pub struct WorkingSet {
|
||||
pub title_limit: usize,
|
||||
pub title_used: usize,
|
||||
pub tools_limit: usize,
|
||||
pub tools_used: usize,
|
||||
pub stack_used: u32,
|
||||
pub physical_pages: u32,
|
||||
pub gpu_optimal_limit: usize,
|
||||
pub gpu_optimal_used: usize,
|
||||
pub tools_gpu_optimal_limit: usize,
|
||||
pub tools_gpu_optimal_used: usize,
|
||||
pub kernel_pool_used: u32,
|
||||
pub kernel_pool_limit: u32,
|
||||
}
|
||||
|
||||
/// The title's budget and our process's commit as what it uses. No tools
|
||||
/// memory: a retail console.
|
||||
// shortcut: all fields are filled whatever the flags ask for, and use is
|
||||
// not split by bandwidth class (GPU-optimal use reads 0); track
|
||||
// allocations per class if a title budgets from that field.
|
||||
pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut WorkingSet) -> BOOL {
|
||||
if out.is_null() {
|
||||
return 0;
|
||||
}
|
||||
let mut counters = PROCESS_MEMORY_COUNTERS {
|
||||
cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: our own process and a sized structure.
|
||||
unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) };
|
||||
let stats = WorkingSet {
|
||||
title_limit: GPU_OPTIMAL_LIMIT + STANDARD_LIMIT - TRANSFERRED.load(Ordering::Relaxed),
|
||||
title_used: counters.PagefileUsage,
|
||||
gpu_optimal_limit: GPU_OPTIMAL_LIMIT,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: checked non-null; the title passes room for the structure.
|
||||
unsafe { out.write(stats) };
|
||||
1
|
||||
}
|
||||
|
||||
/// Hands title memory (standard, in 2 MiB pages) to the system. The other
|
||||
/// transfers involve tools memory, which a retail console has none of.
|
||||
pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL {
|
||||
const TITLE_TO_SYSTEM: u32 = 0;
|
||||
tracing::info!(kind, size, "XMemTransferMemory");
|
||||
if size == 0 {
|
||||
return 1;
|
||||
}
|
||||
let Some(size) = size.checked_next_multiple_of(2 * MIB) else {
|
||||
return 0;
|
||||
};
|
||||
let moved = kind == TITLE_TO_SYSTEM
|
||||
&& TRANSFERRED
|
||||
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |t| {
|
||||
t.checked_add(size).filter(|&t| t <= STANDARD_LIMIT)
|
||||
})
|
||||
.is_ok();
|
||||
moved.into()
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "xmem",
|
||||
dlls: &["xmem.dll"],
|
||||
exports: vec![
|
||||
hle_export!(XMemAlloc),
|
||||
hle_export!(XMemFree),
|
||||
hle_export!(XMemVirtualAlloc),
|
||||
hle_export!(XMemVirtualQuery),
|
||||
hle_export!(XMemGetWorkingSetStatistics),
|
||||
hle_export!(XMemTransferMemory),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn query(address: *const c_void) -> BasicInformation {
|
||||
// SAFETY: plain data; zero is a valid value.
|
||||
let mut info: BasicInformation = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: a pseudo handle needs no closing.
|
||||
let process = unsafe { GetCurrentProcess() };
|
||||
assert_eq!(XMemVirtualQuery(process, address, &mut info), 1);
|
||||
info
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alloc_honours_alignment_and_frees() {
|
||||
for (field, align) in [(0, 16), (4, 16), (0xc, 4096), (0x10, 64 * 1024)] {
|
||||
let attributes = field << ALIGNMENT_SHIFT | 1 << 29; // a graphics type
|
||||
let p = XMemAlloc(100, attributes);
|
||||
assert!(!p.is_null());
|
||||
assert_eq!(p as usize % align, 0, "field {field:#x}");
|
||||
// SAFETY: 100 bytes were allocated.
|
||||
unsafe { p.cast::<u8>().write_bytes(0xab, 100) };
|
||||
XMemFree(p, attributes);
|
||||
}
|
||||
let p = XMemAlloc(4096, ALLOC_32BIT);
|
||||
assert!(!p.is_null() && (p as usize) < 1 << 32);
|
||||
XMemFree(p, ALLOC_32BIT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn virtual_alloc_meets_console_constraints() {
|
||||
const GPU_READ_WRITE: u32 = 0x2000;
|
||||
let p = XMemVirtualAlloc(
|
||||
std::ptr::null_mut(),
|
||||
4 * MIB,
|
||||
PAGES_2M | MEM_RESERVE | MEM_COMMIT,
|
||||
GRAPHICS | 7 << 12, // 40-bit addresses
|
||||
PAGE_READWRITE | GPU_READ_WRITE,
|
||||
);
|
||||
assert!(!p.is_null());
|
||||
assert_eq!(p as usize % (2 * MIB), 0);
|
||||
assert!((p as usize) < 1 << 40);
|
||||
let info = query(p);
|
||||
assert_eq!(info.host.State, MEM_COMMIT);
|
||||
assert_eq!(info.host.Protect, PAGE_READWRITE);
|
||||
assert_eq!(info.flags & GRAPHICS, GRAPHICS);
|
||||
// SAFETY: our own reservation.
|
||||
assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
|
||||
assert_eq!(query(p).flags, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transfers_shrink_the_title_budget() {
|
||||
let mut before = WorkingSet::default();
|
||||
assert_eq!(XMemGetWorkingSetStatistics(0x2000_0001, &mut before), 1);
|
||||
assert!(before.title_used > 0);
|
||||
assert_eq!(XMemTransferMemory(0, 128 * MIB - 1), 1);
|
||||
assert_eq!(XMemTransferMemory(2, MIB), 0, "no tools memory");
|
||||
assert_eq!(XMemTransferMemory(0, STANDARD_LIMIT), 0, "over budget");
|
||||
let mut after = WorkingSet::default();
|
||||
XMemGetWorkingSetStatistics(0x2000_0001, &mut after);
|
||||
assert_eq!(before.title_limit - after.title_limit, 128 * MIB);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statistics_have_the_console_layout() {
|
||||
assert_eq!(size_of::<WorkingSet>(), 0x50);
|
||||
assert_eq!(size_of::<BasicInformation>(), 0x40);
|
||||
assert_eq!(std::mem::offset_of!(WorkingSet, gpu_optimal_limit), 0x28);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
//! XSystem: the console's identity and sandbox, and how analytics describe
|
||||
//! the device. Fixed values: one offline retail Xbox Series X.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, Object, add_ref, missing, put_string,
|
||||
};
|
||||
|
||||
pub const PROVIDER: Guid = Guid::new(
|
||||
0xe349_bd1a,
|
||||
0xfc20,
|
||||
0x4e40,
|
||||
[0xb9, 0x9c, 0x41, 0x78, 0xcc, 0x6b, 0x40, 0x9f],
|
||||
);
|
||||
|
||||
/// The interface as Minecraft (2022) asks for it; an older table
|
||||
/// ended before the device id.
|
||||
pub const IID: Guid = Guid::new(
|
||||
0x6fd7_1f09,
|
||||
0x7513,
|
||||
0x49f0,
|
||||
[0x89, 0xbc, 0xbf, 0xaf, 0x5d, 0xf6, 0xf8, 0x52],
|
||||
);
|
||||
|
||||
/// Analytics information; its interface id is the provider's.
|
||||
pub const ANALYTICS: Guid = Guid::new(
|
||||
0xb884_675d,
|
||||
0xb738,
|
||||
0x4a9c,
|
||||
[0x81, 0x5d, 0x9a, 0x9a, 0x1e, 0x0c, 0x6c, 0x9b],
|
||||
);
|
||||
|
||||
/// 38 characters (39 bytes with the NUL).
|
||||
const CONSOLE_ID: &str = "00000000000000000000000000000000000001";
|
||||
/// The retail sandbox.
|
||||
const SANDBOX: &str = "RETAIL";
|
||||
/// Base64 of 32 bytes: 44 characters (45 bytes with the NUL).
|
||||
const DEVICE_ID: &str = "VkljdG9yeSBvZmZsaW5lIGRldmljZSBpZGVudGl0eSE=";
|
||||
|
||||
pub static OBJECT: Object = Object::new("system", &VTABLE);
|
||||
pub static ANALYTICS_OBJECT: Object = Object::new("analytics", &ANALYTICS_VTABLE);
|
||||
|
||||
pub const INTERFACES: &[Interface] = &[
|
||||
(PROVIDER, IID, &OBJECT),
|
||||
(ANALYTICS, ANALYTICS, &ANALYTICS_OBJECT),
|
||||
];
|
||||
|
||||
type This = *const Object;
|
||||
|
||||
extern "system" fn console_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
|
||||
put_string(CONSOLE_ID, size, buffer, used)
|
||||
}
|
||||
extern "system" fn sandbox_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
|
||||
put_string(SANDBOX, size, buffer, used)
|
||||
}
|
||||
/// The device id this title sees (titles see different ones).
|
||||
extern "system" fn device_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
|
||||
put_string(DEVICE_ID, size, buffer, used)
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Version {
|
||||
pub major: u16,
|
||||
pub minor: u16,
|
||||
pub build: u16,
|
||||
pub revision: u16,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct AnalyticsInfo {
|
||||
pub os: Version,
|
||||
pub hosting_os: Version,
|
||||
/// NUL-terminated.
|
||||
pub family: [u8; 64],
|
||||
pub form: [u8; 64],
|
||||
}
|
||||
|
||||
const OS: Version = Version {
|
||||
major: 10,
|
||||
minor: 0,
|
||||
build: 22000,
|
||||
revision: 0,
|
||||
};
|
||||
|
||||
fn text(s: &str) -> [u8; 64] {
|
||||
let mut out = [0; 64];
|
||||
out[..s.len()].copy_from_slice(s.as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// A struct this large comes back through the caller's buffer, whose
|
||||
/// address is also the return value.
|
||||
extern "system" fn analytics_info(_: This, out: *mut AnalyticsInfo) -> *mut AnalyticsInfo {
|
||||
let info = AnalyticsInfo {
|
||||
os: OS,
|
||||
hosting_os: OS,
|
||||
family: text("Xbox"),
|
||||
form: text("Xbox Series X"),
|
||||
};
|
||||
// SAFETY: the caller passes room for the struct.
|
||||
unsafe { out.write(info) };
|
||||
out
|
||||
}
|
||||
|
||||
static VTABLE: Methods<6> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
console_id as *const (), // 0x18, by the older table; titles seen do not call it
|
||||
sandbox_id as *const (), // 0x20
|
||||
device_id as *const (), // 0x28
|
||||
]);
|
||||
|
||||
static ANALYTICS_VTABLE: Methods<4> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
analytics_info as *const (), // 0x18
|
||||
]);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::modules::xgameruntime::{S_OK, method};
|
||||
|
||||
#[test]
|
||||
fn identity_strings_fit_the_documented_sizes() {
|
||||
type Get = extern "system" fn(This, usize, *mut u8, *mut usize) -> HRESULT;
|
||||
let this: This = &OBJECT;
|
||||
let mut buffer = [0u8; 64];
|
||||
let mut used = 0;
|
||||
for (slot, size) in [(0x18, 39), (0x20, 16), (0x28, 45)] {
|
||||
let get = method::<Get>(&OBJECT, slot);
|
||||
assert_eq!(get(this, size, buffer.as_mut_ptr(), &mut used), S_OK);
|
||||
assert!(used <= size && buffer[used - 1] == 0, "slot {slot:#x}");
|
||||
}
|
||||
assert_eq!(&buffer[..7], b"VkljdG9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analytics_info_comes_back_through_the_buffer() {
|
||||
type Get = extern "system" fn(This, *mut AnalyticsInfo) -> *mut AnalyticsInfo;
|
||||
let mut info = std::mem::MaybeUninit::<AnalyticsInfo>::uninit();
|
||||
let get = method::<Get>(&ANALYTICS_OBJECT, 0x18);
|
||||
let back = get(&ANALYTICS_OBJECT, info.as_mut_ptr());
|
||||
assert_eq!(back, info.as_mut_ptr());
|
||||
// SAFETY: written by the call.
|
||||
let info = unsafe { info.assume_init() };
|
||||
assert_eq!(size_of::<AnalyticsInfo>(), 0x90);
|
||||
assert_eq!(info.os.build, 22000);
|
||||
assert_eq!(&info.form[..14], b"Xbox Series X\0");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
//! XUser: one offline local user, signed in, never a guest, with every
|
||||
//! privilege. Served as the user provider's objects from `QueryApiImpl`;
|
||||
//! adding a user completes through `xasync` like any other async call. No
|
||||
//! input device is associated with the user (there are none, `gameinput`).
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
|
||||
use super::xasync::{self, AsyncBlock, ProviderData};
|
||||
use super::xgameruntime::{
|
||||
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, token,
|
||||
};
|
||||
|
||||
/// The user provider.
|
||||
pub const PROVIDER: Guid = Guid {
|
||||
data1: 0x01ac_d177,
|
||||
data2: 0x91f9,
|
||||
data3: 0x4763,
|
||||
data4: [0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0],
|
||||
};
|
||||
|
||||
/// Its main interface.
|
||||
pub const IID: Guid = Guid {
|
||||
data1: 0xeb9b_f948,
|
||||
data2: 0x18dc,
|
||||
data3: 0x4d82,
|
||||
data4: [0xbb, 0xcc, 0x40, 0xe0, 0xa8, 0x09, 0xc4, 0xc0],
|
||||
};
|
||||
|
||||
/// The interface titles ask for to read a gamertag.
|
||||
pub const GAMERTAG_IID: Guid = Guid {
|
||||
data1: 0xcef4_fac0,
|
||||
data2: 0x7676,
|
||||
data3: 0x4a94,
|
||||
data4: [0xa1, 0x19, 0x4c, 0x43, 0xf9, 0xeb, 0x5b, 0x74],
|
||||
};
|
||||
|
||||
/// The user's devices and audio endpoints.
|
||||
pub const DEVICE_PROVIDER: Guid = Guid::new(
|
||||
0x7d82_4997,
|
||||
0x10dc,
|
||||
0x45ab,
|
||||
[0x86, 0xb7, 0x27, 0x37, 0x76, 0x7c, 0x0b, 0xf1],
|
||||
);
|
||||
|
||||
/// The device interface as Minecraft (2022) asks for it.
|
||||
pub const DEVICE_IID: Guid = Guid::new(
|
||||
0x0cc6_a956,
|
||||
0xe7e1,
|
||||
0x4fdf,
|
||||
[0x93, 0x41, 0x9d, 0x5d, 0xa6, 0x49, 0xeb, 0xc8],
|
||||
);
|
||||
|
||||
/// The documented "no such user" error.
|
||||
pub const USER_NOT_FOUND: HRESULT = 0x8924_5104_u32 as i32;
|
||||
|
||||
pub const XUID: u64 = 0x0009_0000_0000_0001;
|
||||
pub const LOCAL_ID: u64 = 1;
|
||||
const GAMERTAG: &str = "Player";
|
||||
|
||||
/// The only user; a handle is its address, duplicating and closing are free.
|
||||
pub struct User;
|
||||
static USER: User = User;
|
||||
type Handle = *const User;
|
||||
|
||||
fn user() -> Handle {
|
||||
&USER
|
||||
}
|
||||
|
||||
fn found(found: bool, out: *mut Handle) -> HRESULT {
|
||||
if found {
|
||||
put(out, user())
|
||||
} else {
|
||||
USER_NOT_FOUND
|
||||
}
|
||||
}
|
||||
|
||||
pub static OBJECT: Object = Object::new("user", &VTABLE);
|
||||
pub static GAMERTAG_OBJECT: Object = Object::new("user gamertag", &GAMERTAG_VTABLE);
|
||||
pub static DEVICE_OBJECT: Object = Object::new("user devices", &DEVICE_VTABLE);
|
||||
|
||||
pub const INTERFACES: &[Interface] = &[
|
||||
(PROVIDER, IID, &OBJECT),
|
||||
(PROVIDER, GAMERTAG_IID, &GAMERTAG_OBJECT),
|
||||
(DEVICE_PROVIDER, DEVICE_IID, &DEVICE_OBJECT),
|
||||
];
|
||||
|
||||
type This = *const Object;
|
||||
extern "system" fn duplicate(_: This, _: Handle, out: *mut Handle) -> HRESULT {
|
||||
put(out, user())
|
||||
}
|
||||
extern "system" fn close(_: This, _: Handle) {}
|
||||
extern "system" fn compare(_: This, a: Handle, b: Handle) -> i32 {
|
||||
i32::from(a != b)
|
||||
}
|
||||
|
||||
/// The async provider for adding a user: done at once, the result is a
|
||||
/// handle.
|
||||
extern "system" fn add_provider(op: u32, data: *const ProviderData) -> HRESULT {
|
||||
const BEGIN: u32 = 0;
|
||||
const GET_RESULT: u32 = 2;
|
||||
// SAFETY: the async runtime passes valid provider data.
|
||||
let data = unsafe { &*data };
|
||||
match op {
|
||||
BEGIN => xasync::XAsyncComplete(data.block, S_OK, size_of::<Handle>()),
|
||||
GET_RESULT => return put(data.buffer.cast::<Handle>(), user()),
|
||||
_ => {}
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Tells our add calls apart from other async calls on the same block.
|
||||
static ADD: u8 = 0;
|
||||
|
||||
/// Any options add the one user, silently.
|
||||
extern "system" fn add_async(_: This, options: u32, block: *mut AsyncBlock) -> HRESULT {
|
||||
tracing::info!(options, "XUserAddAsync: the offline local user");
|
||||
xasync::XAsyncBegin(
|
||||
block,
|
||||
std::ptr::null_mut(),
|
||||
(&raw const ADD).cast(),
|
||||
std::ptr::null(),
|
||||
Some(add_provider),
|
||||
)
|
||||
}
|
||||
extern "system" fn add_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT {
|
||||
xasync::XAsyncGetResult(
|
||||
block,
|
||||
(&raw const ADD).cast(),
|
||||
size_of::<Handle>(),
|
||||
out.cast(),
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
}
|
||||
extern "system" fn get_local_id(_: This, _: Handle, out: *mut u64) -> HRESULT {
|
||||
put(out, LOCAL_ID)
|
||||
}
|
||||
extern "system" fn find_by_local_id(_: This, id: u64, out: *mut Handle) -> HRESULT {
|
||||
found(id == LOCAL_ID, out)
|
||||
}
|
||||
extern "system" fn get_id(_: This, _: Handle, out: *mut u64) -> HRESULT {
|
||||
put(out, XUID)
|
||||
}
|
||||
extern "system" fn find_by_id(_: This, id: u64, out: *mut Handle) -> HRESULT {
|
||||
found(id == XUID, out)
|
||||
}
|
||||
extern "system" fn get_is_guest(_: This, _: Handle, out: *mut bool) -> HRESULT {
|
||||
put(out, false)
|
||||
}
|
||||
/// 0: signed in.
|
||||
extern "system" fn get_state(_: This, _: Handle, out: *mut u32) -> HRESULT {
|
||||
put(out, 0)
|
||||
}
|
||||
/// The same name for every component (classic, modern, suffix, unique).
|
||||
extern "system" fn get_gamertag(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_component: u32,
|
||||
size: usize,
|
||||
buffer: *mut u8,
|
||||
used: *mut usize,
|
||||
) -> HRESULT {
|
||||
put_string(GAMERTAG, size, buffer, used)
|
||||
}
|
||||
/// Granted; deny reason 0 (none).
|
||||
extern "system" fn check_privilege(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_options: u32,
|
||||
_privilege: u32,
|
||||
has: *mut bool,
|
||||
reason: *mut u32,
|
||||
) -> HRESULT {
|
||||
if !reason.is_null() {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { reason.write(0) };
|
||||
}
|
||||
put(has, true)
|
||||
}
|
||||
|
||||
/// The user never changes and no device is ever associated, so these
|
||||
/// callbacks are never called.
|
||||
extern "system" fn register(
|
||||
_: This,
|
||||
_queue: *const c_void,
|
||||
_context: *mut c_void,
|
||||
_callback: *const c_void,
|
||||
out: *mut u64,
|
||||
) -> HRESULT {
|
||||
put(out, token())
|
||||
}
|
||||
extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// No input device belongs to a user.
|
||||
extern "system" fn find_for_device(_: This, _device: *const c_void, _: *mut Handle) -> HRESULT {
|
||||
USER_NOT_FOUND
|
||||
}
|
||||
|
||||
// Unset slots: gamer pictures, token and signature, issue resolution.
|
||||
static VTABLE: Methods<35> = Methods([
|
||||
missing::<0> as *const (), // 0x00 QueryInterface
|
||||
add_ref as *const (), // 0x08 AddRef
|
||||
add_ref as *const (), // 0x10 Release: the object is static
|
||||
duplicate as *const (), // 0x18
|
||||
close as *const (), // 0x20
|
||||
compare as *const (), // 0x28
|
||||
missing::<6> as *const (), // 0x30 maximum users
|
||||
add_async as *const (), // 0x38
|
||||
add_result as *const (), // 0x40
|
||||
get_local_id as *const (), // 0x48
|
||||
find_by_local_id as *const (), // 0x50
|
||||
get_id as *const (), // 0x58
|
||||
find_by_id as *const (), // 0x60
|
||||
get_is_guest as *const (), // 0x68
|
||||
get_state as *const (), // 0x70
|
||||
get_gamertag as *const (), // 0x78 older gamertag slot
|
||||
missing::<16> as *const (), // 0x80 gamer picture: begin
|
||||
missing::<17> as *const (), // 0x88 result size
|
||||
missing::<18> as *const (), // 0x90 result
|
||||
missing::<19> as *const (), // 0x98 age group
|
||||
check_privilege as *const (), // 0xa0
|
||||
missing::<21> as *const (), // 0xa8 resolve privilege with UI: begin
|
||||
missing::<22> as *const (), // 0xb0 result
|
||||
missing::<23> as *const (), // 0xb8 token and signature: begin
|
||||
missing::<24> as *const (), // 0xc0 result size
|
||||
missing::<25> as *const (), // 0xc8 result
|
||||
missing::<26> as *const (), // 0xd0 the same, UTF-16: begin
|
||||
missing::<27> as *const (), // 0xd8 result size
|
||||
missing::<28> as *const (), // 0xe0 result
|
||||
missing::<29> as *const (), // 0xe8 resolve issue with UI: begin
|
||||
missing::<30> as *const (), // 0xf0 result
|
||||
missing::<31> as *const (), // 0xf8 the same, UTF-16: begin
|
||||
missing::<32> as *const (), // 0x100 result
|
||||
register as *const (), // 0x108 change event
|
||||
unregister as *const (), // 0x110
|
||||
]);
|
||||
|
||||
static GAMERTAG_VTABLE: Methods<4> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
get_gamertag as *const (), // 0x18
|
||||
]);
|
||||
|
||||
static DEVICE_VTABLE: Methods<6> = Methods([
|
||||
missing::<0> as *const (),
|
||||
add_ref as *const (),
|
||||
add_ref as *const (),
|
||||
find_for_device as *const (), // 0x18
|
||||
register as *const (), // 0x20 device association changed
|
||||
unregister as *const (), // 0x28
|
||||
]);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::modules::xasync::E_NOT_SUFFICIENT_BUFFER;
|
||||
use crate::modules::xgameruntime::method as slot;
|
||||
|
||||
#[test]
|
||||
fn startup_adds_the_user_and_reads_its_id() {
|
||||
type Add = extern "system" fn(This, u32, *mut AsyncBlock) -> HRESULT;
|
||||
type AddResult = extern "system" fn(This, *mut AsyncBlock, *mut Handle) -> HRESULT;
|
||||
type GetId = extern "system" fn(This, Handle, *mut u64) -> HRESULT;
|
||||
type Gamertag =
|
||||
extern "system" fn(This, Handle, u32, usize, *mut u8, *mut usize) -> HRESULT;
|
||||
let this: This = &OBJECT;
|
||||
let mut block = AsyncBlock {
|
||||
queue: std::ptr::null(),
|
||||
context: std::ptr::null_mut(),
|
||||
callback: None,
|
||||
internal: [0; 4],
|
||||
};
|
||||
assert_eq!(slot::<Add>(&OBJECT, 0x38)(this, 1, &mut block), S_OK);
|
||||
assert_eq!(xasync::XAsyncGetStatus(&mut block, true), S_OK);
|
||||
let mut handle = std::ptr::null();
|
||||
assert_eq!(
|
||||
slot::<AddResult>(&OBJECT, 0x40)(this, &mut block, &mut handle),
|
||||
S_OK
|
||||
);
|
||||
assert!(!handle.is_null());
|
||||
let mut xuid = 0;
|
||||
assert_eq!(slot::<GetId>(&OBJECT, 0x58)(this, handle, &mut xuid), S_OK);
|
||||
assert_eq!(xuid, XUID);
|
||||
|
||||
let mut name = [0u8; 16];
|
||||
let mut used = 0;
|
||||
let get = slot::<Gamertag>(&GAMERTAG_OBJECT, 0x18);
|
||||
assert_eq!(get(this, handle, 0, 16, name.as_mut_ptr(), &mut used), S_OK);
|
||||
assert_eq!(&name[..used], b"Player\0");
|
||||
assert_eq!(
|
||||
get(this, handle, 0, 2, name.as_mut_ptr(), &mut used),
|
||||
E_NOT_SUFFICIENT_BUFFER
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,8 @@ use std::sync::LazyLock;
|
||||
|
||||
use crate::modules;
|
||||
|
||||
/// One function we implement, under the name the title imports.
|
||||
/// One function we implement, under the name the title imports (`#n` for an
|
||||
/// ordinal).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct HleExport {
|
||||
pub name: &'static str,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! Process-wide state the implementations need.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
static MAIN_IMAGE_BASE: AtomicUsize = AtomicUsize::new(0);
|
||||
@@ -16,3 +18,88 @@ pub fn main_image() -> Option<usize> {
|
||||
base => Some(base),
|
||||
}
|
||||
}
|
||||
|
||||
/// Original file of each title image we mapped, by base address.
|
||||
static IMAGE_PATHS: Mutex<Vec<(usize, PathBuf)>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Records the file a title image was mapped from: the title asks for its
|
||||
/// own path (`GetModuleFileName`) to find its data, and must not get our
|
||||
/// cache copy.
|
||||
pub fn set_image_path(base: usize, path: &Path) {
|
||||
let path = std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
|
||||
let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
paths.retain(|(b, _)| *b != base);
|
||||
paths.push((base, path));
|
||||
}
|
||||
|
||||
pub fn image_path(base: usize) -> Option<PathBuf> {
|
||||
let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
paths
|
||||
.iter()
|
||||
.find(|(b, _)| *b == base)
|
||||
.map(|(_, p)| p.clone())
|
||||
}
|
||||
|
||||
/// What the title's manifest (`MicrosoftGame.config` beside its executable)
|
||||
/// says about it, and where its persistent local storage lives.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Title {
|
||||
pub id: u32,
|
||||
/// Persistent local storage: our folder for it and the title's quota.
|
||||
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.
|
||||
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());
|
||||
Title {
|
||||
id: id.unwrap_or(0),
|
||||
storage: PathBuf::new(),
|
||||
storage_bytes: storage_mb.unwrap_or(0) << 20,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static TITLE: Mutex<Option<Title>> = Mutex::new(None);
|
||||
|
||||
pub fn set_title(title: Title) {
|
||||
*TITLE.lock().unwrap_or_else(|e| e.into_inner()) = Some(title);
|
||||
}
|
||||
|
||||
/// The running title; the default (id 0, no storage) until set.
|
||||
pub fn title() -> Title {
|
||||
TITLE
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.clone()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[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\
|
||||
<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!(Title::from_manifest("").storage_bytes, 0);
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ blake3.workspace = true
|
||||
windows-sys = { workspace = true, features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_System_Diagnostics_Debug",
|
||||
"Win32_System_Kernel",
|
||||
"Win32_System_LibraryLoader",
|
||||
"Win32_System_Memory",
|
||||
"Win32_System_Threading",
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Names the faulting code when title code crashes.
|
||||
//!
|
||||
//! A vectored handler sees every exception first, so it only logs the kinds
|
||||
//! that end a process (access violations and the like) and leaves handling
|
||||
//! to the title's own handlers.
|
||||
|
||||
use windows_sys::Win32::Foundation::{
|
||||
EXCEPTION_ACCESS_VIOLATION, EXCEPTION_ILLEGAL_INSTRUCTION, EXCEPTION_INT_DIVIDE_BY_ZERO,
|
||||
EXCEPTION_PRIV_INSTRUCTION, EXCEPTION_STACK_OVERFLOW, HMODULE,
|
||||
};
|
||||
use windows_sys::Win32::System::Diagnostics::Debug::{
|
||||
AddVectoredExceptionHandler, EXCEPTION_POINTERS,
|
||||
};
|
||||
use windows_sys::Win32::System::LibraryLoader::{
|
||||
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||
GetModuleFileNameW, GetModuleHandleExW,
|
||||
};
|
||||
|
||||
const EXCEPTION_CONTINUE_SEARCH: i32 = 0;
|
||||
/// Stack slots scanned for return addresses into a module.
|
||||
const STACK_SCAN: usize = 64;
|
||||
|
||||
/// Installs the handler; call once before running title code.
|
||||
pub fn report_crashes() {
|
||||
// SAFETY: registers a handler that only reads the exception it is given.
|
||||
unsafe { AddVectoredExceptionHandler(0, Some(handler)) };
|
||||
}
|
||||
|
||||
unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 {
|
||||
// SAFETY: the system passes valid exception pointers.
|
||||
let (record, context) = unsafe { (&*(*info).ExceptionRecord, &*(*info).ContextRecord) };
|
||||
let code = record.ExceptionCode;
|
||||
if ![
|
||||
EXCEPTION_ACCESS_VIOLATION,
|
||||
EXCEPTION_ILLEGAL_INSTRUCTION,
|
||||
EXCEPTION_PRIV_INSTRUCTION,
|
||||
EXCEPTION_INT_DIVIDE_BY_ZERO,
|
||||
EXCEPTION_STACK_OVERFLOW,
|
||||
]
|
||||
.contains(&code)
|
||||
{
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
let at = record.ExceptionAddress as usize;
|
||||
let access = if code == EXCEPTION_ACCESS_VIOLATION {
|
||||
let kind = match record.ExceptionInformation[0] {
|
||||
0 => "read",
|
||||
1 => "write",
|
||||
_ => "execute",
|
||||
};
|
||||
format!(" ({kind} {:#x})", record.ExceptionInformation[1])
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
eprintln!(
|
||||
"VIctory: exception {:#010x} at {}{access}",
|
||||
code as u32,
|
||||
locate(at)
|
||||
);
|
||||
eprintln!(
|
||||
" rax {:#x} rbx {:#x} rcx {:#x} rdx {:#x} rsi {:#x} rdi {:#x} rsp {:#x}",
|
||||
context.Rax, context.Rbx, context.Rcx, context.Rdx, context.Rsi, context.Rdi, context.Rsp
|
||||
);
|
||||
// shortcut: a stack scan, not an unwind; it lists stale return
|
||||
// addresses too. Use RtlVirtualUnwind if this misleads.
|
||||
let stack = context.Rsp as *const usize;
|
||||
for i in 0..STACK_SCAN {
|
||||
// SAFETY: slots just above the faulting RSP are committed stack.
|
||||
let value = unsafe { stack.add(i).read_unaligned() };
|
||||
if let Some(name) = module_of(value) {
|
||||
eprintln!(" [rsp+{:#x}] {name}", i * 8);
|
||||
}
|
||||
}
|
||||
EXCEPTION_CONTINUE_SEARCH
|
||||
}
|
||||
|
||||
/// `module+rva`, or the bare address.
|
||||
pub fn locate(address: usize) -> String {
|
||||
module_of(address).unwrap_or_else(|| format!("{address:#x}"))
|
||||
}
|
||||
|
||||
fn module_of(address: usize) -> Option<String> {
|
||||
let mut module: HMODULE = std::ptr::null_mut();
|
||||
// SAFETY: looks up the module containing `address`; no reference taken.
|
||||
let found = unsafe {
|
||||
GetModuleHandleExW(
|
||||
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||
address as *const u16,
|
||||
&mut module,
|
||||
)
|
||||
};
|
||||
if found == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut path = [0u16; 260];
|
||||
// SAFETY: `module` is a loaded module; the buffer length is passed.
|
||||
let len = unsafe { GetModuleFileNameW(module, path.as_mut_ptr(), path.len() as u32) };
|
||||
let path = String::from_utf16_lossy(&path[..len as usize]);
|
||||
let name = path.rsplit('\\').next().unwrap_or(&path);
|
||||
Some(format!("{name}+{:#x}", address - module as usize))
|
||||
}
|
||||
@@ -11,25 +11,34 @@
|
||||
//! none of its code and resolves none of its imports;
|
||||
//! 2. load that copy as a real module (debuggers, profilers, crash dumps
|
||||
//! and stack walks all see it); this step is Windows-only;
|
||||
//! 3. bind every import ourselves through an [`ImportResolver`], our
|
||||
//! runtime (`victory-hle`) or the host, and route anything unresolved
|
||||
//! to a generated stub that reports exactly what was called;
|
||||
//! 4. run TLS callbacks and the entry point on a thread with the stack size
|
||||
//! the image asks for.
|
||||
//! 3. map the DLLs the title ships beside it the same way
|
||||
//! (`load_title_dlls`);
|
||||
//! 4. bind every import ourselves through an [`ImportResolver`], our
|
||||
//! runtime (`victory-hle`), the host or the title's DLLs, and route
|
||||
//! anything unresolved to a generated stub that reports exactly what
|
||||
//! was called;
|
||||
//! 5. initialise the title's DLLs, then run TLS callbacks and the entry
|
||||
//! point on a thread with the stack size the image asks for.
|
||||
|
||||
#[cfg(windows)]
|
||||
mod crash;
|
||||
pub mod prepare;
|
||||
pub mod resolve;
|
||||
#[cfg(windows)]
|
||||
mod thunks;
|
||||
#[cfg(windows)]
|
||||
mod tls;
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
|
||||
#[cfg(windows)]
|
||||
pub use crash::{locate, report_crashes};
|
||||
pub use prepare::{PrepareError, PreparedImage, prepare};
|
||||
pub use resolve::{ImportResolver, Provenance, Resolution};
|
||||
#[cfg(windows)]
|
||||
pub use thunks::{UnimplementedPolicy, unimplemented_call_count};
|
||||
#[cfg(windows)]
|
||||
pub use windows::{BindReport, LoadedImage, MissingImport, load};
|
||||
pub use windows::{BindReport, LoadedImage, MissingImport, WithTitleDlls, load, load_title_dlls};
|
||||
|
||||
/// `DLL_PROCESS_ATTACH`, for TLS callbacks.
|
||||
pub const DLL_PROCESS_ATTACH: u32 = 1;
|
||||
@@ -10,6 +10,8 @@ pub enum Provenance {
|
||||
/// The host's own implementation (e.g. Windows API sets that behave the
|
||||
/// same on console and PC).
|
||||
Host,
|
||||
/// A DLL the title ships, mapped like the executable.
|
||||
Title,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
//! Static TLS of an executable mapped as a DLL.
|
||||
//!
|
||||
//! An exe always gets TLS index 0, so title code reaches its thread-local
|
||||
//! block as `mov r64, gs:[0x58]` (the thread's TLS array) followed by
|
||||
//! `[r64]`, without reading `_tls_index`. Mapped as a DLL, the image gets
|
||||
//! another index. Every such load is turned into a call to a thunk that
|
||||
//! yields `&array[index]` instead, and the image's `_tls_index` (which CRT
|
||||
//! code does read, and adds to the array pointer) is set to 0.
|
||||
|
||||
use std::ffi::c_void;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use victory_pe::ImageInfo;
|
||||
use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache;
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_READWRITE,
|
||||
VirtualAlloc, VirtualProtect,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||
|
||||
const SCN_MEM_EXECUTE: u32 = 0x2000_0000;
|
||||
const TLS64_ADDRESS_OF_INDEX: usize = 16;
|
||||
/// `mov r64, gs:[0x58]` is `65 REX 8B ModRM 25 58 00 00 00`.
|
||||
const LOAD_LEN: usize = 9;
|
||||
const THUNK_SIZE: usize = 32;
|
||||
|
||||
/// Redirects the image's TLS-array loads if the OS gave it an index other
|
||||
/// than 0. Returns the number of loads patched.
|
||||
///
|
||||
/// # Safety
|
||||
/// `base` is the image `info` describes, mapped and not yet running.
|
||||
pub(crate) unsafe fn redirect(base: usize, info: &ImageInfo) -> Result<usize> {
|
||||
let Some(tls) = &info.tls else { return Ok(0) };
|
||||
// SAFETY: the TLS directory and the index it points to are in the image;
|
||||
// the OS relocated the pointer and wrote the index.
|
||||
let index_at = unsafe {
|
||||
((base + tls.directory_rva as usize + TLS64_ADDRESS_OF_INDEX) as *const usize).read()
|
||||
} as *mut u32;
|
||||
// SAFETY: as above.
|
||||
let index = unsafe { index_at.read() };
|
||||
if index == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let thunks = thunks(near(base, info.size_of_image as usize)?, index)?;
|
||||
let mut patched = 0;
|
||||
for section in info
|
||||
.sections
|
||||
.iter()
|
||||
.filter(|s| s.characteristics & SCN_MEM_EXECUTE != 0)
|
||||
{
|
||||
let start = base + section.rva as usize;
|
||||
let len = section.virtual_size as usize;
|
||||
let mut old = 0;
|
||||
// SAFETY: the section is part of the mapped image.
|
||||
if unsafe { VirtualProtect(start as _, len, PAGE_EXECUTE_READWRITE, &mut old) } == 0 {
|
||||
bail!(
|
||||
"VirtualProtect(code) failed: {}",
|
||||
std::io::Error::last_os_error()
|
||||
);
|
||||
}
|
||||
// SAFETY: writable now, and no title code runs yet.
|
||||
let code = unsafe { std::slice::from_raw_parts_mut(start as *mut u8, len) };
|
||||
patched += patch(code, start, thunks);
|
||||
// SAFETY: restoring the protection we changed; flushing our own code.
|
||||
unsafe {
|
||||
VirtualProtect(start as _, len, old, &mut old);
|
||||
FlushInstructionCache(GetCurrentProcess(), start as _, len);
|
||||
}
|
||||
}
|
||||
// SAFETY: see `index_at`; `.data` is writable.
|
||||
unsafe { index_at.write(0) };
|
||||
tracing::info!(index, patched, "static TLS redirected");
|
||||
Ok(patched)
|
||||
}
|
||||
|
||||
/// Rewrites each `mov r64, gs:[0x58]` in `code` (at address `at`) as
|
||||
/// `call thunks[r]; nop4`. `thunks` must be within 2 GiB of `code`.
|
||||
fn patch(code: &mut [u8], at: usize, thunks: usize) -> usize {
|
||||
let mut count = 0;
|
||||
let mut i = 0;
|
||||
while i + LOAD_LEN <= code.len() {
|
||||
let c = &code[i..i + LOAD_LEN];
|
||||
let rex = c[1];
|
||||
let reg = usize::from((c[3] >> 3) & 7) | if rex & 4 != 0 { 8 } else { 0 };
|
||||
// shortcut: a byte match, not a decode; a false hit inside other
|
||||
// bytes is unlikely at 9 specific bytes. Decode .text if one shows.
|
||||
if c[0] == 0x65
|
||||
&& (rex == 0x48 || rex == 0x4C)
|
||||
&& c[2] == 0x8B
|
||||
&& c[3] & 0xC7 == 0x04
|
||||
&& c[4..] == [0x25, 0x58, 0, 0, 0]
|
||||
&& reg != 4
|
||||
{
|
||||
let rel = (thunks + reg * THUNK_SIZE) as i64 - (at + i + 5) as i64;
|
||||
code[i] = 0xE8;
|
||||
code[i + 1..i + 5].copy_from_slice(&(rel as i32).to_le_bytes());
|
||||
code[i + 5..i + 9].copy_from_slice(&[0x0F, 0x1F, 0x40, 0x00]);
|
||||
count += 1;
|
||||
i += LOAD_LEN;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
/// Fills `block` with one thunk per register: `mov r, gs:[0x58];
|
||||
/// lea r, [r + index * 8]; ret` (flags untouched, like the load it replaces).
|
||||
fn thunks(block: *mut u8, index: u32) -> Result<usize> {
|
||||
let disp = (index * 8).to_le_bytes();
|
||||
for reg in 0..16u8 {
|
||||
let (r, low) = (reg >> 3, reg & 7);
|
||||
let mut code = vec![0x65, 0x48 | r << 2, 0x8B, low << 3 | 4, 0x25, 0x58, 0, 0, 0];
|
||||
code.extend([0x48 | r << 2 | r, 0x8D, 0x80 | low << 3 | low]);
|
||||
if low == 4 {
|
||||
code.push(0x24); // SIB: [r12 + disp32]
|
||||
}
|
||||
code.extend(disp);
|
||||
code.push(0xC3);
|
||||
// SAFETY: `block` holds 16 thunks and is still writable.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(
|
||||
code.as_ptr(),
|
||||
block.add(usize::from(reg) * THUNK_SIZE),
|
||||
code.len(),
|
||||
)
|
||||
};
|
||||
}
|
||||
let mut old = 0;
|
||||
// SAFETY: `block` is our allocation of one page.
|
||||
if unsafe { VirtualProtect(block as _, 4096, PAGE_EXECUTE_READ, &mut old) } == 0 {
|
||||
bail!(
|
||||
"VirtualProtect(TLS thunks) failed: {}",
|
||||
std::io::Error::last_os_error()
|
||||
);
|
||||
}
|
||||
Ok(block as usize)
|
||||
}
|
||||
|
||||
/// One writable page within `rel32` reach of `[base, base + size)`. Leaked:
|
||||
/// title code calls into it for the life of the process.
|
||||
fn near(base: usize, size: usize) -> Result<*mut u8> {
|
||||
const GRANULE: usize = 0x1_0000;
|
||||
// The search spans 1 GiB each side, so every call site stays in reach.
|
||||
if size >= 1 << 30 {
|
||||
bail!("image too large for TLS thunks within rel32 reach");
|
||||
}
|
||||
let above = (base + size).next_multiple_of(GRANULE);
|
||||
for k in 0..(1usize << 14) {
|
||||
for hint in [
|
||||
base.checked_sub((k + 1) * GRANULE),
|
||||
Some(above + k * GRANULE),
|
||||
] {
|
||||
let Some(hint) = hint else { continue };
|
||||
// SAFETY: a fresh allocation at a free address, or null.
|
||||
let p = unsafe {
|
||||
VirtualAlloc(
|
||||
hint as *const c_void,
|
||||
4096,
|
||||
MEM_COMMIT | MEM_RESERVE,
|
||||
PAGE_READWRITE,
|
||||
)
|
||||
};
|
||||
if !p.is_null() {
|
||||
return Ok(p.cast());
|
||||
}
|
||||
}
|
||||
}
|
||||
bail!("no free page near the image for TLS thunks")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Reads the thread's TLS array pointer the way title code does.
|
||||
fn tls_array() -> usize {
|
||||
let array: usize;
|
||||
// SAFETY: reads TEB.ThreadLocalStoragePointer.
|
||||
unsafe { std::arch::asm!("mov {}, gs:[0x58]", out(reg) array) };
|
||||
array
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loads_become_calls_that_yield_the_title_slot() {
|
||||
let page = near(tls_array as *const () as usize, 0).unwrap();
|
||||
let thunks = thunks(near(page as usize, 4096).unwrap(), 3).unwrap();
|
||||
// (before the load, REX, ModRM, after the load): each case returns
|
||||
// the loaded register in rax; r12 is saved, being callee-saved.
|
||||
let cases: [(&[u8], u8, u8, &[u8]); 3] = [
|
||||
(&[], 0x48, 0x04, &[0xC3]), // rax
|
||||
(&[], 0x4C, 0x04, &[0x4C, 0x89, 0xC0, 0xC3]), // r8
|
||||
(
|
||||
&[0x41, 0x54],
|
||||
0x4C,
|
||||
0x24,
|
||||
&[0x4C, 0x89, 0xE0, 0x41, 0x5C, 0xC3],
|
||||
), // r12
|
||||
];
|
||||
for (before, rex, modrm, after) in cases {
|
||||
let mut code = before.to_vec();
|
||||
code.extend([0x65, rex, 0x8B, modrm, 0x25, 0x58, 0, 0, 0]);
|
||||
code.extend(after);
|
||||
// SAFETY: the page is ours and writable.
|
||||
let bytes = unsafe { std::slice::from_raw_parts_mut(page, code.len()) };
|
||||
bytes.copy_from_slice(&code);
|
||||
assert_eq!(patch(bytes, page as usize, thunks), 1);
|
||||
let mut old = 0;
|
||||
// SAFETY: our page, made executable to run the patched code.
|
||||
unsafe { VirtualProtect(page as _, 4096, PAGE_EXECUTE_READ, &mut old) };
|
||||
// SAFETY: the page holds the patched load and a return.
|
||||
let f: extern "system" fn() -> usize = unsafe { std::mem::transmute(page) };
|
||||
assert_eq!(f(), tls_array() + 3 * 8, "REX {rex:#x} ModRM {modrm:#x}");
|
||||
// SAFETY: our page again.
|
||||
unsafe { VirtualProtect(page as _, 4096, PAGE_READWRITE, &mut old) };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
//! Loading a prepared image as a real Windows module and binding it.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::ffi::{CString, c_void};
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
@@ -12,7 +14,7 @@ use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryExW};
|
||||
use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect};
|
||||
|
||||
use crate::thunks::{ImportSite, ThunkBlock, UnimplementedPolicy};
|
||||
use crate::{DLL_PROCESS_ATTACH, ImportResolver, PreparedImage, Provenance, Resolution};
|
||||
use crate::{DLL_PROCESS_ATTACH, ImportResolver, PreparedImage, Provenance, Resolution, prepare};
|
||||
|
||||
/// A title image mapped into this process.
|
||||
#[derive(Debug)]
|
||||
@@ -39,6 +41,7 @@ pub struct MissingImport {
|
||||
pub struct BindReport {
|
||||
pub hle: usize,
|
||||
pub host: usize,
|
||||
pub title: usize,
|
||||
pub missing: Vec<MissingImport>,
|
||||
}
|
||||
|
||||
@@ -72,6 +75,11 @@ pub fn load(prepared: &PreparedImage, dir: &Path) -> Result<LoadedImage> {
|
||||
path,
|
||||
info: prepared.info.clone(),
|
||||
};
|
||||
// A DLL indexes its TLS properly; only an exe assumes index 0.
|
||||
if !loaded.info.is_dll() {
|
||||
// SAFETY: just mapped, and no title code has run.
|
||||
unsafe { crate::tls::redirect(loaded.base(), &loaded.info) }?;
|
||||
}
|
||||
tracing::info!(
|
||||
base = format_args!("{:#x}", loaded.base()),
|
||||
preferred = format_args!("{:#x}", loaded.info.image_base),
|
||||
@@ -81,6 +89,67 @@ pub fn load(prepared: &PreparedImage, dir: &Path) -> Result<LoadedImage> {
|
||||
Ok(loaded)
|
||||
}
|
||||
|
||||
/// Maps the DLLs the title ships in `title_dir` that `main` imports,
|
||||
/// directly or through each other, in initialisation order (dependencies
|
||||
/// first). Only DLL names `wanted` accepts are considered, so DLLs the host
|
||||
/// or our runtime provide stay with them. Imports are not bound.
|
||||
pub fn load_title_dlls(
|
||||
main: &ImageInfo,
|
||||
title_dir: &Path,
|
||||
cache_dir: &Path,
|
||||
wanted: &dyn Fn(&str) -> bool,
|
||||
) -> Result<Vec<(String, LoadedImage)>> {
|
||||
fn visit(
|
||||
info: &ImageInfo,
|
||||
dirs: (&Path, &Path),
|
||||
wanted: &dyn Fn(&str) -> bool,
|
||||
seen: &mut HashSet<String>,
|
||||
loaded: &mut Vec<(String, LoadedImage)>,
|
||||
) -> Result<()> {
|
||||
for module in info.imports.iter().chain(&info.delay_imports) {
|
||||
let name = module.dll.to_ascii_lowercase();
|
||||
let path = dirs.0.join(&name);
|
||||
if !seen.insert(name.clone()) || !wanted(&name) || !path.is_file() {
|
||||
continue;
|
||||
}
|
||||
let original =
|
||||
std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?;
|
||||
let image = load(&prepare(&original)?, dirs.1)
|
||||
.with_context(|| format!("loading {}", path.display()))?;
|
||||
visit(&image.info, dirs, wanted, seen, loaded)?;
|
||||
loaded.push((name, image));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
let mut loaded = Vec::new();
|
||||
let dirs = (title_dir, cache_dir);
|
||||
visit(main, dirs, wanted, &mut HashSet::new(), &mut loaded)?;
|
||||
Ok(loaded)
|
||||
}
|
||||
|
||||
/// Resolves through `inner`, then through the exports of the title's DLLs.
|
||||
pub struct WithTitleDlls<'a> {
|
||||
pub inner: &'a dyn ImportResolver,
|
||||
pub dlls: &'a [(String, LoadedImage)],
|
||||
}
|
||||
|
||||
impl ImportResolver for WithTitleDlls<'_> {
|
||||
fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution {
|
||||
let found = self.inner.resolve(dll, symbol);
|
||||
if found != Resolution::Missing {
|
||||
return found;
|
||||
}
|
||||
self.dlls
|
||||
.iter()
|
||||
.find(|(name, _)| name.eq_ignore_ascii_case(dll))
|
||||
.and_then(|(_, image)| image.export_symbol(symbol))
|
||||
.map_or(Resolution::Missing, |address| Resolution::Found {
|
||||
address,
|
||||
provenance: Provenance::Title,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn write_if_changed(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
if std::fs::read(path).is_ok_and(|existing| existing == bytes) {
|
||||
return Ok(());
|
||||
@@ -109,6 +178,16 @@ impl LoadedImage {
|
||||
.map(|f| f as *const () as usize)
|
||||
}
|
||||
|
||||
/// Address of an export, by name or ordinal.
|
||||
pub fn export_symbol(&self, symbol: &ImportSymbol) -> Option<usize> {
|
||||
match symbol {
|
||||
ImportSymbol::Name { name, .. } => self.export(name),
|
||||
// SAFETY: MAKEINTRESOURCE-style ordinal lookup on a valid module.
|
||||
ImportSymbol::Ordinal(o) => unsafe { GetProcAddress(self.module, *o as usize as _) }
|
||||
.map(|f| f as *const () as usize),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fills every IAT slot of the image.
|
||||
///
|
||||
/// Each import goes to `resolver`; whatever it cannot resolve gets an
|
||||
@@ -134,6 +213,7 @@ impl LoadedImage {
|
||||
match provenance {
|
||||
Provenance::Hle => report.hle += 1,
|
||||
Provenance::Host => report.host += 1,
|
||||
Provenance::Title => report.title += 1,
|
||||
}
|
||||
slots.push((entry.iat_slot_rva, address));
|
||||
}
|
||||
@@ -209,13 +289,40 @@ impl LoadedImage {
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the title: on a new thread with the stack size from the image
|
||||
/// header, runs the TLS callbacks (`DLL_PROCESS_ATTACH`), then the
|
||||
/// original entry point. Returns the thread so the caller can join it.
|
||||
/// Initialises a DLL as the Windows loader would: its TLS callbacks,
|
||||
/// then `DllMain(DLL_PROCESS_ATTACH)`.
|
||||
///
|
||||
/// # Safety
|
||||
/// Runs title code. Imports must be bound first.
|
||||
pub unsafe fn spawn_main(self: std::sync::Arc<Self>) -> Result<std::thread::JoinHandle<u32>> {
|
||||
/// Runs title code. Imports must be bound first, and the DLLs this one
|
||||
/// depends on attached.
|
||||
pub unsafe fn attach(&self) -> Result<()> {
|
||||
// SAFETY: forwarded from the caller.
|
||||
unsafe { self.run_tls_callbacks(DLL_PROCESS_ATTACH) };
|
||||
if self.info.entry_rva == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
type DllMain = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32;
|
||||
// SAFETY: the entry RVA came from the original image header.
|
||||
let main: DllMain =
|
||||
unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) };
|
||||
// SAFETY: forwarded from the caller.
|
||||
if unsafe { main(self.module, DLL_PROCESS_ATTACH, std::ptr::null_mut()) } == 0 {
|
||||
bail!("DllMain returned FALSE");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Starts the title: on a new thread with the stack size from the image
|
||||
/// header, attaches `dlls` in order (see [`Self::attach`]), runs the
|
||||
/// image's TLS callbacks (`DLL_PROCESS_ATTACH`), then its original entry
|
||||
/// point. Returns the thread so the caller can join it.
|
||||
///
|
||||
/// # Safety
|
||||
/// Runs title code. Imports of the image and of `dlls` must be bound.
|
||||
pub unsafe fn spawn_main(
|
||||
self: Arc<Self>,
|
||||
dlls: Vec<(String, LoadedImage)>,
|
||||
) -> Result<std::thread::JoinHandle<Result<u32>>> {
|
||||
if self.info.entry_rva == 0 {
|
||||
bail!("image has no entry point");
|
||||
}
|
||||
@@ -226,6 +333,10 @@ impl LoadedImage {
|
||||
.name("title-main".into())
|
||||
.stack_size(stack)
|
||||
.spawn(move || {
|
||||
for (name, dll) in &dlls {
|
||||
// SAFETY: forwarded from the caller of `spawn_main`.
|
||||
unsafe { dll.attach() }.with_context(|| format!("attaching {name}"))?;
|
||||
}
|
||||
// SAFETY: forwarded from the caller of `spawn_main`.
|
||||
unsafe { self.run_tls_callbacks(DLL_PROCESS_ATTACH) };
|
||||
type Entry = unsafe extern "system" fn(*mut c_void) -> u32;
|
||||
@@ -233,7 +344,7 @@ impl LoadedImage {
|
||||
let entry: Entry =
|
||||
unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) };
|
||||
// SAFETY: forwarded from the caller of `spawn_main`.
|
||||
unsafe { entry(std::ptr::null_mut()) }
|
||||
Ok(unsafe { entry(std::ptr::null_mut()) })
|
||||
})
|
||||
.context("spawning title main thread")
|
||||
}
|
||||
|
||||
@@ -7,7 +7,8 @@ use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use victory_loader::{
|
||||
ImportResolver, Provenance, Resolution, UnimplementedPolicy, prepare, unimplemented_call_count,
|
||||
ImportResolver, Provenance, Resolution, UnimplementedPolicy, WithTitleDlls, prepare,
|
||||
unimplemented_call_count,
|
||||
};
|
||||
use victory_pe::ImportSymbol;
|
||||
use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA};
|
||||
@@ -120,9 +121,33 @@ fn loads_binds_and_calls_probe() {
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let image = victory_loader::load(&prepared, dir.path()).unwrap();
|
||||
|
||||
// The "title" ships victory-probe-title.dll: any real DLL will do.
|
||||
let title_dir = tempfile::tempdir().unwrap();
|
||||
std::fs::copy(
|
||||
r"C:\Windows\System32\version.dll",
|
||||
title_dir.path().join("victory-probe-title.dll"),
|
||||
)
|
||||
.unwrap();
|
||||
let dlls =
|
||||
victory_loader::load_title_dlls(image.info(), title_dir.path(), dir.path(), &|_| true)
|
||||
.unwrap();
|
||||
let names: Vec<_> = dlls.iter().map(|(n, _)| n.as_str()).collect();
|
||||
assert_eq!(names, ["victory-probe-title.dll"]);
|
||||
let resolver = WithTitleDlls {
|
||||
inner: &TestResolver,
|
||||
dlls: &dlls,
|
||||
};
|
||||
for (_, dll) in &dlls {
|
||||
dll.bind_imports(&resolver, UnimplementedPolicy::ReturnZero)
|
||||
.unwrap();
|
||||
// SAFETY: its imports are bound, and it depends on no other title DLL.
|
||||
unsafe { dll.attach() }.unwrap();
|
||||
}
|
||||
let report = image
|
||||
.bind_imports(&TestResolver, UnimplementedPolicy::ReturnZero)
|
||||
.bind_imports(&resolver, UnimplementedPolicy::ReturnZero)
|
||||
.unwrap();
|
||||
assert_eq!(report.title, 1);
|
||||
|
||||
assert_eq!(report.hle, 3);
|
||||
assert!(report.host > 0);
|
||||
@@ -142,6 +167,9 @@ fn loads_binds_and_calls_probe() {
|
||||
let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_pid"));
|
||||
assert_eq!(f(), std::process::id(), "host API must pass through");
|
||||
|
||||
let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_title"));
|
||||
assert_ne!(f(), 0, "title DLL export must be bound");
|
||||
|
||||
let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_delayed"));
|
||||
assert_eq!(f(), 4242, "delay-loaded API must be bound");
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ mod fields;
|
||||
mod opcodes;
|
||||
mod sp3;
|
||||
|
||||
pub use fields::{Cache, Dpp, Fields, Operand, Sdwa, Valu};
|
||||
pub use fields::{Cache, Dpp, Fields, NULL, Operand, Sdwa, Valu};
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -76,12 +76,9 @@ pub fn decode(code: &[u8]) -> Result<Vec<Instruction>, ShaderError> {
|
||||
while !found.contains_key(&offset) {
|
||||
let inst = instruction(code, offset)?;
|
||||
let next = offset + 4 * inst.words.len();
|
||||
let flow = match flow(&inst, next, code.len())? {
|
||||
Flow::Stop if inst.name() == Some("s_setpc_b64") => {
|
||||
far_jump(&found, &inst, code.len())?.map_or(Flow::Stop, Flow::Jump)
|
||||
}
|
||||
flow => flow,
|
||||
};
|
||||
let flow = control(&inst, code.len(), |at| {
|
||||
found.range(..at).next_back().map(|(_, i)| i)
|
||||
})?;
|
||||
found.insert(offset, inst);
|
||||
match flow {
|
||||
Flow::Next => offset = next,
|
||||
@@ -104,13 +101,32 @@ pub fn decode(code: &[u8]) -> Result<Vec<Instruction>, ShaderError> {
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
enum Flow {
|
||||
/// Where execution goes after an instruction.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Flow {
|
||||
Next,
|
||||
/// End of the program, or an indirect jump that is not a far jump.
|
||||
Stop,
|
||||
Jump(usize),
|
||||
/// Conditional: to the target or the next instruction.
|
||||
Branch(usize),
|
||||
}
|
||||
|
||||
/// Control flow after `inst`, resolving far jumps. `before(at)` returns the
|
||||
/// decoded instruction with the highest offset below `at`, if any.
|
||||
pub(crate) fn control<'a>(
|
||||
inst: &Instruction,
|
||||
len: usize,
|
||||
before: impl Fn(usize) -> Option<&'a Instruction>,
|
||||
) -> Result<Flow, ShaderError> {
|
||||
Ok(match flow(inst, inst.offset + 4 * inst.words.len(), len)? {
|
||||
Flow::Stop if inst.name() == Some("s_setpc_b64") => {
|
||||
far_jump(before, inst, len)?.map_or(Flow::Stop, Flow::Jump)
|
||||
}
|
||||
flow => flow,
|
||||
})
|
||||
}
|
||||
|
||||
fn flow(inst: &Instruction, next: usize, len: usize) -> Result<Flow, ShaderError> {
|
||||
let target = || {
|
||||
let delta = 4 * i64::from(inst.words[0] as u16 as i16);
|
||||
@@ -138,8 +154,8 @@ fn flow(inst: &Instruction, next: usize, len: usize) -> Result<Flow, ShaderError
|
||||
/// into s(n+1), `s_setpc_b64 s[n:n+1]`, looking back over the straight-line
|
||||
/// run just decoded. Any other `s_setpc_b64` (e.g. a handover to the next
|
||||
/// merged stage through registers) gives `None`.
|
||||
fn far_jump(
|
||||
found: &BTreeMap<usize, Instruction>,
|
||||
fn far_jump<'a>(
|
||||
before: impl Fn(usize) -> Option<&'a Instruction>,
|
||||
setpc: &Instruction,
|
||||
len: usize,
|
||||
) -> Result<Option<usize>, ShaderError> {
|
||||
@@ -147,7 +163,7 @@ fn far_jump(
|
||||
let mut delta = None;
|
||||
let mut at = setpc.offset;
|
||||
for _ in 0..4 {
|
||||
let Some((_, prev)) = found.range(..at).next_back() else {
|
||||
let Some(prev) = before(at) else {
|
||||
break;
|
||||
};
|
||||
if prev.offset + 4 * prev.words.len() != at {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -9,7 +9,9 @@
|
||||
pub mod dxbc;
|
||||
pub mod dxil;
|
||||
pub mod gfx10;
|
||||
pub mod ir;
|
||||
pub mod native;
|
||||
pub mod structure;
|
||||
|
||||
pub use dxbc::{Container, FourCC, Part};
|
||||
pub use dxil::{DxilProgram, ShaderKind, XboxExtras};
|
||||
@@ -23,4 +25,7 @@ pub enum ShaderError {
|
||||
Malformed(&'static str),
|
||||
#[error("GFX10 code at {offset:#x}: {reason}")]
|
||||
Isa { offset: usize, reason: &'static str },
|
||||
/// Valid code the translator cannot handle yet: an opcode name or a construct.
|
||||
#[error("GFX10 code at {offset:#x}: {what} is not supported")]
|
||||
Unsupported { offset: usize, what: &'static str },
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
//! mesh 0x48, compute 0x60; unused ones are 0xDEADBEEF_DEADBEEF
|
||||
//! record +0x00 u64 code offset, +0x08 u64 code size (payload-relative),
|
||||
//! +0x14 u32 flags: bit 5 wave32 (else wave64)
|
||||
//! +0x50 u32 bits 0-9 VGPRs used, bits 20-27 SGPRs used
|
||||
//! ```
|
||||
//!
|
||||
//! Other kinds seen: 0x07 program header + bitcode (or a stub when stripped),
|
||||
@@ -47,9 +48,10 @@ const SLOTS: [(HwStage, usize); 8] = [
|
||||
(HwStage::Cs, 0x60),
|
||||
];
|
||||
const ABSENT: u64 = 0xDEAD_BEEF_DEAD_BEEF;
|
||||
const RECORD_SIZE: u64 = 0x18;
|
||||
const RECORD_SIZE: u64 = 0x54;
|
||||
const RECORD_FLAGS: usize = 0x14;
|
||||
const FLAG_WAVE32: u32 = 1 << 5;
|
||||
const RECORD_REGS: usize = 0x50;
|
||||
/// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes.
|
||||
const MAX_UNPACKED: u64 = 16 << 20;
|
||||
|
||||
@@ -72,6 +74,8 @@ pub struct NativeProgram {
|
||||
pub stage: HwStage,
|
||||
/// Runs as 64 lanes per wave (else 32); sizes lane masks.
|
||||
pub wave64: bool,
|
||||
/// VGPRs the program uses (v0 up to this), the bound of indexed access.
|
||||
pub vgprs: u16,
|
||||
/// GFX10 machine code.
|
||||
pub code: Vec<u8>,
|
||||
}
|
||||
@@ -145,9 +149,14 @@ fn programs(fssm: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> {
|
||||
bytes(payload, record, RECORD_SIZE).ok_or(Malformed("FSSM record out of bounds"))?;
|
||||
let code = bytes(payload, u64_at(record, 0)?, u64_at(record, 8)?)
|
||||
.ok_or(Malformed("native code out of bounds"))?;
|
||||
let vgprs = (u32_at(record, RECORD_REGS)? & 0x3FF) as u16;
|
||||
if vgprs > 256 {
|
||||
return Err(Malformed("implausible VGPR count"));
|
||||
}
|
||||
out.push(NativeProgram {
|
||||
stage,
|
||||
wave64: u32_at(record, RECORD_FLAGS)? & FLAG_WAVE32 == 0,
|
||||
vgprs,
|
||||
code: code.to_vec(),
|
||||
});
|
||||
}
|
||||
@@ -166,6 +175,7 @@ mod tests {
|
||||
|
||||
const VS_CODE: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
|
||||
const PS_CODE: [u8; 4] = [9, 10, 11, 12];
|
||||
const VGPRS: u32 = 28;
|
||||
|
||||
fn slot(stage: HwStage) -> usize {
|
||||
SLOTS.iter().find(|s| s.0 == stage).unwrap().1
|
||||
@@ -187,6 +197,8 @@ mod tests {
|
||||
let flags = if stage == HwStage::Ps { FLAG_WAVE32 } else { 0 };
|
||||
payload.extend_from_slice(&[0; 4]);
|
||||
payload.extend_from_slice(&flags.to_le_bytes());
|
||||
payload.resize(record as usize + RECORD_REGS, 0);
|
||||
payload.extend_from_slice(&(VGPRS | 31 << 20).to_le_bytes());
|
||||
payload.extend_from_slice(code);
|
||||
}
|
||||
let mut out = b"FSSM".to_vec();
|
||||
@@ -236,11 +248,13 @@ mod tests {
|
||||
NativeProgram {
|
||||
stage: HwStage::Vs,
|
||||
wave64: true,
|
||||
vgprs: 28,
|
||||
code: VS_CODE.to_vec()
|
||||
},
|
||||
NativeProgram {
|
||||
stage: HwStage::Ps,
|
||||
wave64: false,
|
||||
vgprs: 28,
|
||||
code: PS_CODE.to_vec()
|
||||
},
|
||||
]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user