Run Grand Theft Auto VI from first boot into the world

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

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

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

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

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

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

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

No files matched your search

+634 -35
View File
@@ -8,14 +8,18 @@
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::alloc::{Layout, alloc, dealloc};
use std::collections::{BTreeMap, HashMap};
use std::ffi::c_void;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, LazyLock, Mutex, MutexGuard};
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::Memory::{
MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, MEM_RELEASE, MEM_RESERVE,
MEMORY_BASIC_INFORMATION, MemExtendedParameterAddressRequirements, PAGE_NOACCESS,
PAGE_READWRITE, VirtualAlloc2, VirtualFree, VirtualQueryEx,
CreateFileMappingW, MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER,
MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE,
MEM_RESERVE_PLACEHOLDER, MEMORY_BASIC_INFORMATION, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile3,
MemExtendedParameterAddressRequirements, PAGE_NOACCESS, PAGE_READWRITE, SEC_RESERVE,
UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQueryEx,
};
use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
@@ -24,11 +28,6 @@ use windows_sys::core::BOOL;
use crate::{HleModule, hle_export};
const MIB: usize = 1 << 20;
const GIB: usize = 1 << 30;
/// Title memory of an Xbox Series X in the advanced mode: 10 GiB of
/// GPU-optimal and 3.5 GiB of standard memory.
const GPU_OPTIMAL_LIMIT: usize = 10 * GIB;
const STANDARD_LIMIT: usize = 7 * GIB / 2;
/// Standard memory the title has handed to the system.
static TRANSFERRED: AtomicUsize = AtomicUsize::new(0);
@@ -39,6 +38,7 @@ static TRANSFERRED: AtomicUsize = AtomicUsize::new(0);
const PAGES_2M: u32 = 0x2000_0000;
/// With `PAGES_2M`: 64 KiB pages; the host reads it as AWE memory.
const PAGES_64K_BIT: u32 = 0x40_0000;
const PAGES_64K: u32 = PAGES_2M | PAGES_64K_BIT;
/// The host's protection constants and `PAGE_GUARD`. Above them the console
/// adds GPU access bits (0x800-0x40000). Write-combining and uncached are
/// dropped too: our GPU side reads this memory through the CPU.
@@ -47,16 +47,23 @@ const HOST_PROTECTION: u32 = 0x1ff;
const GRAPHICS: u64 = 3;
/// XMem flag bit of 32-bit graphics memory.
const ADDRESS_32BIT: u64 = 4;
/// The host's write watching (not in windows-sys' memory module).
const MEM_WRITE_WATCH: u32 = 0x20_0000;
/// The highest address XMem `flags` allow, 0 for no limit: 32 bits, or
/// 46 down to 40 bits from the field at bit 12.
fn highest_address(flags: u64) -> usize {
/// The addresses XMem `flags` allow, first and last: the low 4 GiB for
/// 32-bit memory; else from 4 GiB (kept for 32-bit requests, which the
/// title's big pools would otherwise crowd out) up to 46 down to 40 bits
/// from the field at bit 12, or 40 bits without one: the console keeps
/// title memory there, and its ray-tracing structures must be (Grand Theft
/// Auto VI's BVH builder refuses one above; the title asks for its GPU heap
/// with no field). Decision 0001.
fn address_range(flags: u64) -> (usize, usize) {
let bits = match (flags & ADDRESS_32BIT, flags >> 12 & 7) {
(0, 0) => return 0,
(0, 0) => 40,
(0, field) => 47 - field,
_ => 32,
_ => return (0, u32::MAX as usize),
};
(1 << bits) - 1
(1 << 32, (1 << bits) - 1)
}
pub extern "system" fn XMemVirtualAlloc(
@@ -66,42 +73,78 @@ pub extern "system" fn XMemVirtualAlloc(
flags: u64,
protect: u32,
) -> *mut c_void {
let (lowest, highest) = address_range(flags);
let mut requirements = MEM_ADDRESS_REQUIREMENTS {
HighestEndingAddress: highest_address(flags) as *mut c_void,
LowestStartingAddress: lowest as *mut c_void,
HighestEndingAddress: highest as *mut c_void,
Alignment: if kind & (PAGES_2M | PAGES_64K_BIT) == PAGES_2M {
2 * MIB
} else {
0
},
..Default::default()
};
let mut kind = kind & !(PAGES_2M | PAGES_64K_BIT);
let protect = match protect & HOST_PROTECTION {
let mut protect = match protect & HOST_PROTECTION {
0 => PAGE_NOACCESS,
p => p,
};
// A reservation of 64 KiB pages takes physical pages later
// (`XMemMapPhysicalPages`); on the host only a placeholder can.
// shortcut: committing part of such a reservation later would fail
// (Grand Theft Auto VI's 23 calls never do); replace that part of the
// placeholder then.
let placeholder = kind & PAGES_64K == PAGES_64K && kind & MEM_COMMIT == 0;
if placeholder {
if kind & MEM_REPLACE_PLACEHOLDER != 0 {
// Part of a placeholder the title split: it stays one.
return base;
}
protect = PAGE_NOACCESS;
}
let mut kind = kind & !(PAGES_2M | PAGES_64K_BIT);
if placeholder {
kind |= MEM_RESERVE | MEM_RESERVE_PLACEHOLDER;
}
let mut parameter = MEM_EXTENDED_PARAMETER::default();
parameter.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64;
parameter.Anonymous2.Pointer = (&raw mut requirements).cast();
// Address requirements apply to reservations at an address of our choice.
let constrained = base.is_null()
&& (!requirements.HighestEndingAddress.is_null() || requirements.Alignment != 0);
let constrained = base.is_null();
if constrained {
kind |= MEM_RESERVE;
// The GPU side copies only the pages the title wrote since its last
// copy (`victory_gpu`, decision 0007); placeholders cannot be
// watched (their physical-page views are copied whole).
if kind & MEM_RESERVE_PLACEHOLDER == 0 {
kind |= MEM_WRITE_WATCH;
}
}
// SAFETY: the title's own arguments, cleaned of console bits; the
// parameter points at `requirements`, which outlives the call.
unsafe {
let at = unsafe {
VirtualAlloc2(
GetCurrentProcess(),
base,
size,
kind,
protect,
if constrained { &mut parameter } else { std::ptr::null_mut() },
if constrained {
&mut parameter
} else {
std::ptr::null_mut()
},
constrained.into(),
)
};
if base.is_null() {
tracing::debug!(
size,
kind = format_args!("{kind:#x}"),
flags = format_args!("{flags:#x}"),
at = format_args!("{at:p}"),
"XMemVirtualAlloc"
);
}
at
}
/// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the
@@ -115,8 +158,9 @@ pub struct BasicInformation {
}
// shortcut: every committed page reports graphics memory and no tag, since
// all of it is GPU-reachable here; remember the flags of `XMemVirtualAlloc`
// regions if a title tells CPU-only memory apart.
// all of it is GPU-reachable here (Grand Theft Auto VI's BVH builder, the
// only caller, wants graphics memory); remember the flags of
// `XMemVirtualAlloc` regions if a title tells CPU-only memory apart.
pub extern "system" fn XMemVirtualQuery(
process: HANDLE,
address: *const c_void,
@@ -130,7 +174,11 @@ pub extern "system" fn XMemVirtualQuery(
return 0;
}
let info = &mut *out;
info.flags = if info.host.State == MEM_COMMIT { GRAPHICS } else { 0 };
info.flags = if info.host.State == MEM_COMMIT {
GRAPHICS
} else {
0
};
info.tag_code = 0;
info.tag = [0; 4];
}
@@ -151,10 +199,66 @@ fn layout(size: usize, attributes: u64) -> Option<Layout> {
Layout::from_size_align(size.checked_add(align)?, align).ok()
}
/// The title's general allocator, for middleware too.
// shortcut: allocation hooks (`XMemSetAllocationHooks`, or hooks the title
// exports) are not called; no title we have sets them.
type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void;
type FreeRoutine = extern "system" fn(*mut c_void, u64);
/// The allocation and free routines the title's exe exports as
/// `__XMemAllocationHooks__` (Grand Theft Auto VI does): `XMemAlloc` and
/// `XMemFree` call them, for the title's own calls and its middleware's;
/// the `…Default` exports do not.
fn hooks() -> [usize; 2] {
static AT: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
let at = match AT.get() {
Some(&at) => at,
// Looked up once the title is mapped, which is before it runs.
None => match crate::runtime::main_image() {
Some(base) => *AT.get_or_init(|| {
use windows_sys::Win32::System::LibraryLoader::GetProcAddress;
// SAFETY: a mapped image and a NUL-terminated name.
let at = unsafe {
GetProcAddress(base as _, c"__XMemAllocationHooks__".as_ptr().cast())
}
.map_or(0, |f| f as usize);
tracing::info!(found = at != 0, "xmem allocation hooks");
at
}),
None => 0,
},
};
if at == 0 {
return [0; 2];
}
// SAFETY: the export is two routine pointers.
unsafe { (at as *const [usize; 2]).read() }
}
/// The title's general allocator, for middleware too: its hook if it has
/// one, else [`XMemAllocDefault`].
pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void {
match hooks()[0] {
0 => XMemAllocDefault(size, attributes),
hook => {
// SAFETY: the title's own routine of this type.
let alloc: AllocRoutine = unsafe { std::mem::transmute(hook) };
alloc(size, attributes)
}
}
}
/// See [`XMemAlloc`].
pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) {
match hooks()[1] {
0 => XMemFreeDefault(address, attributes),
hook => {
// SAFETY: the title's own routine of this type.
let free: FreeRoutine = unsafe { std::mem::transmute(hook) };
free(address, attributes)
}
}
}
/// The system allocator behind [`XMemAlloc`].
pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_void {
if attributes & ALLOC_32BIT != 0 {
return XMemVirtualAlloc(
std::ptr::null_mut(),
@@ -167,6 +271,10 @@ pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void {
let Some(layout) = layout(size, attributes) else {
return std::ptr::null_mut();
};
// shortcut: the host heap's addresses lie above 2^40, unlike the
// console's; nothing seen builds ray-tracing structures in this memory
// (Grand Theft Auto VI uses its GPU heap). Sub-allocate from a
// reservation below 2^40 if one does.
// SAFETY: the layout has a non-zero size.
let block = unsafe { alloc(layout) };
if block.is_null() {
@@ -183,8 +291,8 @@ pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void {
}
}
/// Frees what [`XMemAlloc`] returned, given the same attributes.
pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) {
/// Frees what [`XMemAllocDefault`] returned, given the same attributes.
pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) {
if address.is_null() {
return;
}
@@ -204,6 +312,383 @@ pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) {
}
}
/// A retail console has no tools memory.
pub extern "system" fn XMemIsToolsMemAvailable() -> BOOL {
0
}
// Physical pages: on the console, 64 KiB frames a title maps into its own
// reservations, at more than one address if it likes. Here each allocation
// is a pagefile-backed section, its pages are 64 KiB slices of it, and a
// mapping is a view of consecutive slices in place of a host placeholder.
const PAGE: usize = 64 << 10;
struct Section(HANDLE);
// SAFETY: a section handle may be used from any thread.
unsafe impl Send for Section {}
// SAFETY: as above.
unsafe impl Sync for Section {}
impl Drop for Section {
fn drop(&mut self) {
// SAFETY: our handle; views keep the section alive on their own.
unsafe { CloseHandle(self.0) };
}
}
/// Where a page lives, or what a view starts with: a section and a page
/// index in it.
#[derive(Clone)]
struct Slice {
section: Arc<Section>,
index: usize,
}
#[derive(Default)]
struct Physical {
next_page: usize,
pages: HashMap<usize, Slice>,
/// Mapped views by address: their length and what they show.
views: BTreeMap<usize, (usize, Slice)>,
}
static PHYSICAL: LazyLock<Mutex<Physical>> = LazyLock::new(|| {
Mutex::new(Physical {
// Page numbers are opaque to titles; 0 stays unused.
next_page: 0x10_0000,
..Default::default()
})
});
fn physical() -> MutexGuard<'static, Physical> {
PHYSICAL.lock().unwrap_or_else(|e| e.into_inner())
}
/// `count` is in and out (pages wanted, pages given); all or nothing here.
pub extern "system" fn XMemAllocatePhysicalPages(
flags: u64,
count: *mut usize,
pages: *mut usize,
) -> BOOL {
if count.is_null() || pages.is_null() {
return 0;
}
// SAFETY: checked non-null.
let n = unsafe { *count };
let Some(size) = n.checked_mul(PAGE).filter(|&s| s > 0) else {
return 0;
};
// A pagefile-backed section of `size` bytes, its pages committed when
// first mapped or written (`commit`): Grand Theft Auto VI asks for 6.1
// GiB at once, which a busy host often cannot commit (error 1450).
// SAFETY: plain section creation.
let handle = unsafe {
CreateFileMappingW(
INVALID_HANDLE_VALUE,
std::ptr::null(),
PAGE_READWRITE | SEC_RESERVE,
(size as u64 >> 32) as u32,
size as u32,
std::ptr::null(),
)
};
if handle.is_null() {
let error = std::io::Error::last_os_error();
tracing::warn!(n, %error, "XMemAllocatePhysicalPages failed");
// SAFETY: checked non-null.
unsafe { count.write(0) };
return 0;
}
tracing::debug!(
n,
flags = format_args!("{flags:#x}"),
"XMemAllocatePhysicalPages"
);
let section = Arc::new(Section(handle));
let mut physical = physical();
let first = physical.next_page;
physical.next_page += n * FRAMES;
for index in 0..n {
let slice = Slice {
section: section.clone(),
index,
};
let number = first + index * FRAMES;
physical.pages.insert(number, slice);
// SAFETY: the title passes room for `n` page numbers.
unsafe { pages.add(index).write(number) };
}
1
}
/// Page numbers count 4 KiB frames, so a 64 KiB page's is a multiple of
/// 16: Grand Theft Auto VI keeps them as 21-bit `number >> 4` and rebuilds
/// them with `<< 4` (128 GiB of pages at most).
const FRAMES: usize = PAGE >> 12;
/// Pages still mapped stay readable through their views until unmapped.
pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> BOOL {
if pages.is_null() {
return 0;
}
let mut physical = physical();
for i in 0..n {
// SAFETY: the title passes `n` page numbers.
physical.pages.remove(&unsafe { *pages.add(i) });
}
1
}
/// Copies `data` into physical pages, from `offset` bytes into the first,
/// whether or not they are mapped anywhere (DirectStorage destinations).
/// False if a page is unknown or the host fails.
pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> bool {
use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile};
let mut done = 0;
while done < data.len() {
let (page, within) = ((offset + done) / PAGE, (offset + done) % PAGE);
let Some(slice) = pages
.get(page)
.and_then(|p| physical().pages.get(p).cloned())
else {
return false;
};
let at = (slice.index * PAGE) as u64;
// SAFETY: one page of a section we own, mapped for the copy only.
let view = unsafe {
MapViewOfFile(
slice.section.0,
FILE_MAP_WRITE,
(at >> 32) as u32,
at as u32,
PAGE,
)
};
if view.Value.is_null() {
return false;
}
if !commit(view.Value as usize, PAGE) {
// SAFETY: our view.
unsafe { UnmapViewOfFile(view) };
return false;
}
let n = (PAGE - within).min(data.len() - done);
// SAFETY: the view holds `PAGE` bytes; `within + n <= PAGE`.
unsafe {
view.Value
.cast::<u8>()
.add(within)
.copy_from_nonoverlapping(data[done..].as_ptr(), n);
UnmapViewOfFile(view);
}
done += n;
}
true
}
/// Maps `n` pages at `address`, in place of what is mapped there; null
/// `pages` unmaps. Returns `address`, or null if a page or the host fails.
pub extern "system" fn XMemMapPhysicalPages(
address: *mut c_void,
n: usize,
pages: *const usize,
) -> *mut c_void {
let base = address as usize;
let mut physical = physical();
unmap(&mut physical, base, n * PAGE);
if pages.is_null() {
return address;
}
// SAFETY: the title passes `n` page numbers.
let pages = unsafe { std::slice::from_raw_parts(pages, n) };
let mut i = 0;
while i < n {
let Some(first) = physical.pages.get(&pages[i]).cloned() else {
tracing::warn!(page = pages[i], "XMemMapPhysicalPages: unknown page");
return std::ptr::null_mut();
};
// One view per run of consecutive slices of one section.
let run = 1 + pages[i + 1..]
.iter()
.zip(1..)
.take_while(|&(page, k)| {
physical.pages.get(page).is_some_and(|s| {
Arc::ptr_eq(&s.section, &first.section) && s.index == first.index + k
})
})
.count();
if !map(&mut physical, base + i * PAGE, run * PAGE, first) {
return std::ptr::null_mut();
}
i += run;
}
address
}
/// One page at each address; null `pages`, or a page number 0, unmaps
/// (Grand Theft Auto VI passes 0 for addresses to clear).
pub extern "system" fn XMemMapPhysicalPagesScatter(
addresses: *const *mut c_void,
n: usize,
pages: *const usize,
) -> BOOL {
if addresses.is_null() {
return 0;
}
for i in 0..n {
// SAFETY: the title passes `n` addresses and, unless null, `n` pages.
let (address, page) = unsafe {
(
*addresses.add(i),
if pages.is_null() || *pages.add(i) == 0 {
std::ptr::null()
} else {
pages.add(i)
},
)
};
if XMemMapPhysicalPages(address, 1, page).is_null() {
return 0;
}
}
1
}
/// Maps the physical pages shown at `[from, from + len)` at `to` as well,
/// in place of what `to` shows; `from` 0 unmaps. The GPU's page-mapping
/// copies (`victory_gpu`, queue `CopyPageMappingsBatchX`): Grand Theft Auto
/// VI maps pages into a pool view, then has the GPU map them into its tiled
/// heap. Page by page; false if a source page is not mapped physical memory.
pub fn map_alias(to: u64, from: u64, len: u64) -> bool {
let (to, from, len) = (to as usize, from as usize, len as usize);
let mut physical = physical();
unmap(&mut physical, to, len);
for k in (0..len).step_by(PAGE) {
if from == 0 {
break;
}
let at = from + k;
let Some(slice) = physical
.views
.range(..=at)
.next_back()
.filter(|(base, (size, _))| at < *base + size)
.map(|(base, (_, s))| Slice {
index: s.index + (at - base) / PAGE,
section: s.section.clone(),
})
else {
return false;
};
if !map(&mut physical, to + k, PAGE, slice) {
return false;
}
}
true
}
/// Maps `slice` and the slices after it over `[base, base + len)`, which
/// must lie in one placeholder.
fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
// SAFETY: splits the placeholder around the range (failing harmlessly
// when the range is the whole placeholder), then maps the section
// there; both act only on placeholders.
let view = unsafe {
VirtualFree(
base as *mut c_void,
len,
MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
);
MapViewOfFile3(
slice.section.0,
GetCurrentProcess(),
base as *const c_void,
(slice.index * PAGE) as u64,
len,
MEM_REPLACE_PLACEHOLDER,
PAGE_READWRITE,
std::ptr::null_mut(),
0,
)
};
if view.Value as usize != base {
tracing::warn!(
address = format_args!("{base:#x}"),
len,
error = %std::io::Error::last_os_error(),
"mapping physical pages failed (not a placeholder?)"
);
return false;
}
if !commit(base, len) {
// SAFETY: the view just mapped, back to a placeholder.
unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) };
return false;
}
// New contents, read-write: the GPU side's copies no longer guard it.
victory_gpu::title_memory_remapped(base, len);
physical.views.insert(base, (len, slice));
true
}
/// Commits the section pages a view shows (once per page, whichever view).
fn commit(base: usize, len: usize) -> bool {
// SAFETY: `[base, base + len)` is a view of a reserved section.
let done =
!unsafe { VirtualAlloc(base as *const c_void, len, MEM_COMMIT, PAGE_READWRITE) }.is_null();
if !done {
tracing::warn!(
len,
error = %std::io::Error::last_os_error(),
"committing physical pages failed"
);
}
done
}
/// Returns `[base, base + len)` to placeholders; views reaching past it
/// are mapped again outside it.
fn unmap(physical: &mut Physical, base: usize, len: usize) {
let end = base + len;
// Views do not overlap: the one holding `base`, then those starting
// inside (the GPU's page mappings make one view per page).
let first = physical
.views
.range(..=base)
.next_back()
.filter(|(at, (size, _))| *at + size > base)
.map(|(at, _)| *at);
let hit: Vec<usize> = first
.into_iter()
.chain(physical.views.range(base + 1..end).map(|(at, _)| *at))
.collect();
for at in hit {
let Some((size, slice)) = physical.views.remove(&at) else {
continue;
};
victory_gpu::title_memory_remapped(at, size);
// SAFETY: a view we mapped; it becomes a placeholder again.
unsafe {
UnmapViewOfFile2(
GetCurrentProcess(),
MEMORY_MAPPED_VIEW_ADDRESS {
Value: at as *mut c_void,
},
MEM_PRESERVE_PLACEHOLDER,
)
};
if at < base {
map(physical, at, base - at, slice.clone());
}
if at + size > end {
let index = slice.index + (end - at) / PAGE;
map(physical, end, at + size - end, Slice { index, ..slice });
}
}
}
/// The oldest layout we know; newer titles pass other flag values (Minecraft
/// 0x20000001) and read the same leading fields.
#[repr(C)]
@@ -238,10 +723,11 @@ pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut Workin
};
// SAFETY: our own process and a sized structure.
unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) };
let (gpu_optimal, standard) = victory_gpu::console::current().title_memory();
let stats = WorkingSet {
title_limit: GPU_OPTIMAL_LIMIT + STANDARD_LIMIT - TRANSFERRED.load(Ordering::Relaxed),
title_limit: gpu_optimal + standard - TRANSFERRED.load(Ordering::Relaxed),
title_used: counters.PagefileUsage,
gpu_optimal_limit: GPU_OPTIMAL_LIMIT,
gpu_optimal_limit: gpu_optimal,
..Default::default()
};
// SAFETY: checked non-null; the title passes room for the structure.
@@ -260,10 +746,11 @@ pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL {
let Some(size) = size.checked_next_multiple_of(2 * MIB) else {
return 0;
};
let standard = victory_gpu::console::current().title_memory().1;
let moved = kind == TITLE_TO_SYSTEM
&& TRANSFERRED
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |t| {
t.checked_add(size).filter(|&t| t <= STANDARD_LIMIT)
t.checked_add(size).filter(|&t| t <= standard)
})
.is_ok();
moved.into()
@@ -276,6 +763,13 @@ pub(crate) fn module() -> HleModule {
exports: vec![
hle_export!(XMemAlloc),
hle_export!(XMemFree),
hle_export!(XMemAllocDefault),
hle_export!(XMemFreeDefault),
hle_export!(XMemIsToolsMemAvailable),
hle_export!(XMemAllocatePhysicalPages),
hle_export!(XMemFreePhysicalPages),
hle_export!(XMemMapPhysicalPages),
hle_export!(XMemMapPhysicalPagesScatter),
hle_export!(XMemVirtualAlloc),
hle_export!(XMemVirtualQuery),
hle_export!(XMemGetWorkingSetStatistics),
@@ -330,9 +824,36 @@ mod tests {
assert_eq!(info.host.State, MEM_COMMIT);
assert_eq!(info.host.Protect, PAGE_READWRITE);
assert_eq!(info.flags & GRAPHICS, GRAPHICS);
// Write-watched, for the GPU side's copies.
let (mut found, mut count, mut granularity) = ([0usize; 4], 4, 0);
// SAFETY: room for `count` addresses.
let watched = unsafe {
windows_sys::Win32::System::Memory::GetWriteWatch(
0,
p,
4 * MIB,
found.as_mut_ptr().cast(),
&mut count,
&mut granularity,
)
};
assert_eq!(watched, 0);
// SAFETY: our own reservation.
assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
assert_eq!(query(p).flags, 0);
// No address field: above the 32-bit range and below 2^40, where
// the console keeps it.
let p = XMemVirtualAlloc(
std::ptr::null_mut(),
16 << 30,
MEM_RESERVE,
GRAPHICS,
PAGE_NOACCESS,
);
assert!(!p.is_null() && (p as usize) >= 1 << 32, "{p:p}");
assert!((p as usize) + (16 << 30) <= 1 << 40, "{p:p}");
// SAFETY: our own reservation.
assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
}
#[test]
@@ -342,7 +863,8 @@ mod tests {
assert!(before.title_used > 0);
assert_eq!(XMemTransferMemory(0, 128 * MIB - 1), 1);
assert_eq!(XMemTransferMemory(2, MIB), 0, "no tools memory");
assert_eq!(XMemTransferMemory(0, STANDARD_LIMIT), 0, "over budget");
let standard = victory_gpu::console::current().title_memory().1;
assert_eq!(XMemTransferMemory(0, standard), 0, "over budget");
let mut after = WorkingSet::default();
XMemGetWorkingSetStatistics(0x2000_0001, &mut after);
assert_eq!(before.title_limit - after.title_limit, 128 * MIB);
@@ -354,4 +876,81 @@ mod tests {
assert_eq!(size_of::<BasicInformation>(), 0x40);
assert_eq!(std::mem::offset_of!(WorkingSet, gpu_optimal_limit), 0x28);
}
#[test]
fn physical_pages_map_alias_and_unmap() {
let mut pages = [0usize; 3];
let mut n = 3;
assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1);
assert_eq!(n, 3);
// Packed into 21 bits as `number >> 4`, as the title keeps them.
for p in pages {
assert_eq!((p >> 4 & 0x1f_ffff) << 4, p);
}
// Reservations of 64 KiB pages, as titles make them for mapping.
let reserve = || {
XMemVirtualAlloc(
std::ptr::null_mut(),
3 * PAGE,
MEM_RESERVE | PAGES_64K,
0,
PAGE_READWRITE,
)
};
let (a, b) = (reserve(), reserve());
assert!(!a.is_null() && !b.is_null());
let at = |p: *mut c_void, page: usize| p.wrapping_byte_add(page * PAGE);
assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
// The same page at a second address shows the same bytes.
assert_eq!(
XMemMapPhysicalPages(at(b, 1), 1, pages[2..].as_ptr()),
at(b, 1)
);
// SAFETY: both pages are mapped read-write.
unsafe {
at(a, 2).cast::<u8>().write(7);
assert_eq!(at(b, 1).cast::<u8>().read(), 7);
a.cast::<u8>().write(1);
}
// Writes into pages (DirectStorage's) show through their views.
assert!(write_physical(&pages[2..], 1, &[9]));
// SAFETY: mapped read-write.
assert_eq!(unsafe { at(b, 1).cast::<u8>().add(1).read() }, 9);
// Unmapping the middle page keeps its neighbours.
assert_eq!(
XMemMapPhysicalPages(at(a, 1), 1, std::ptr::null()),
at(a, 1)
);
assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE);
assert_eq!(query(a).host.State, MEM_COMMIT);
assert_eq!(query(at(a, 2)).host.State, MEM_COMMIT);
// SAFETY: still mapped.
assert_eq!(unsafe { at(a, 2).cast::<u8>().read() }, 7);
// A scattered page lands in the hole.
let addresses = [at(a, 1)];
assert_eq!(
XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, pages.as_ptr()),
1
);
// SAFETY: page 0 is now mapped at both `a` and `a + PAGE`.
assert_eq!(unsafe { at(a, 1).cast::<u8>().read() }, 1);
// Page number 0 unmaps.
assert_eq!(
XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, [0usize].as_ptr()),
1
);
assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE);
// The GPU's page-mapping copy: what `a + 2 pages` shows, at `b`.
assert!(map_alias(b as u64, at(a, 2) as u64, PAGE as u64));
// SAFETY: mapped read-write.
assert_eq!(unsafe { b.cast::<u8>().read() }, 7);
assert!(map_alias(b as u64, 0, PAGE as u64));
assert_eq!(query(b).host.State, MEM_RESERVE);
assert!(!map_alias(b as u64, at(a, 1) as u64, PAGE as u64));
assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
assert_eq!(XMemIsToolsMemAvailable(), 0);
}
}