From 9e759de1f2ef93a2f69dc98fcb7c286a3f034377 Mon Sep 17 00:00:00 2001 From: ivall Date: Sun, 22 Nov 2026 14:34:17 +0100 Subject: [PATCH] Minecraft reaches its main menu: title window as the console screen, heap buffers in unified memory - The title's top-level window is the console's screen: frameless, 1920x1080, client area = window (WM_NCCALCSIZE), cloaked. A PC overlapped window gave a 1904x1041 client area. Minecraft sized its back buffer from it, the 1920x1080 resolve overran it and the device was removed. - ResourceBarrier drops VERTEX_AND_CONSTANT_BUFFER / INDEX_BUFFER for non-buffers. The console takes them for textures; the PC list failed to close. - FreeLibraryWhenCallbackReturns is a no-op for XCL-mapped modules. msvcp140's thread-pool callbacks raised 0xC000070E, then a fail-fast. - A GPU address the title gives is translated only when it is the title's memory (Uma::is_title_address). A PC resource's address can fall in a window's range by number. - Buffers placed in the title's heaps live in unified memory. A heap gets a block when its first buffer is placed. Console code reads root CBVs and V#s from unified memory, and Minecraft's constants read as zero. - Diagnostics: PSO states, resolves, depth clears, vertex-buffer bindings and the per-draw fixed-function state under XCL_TRACE_FRAME; XCL_TRACE_UI_ANY; graphics reservations under XCL_TRACE_MEM. --- HANDOFF.md | 22 +++++ crates/xcl/src/gpu/uma.rs | 30 +++++++ crates/xcl/src/hle/d3d12x/bind.rs | 10 ++- crates/xcl/src/hle/d3d12x/list_x.rs | 121 +++++++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/present.rs | 6 +- crates/xcl/src/hle/d3d12x/real.rs | 121 +++++++++++++++++++++++++++ crates/xcl/src/hle/kernelx.rs | 21 ++++- crates/xcl/src/hle/user.rs | 86 ++++++++++++++++++- 8 files changed, 409 insertions(+), 8 deletions(-) diff --git a/HANDOFF.md b/HANDOFF.md index 633ebf3..1b2aaa8 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1141,6 +1141,28 @@ of the title (it writes to address 0 after a failed D3D12 call: `call 0x14068c76 `sparse::mapped_ranges`). Use the release build for game runs: the debug build hashes the dirty chunks ~10× slower (and the queues then wait on each other for the sparse lock). The log has "sparse windows timing: write-watch / lock wait / chunk scan / upload" lines. +- **Minecraft (Microsoft.MinecraftBeta 1.18.30.64) reaches its main menu (2026-11-22, latest)**: panorama, logo, + buttons, the character, music and Enter work; it offers the trial (XStore is refused – no fake licences) and + stops at the Microsoft-account sign-in (Xbox Live). Run `Minecraft.Windows.exe.original`: the `Minecraft.Windows.exe` + next to it is a 29-byte patch that makes licence checks return true – not run by XCL work. Fixed (all general): + - the title's top-level window is the console's screen (`hle/user.rs`): frameless, 1920x1080, client = window + (WM_NCCALCSIZE), cloaked – a PC overlapped window gave a 1904x1041 client area, Minecraft sized its back buffer + from it and resolved 1920x1080 into it: the list failed to close, the device was removed; + - ResourceBarrier: VERTEX_AND_CONSTANT_BUFFER / INDEX_BUFFER bits are dropped for non-buffers (the console takes a + generic-read combination for textures; the PC list fails to close); + - kernelx `FreeLibraryWhenCallbackReturns`: a no-op for XCL-mapped modules (msvcp140's thread-pool callbacks: + 0xC000070E in 20 workers, then a fail-fast); + - `Uma::is_title_address` / `list_x::pc_va`: a GPU address the title gives is translated only when it is the + title's memory – a PC resource's GPU address can fall in a window's range by number (Minecraft's 4 MB dynamic + vertex buffer was read from an empty sparse window); + - buffers in the title's heaps live in unified memory (`real::note_heap_uma` / `heap_block` / + `dev_create_placed_resource_x`): the heap gets a block when its first buffer is placed, the buffer is placed + at block + offset. Console code reads root CBVs and V#s from unified memory only – Minecraft's constant buffers + were PC-only and every draw read a zero transform (nothing drew). Eager blocks for every heap filled the 2 GiB and + draws were skipped for want of argument space (the image flickered). + Diagnostics: `XCL_TRACE_FRAME` logs PSO states (depth / stencil / blend), resolves, ClearDepthStencilView, + vertex-buffer bindings (address, window, memory state) and the fixed-function state per draw kind; + `XCL_TRACE_UI_ANY=1` traces draws into any target; `XCL_TRACE_MEM=1` also logs graphics reservations. - **PS attributes / VS params are registers (2026-11-22, latest)**: Fortnite's loading art ("ŁĄCZENIE"), title screen (FORTNITE logo, "press to start", version, Epic/Unreal logos) and UI text now draw. Cause: `exp param N` (VS, MS) and `v_interp attrN` (PS) name a signature *register*, not an element, and the console's compiler diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index db8430b..9f47216 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -193,6 +193,23 @@ impl Uma { self.window_of(p).is_some() } + /// Whether `p` is memory the title has here: a block handed out in a committed window, or + /// one of its reservations in a sparse window. The windows' ranges are wide (4 GiB each) and + /// a PC resource's GPU address can fall in one by number – that address is not the + /// window's memory (Minecraft's dynamic vertex buffer, a PC upload buffer, was read from an + /// empty sparse window: nothing drew). + pub fn is_title_address(&self, p: usize) -> bool { + if self.is_sparse(p) { + return self.sparse_reservation(p).is_some(); + } + if !self.is_committed(p) { + return false; + } + let off = p - self.base; + let g = self.inner.lock().unwrap(); + g.used.range(..=off).next_back().is_some_and(|(&o, &l)| off < o + l) + } + /// Zeroed block of `size` bytes aligned to `align` (at least 64 KiB), first fit (window 0 /// first). pub fn alloc(&self, size: usize, align: usize) -> Option<*mut u8> { @@ -337,4 +354,17 @@ mod tests { // everything merged back into one range assert!(u.alloc(16 << 20, 0).is_some()); } + + /// Only handed-out blocks are the title's memory: an address in a window's range that is + /// not one (a PC GPU address by number) is not. + #[test] + fn title_addresses_are_blocks_handed_out() { + let u = Uma::new(16 << 20).unwrap(); + let a = u.alloc(0x2_0000, 0).unwrap() as usize; + assert!(u.is_title_address(a) && u.is_title_address(a + 0x1_FFFF)); + assert!(!u.is_title_address(a + 0x2_0000) && !u.is_title_address(u.base() + (8 << 20))); + assert!(!u.is_title_address(u.base() - 1) && !u.is_title_address(u.base() + (32 << 20))); + assert!(u.free(a)); + assert!(!u.is_title_address(a)); + } } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 8abb049..3852903 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -268,7 +268,7 @@ unsafe fn trace_draw_kinds(this: *mut c_void, pso: usize) { } g.push((vs, ps, rt)); } - let desc = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0) }); + let desc = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0, d.SampleDesc.Count) }); let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); let mut tex = Vec::new(); @@ -288,10 +288,11 @@ unsafe fn trace_draw_kinds(this: *mut c_void, pso: usize) { } } crate::xlog_info!( - "frame trace: draws vs {vs:016x} ps {ps:016x} into {:?}{} – textures {}", + "frame trace: draws vs {vs:016x} ps {ps:016x} into {:?}{} – textures {}; {}", desc(rt), if super::present::is_presented(rt) { " (presented)" } else { "" }, - tex.join(", ") + tex.join(", "), + super::list_x::state_summary(this) ); } @@ -301,8 +302,9 @@ unsafe fn trace_ui_draw(this: *mut c_void, pso: usize) { if super::present::activity().0 < 300 || N.load(std::sync::atomic::Ordering::Relaxed) >= 24 { return; } + // draws into a presented target, or – `XCL_TRACE_UI_ANY` – into any target let Some(rt) = super::present::rt0_resource(this as usize) else { return }; - if !super::present::is_presented(rt) { + if !super::present::is_presented(rt) && std::env::var_os("XCL_TRACE_UI_ANY").is_none() { return; } N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 9725d52..38b69c5 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -245,6 +245,25 @@ struct Bindings { render_targets: Option<(Vec, i32, Option)>, } +/// `XCL_TRACE_FRAME`: the fixed-function state a list last set (topology, first viewport and +/// scissor, render targets) as text. +pub(super) fn state_summary(list: *mut c_void) -> String { + let mut out = String::new(); + with_bindings(list, |b| { + let vp = b.viewports.first().map(|v| (v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth)); + let sc = b.scissors.first().map(|r| (r.left, r.top, r.right, r.bottom)); + out = format!( + "topology {:?}, stencil ref {:?}, viewport {vp:?} ({} set), scissor {sc:?} ({} set), render targets {:?}", + b.topology, + b.stencil, + b.viewports.len(), + b.scissors.len(), + b.render_targets.as_ref().map(|(h, _, d)| (h.len(), d.is_some())) + ); + }); + out +} + fn with_bindings(list: *mut c_void, f: impl FnOnce(&mut Bindings)) { let mut g = LISTS.lock().unwrap(); f(&mut g.get_or_insert_with(HashMap::new).entry(list as usize).or_default().bindings); @@ -1270,7 +1289,12 @@ pub(super) unsafe fn prepare_draw(list: *mut c_void) { // --------------------------------------------------------------------------------------- /// a console GPU address as the PC's (unified memory: the window buffer's) +/// A GPU address the title gave: its memory's PC address when it is the title's memory, else +/// as it is (a PC resource's GPU address – it may lie in a window's range by number). fn pc_va(va: u64) -> u64 { + if !crate::gpu::uma::get().is_some_and(|u| u.is_title_address(va as usize)) { + return va; + } real::uma_va_of(va as usize).unwrap_or(va) } @@ -1329,7 +1353,28 @@ pub(super) unsafe extern "system" fn ia_set_vertex_buffers_x(this: *mut c_void, let v: Vec = (0..n as usize) .map(|k| { let mut v = views.add(k).read_unaligned(); + let title = v.BufferLocation; v.BufferLocation = pc_va(v.BufferLocation); + if super::present::trace_frame() { + static N: AtomicU64 = AtomicU64::new(0); + let i = N.fetch_add(1, Ordering::Relaxed); + if i < 12 || (i.is_power_of_two() && i < 1 << 16) { + let n = (v.SizeInBytes as usize).min(256); + let data = (title != 0 && crate::gpu::shader::readable(title as usize, n)).then(|| std::slice::from_raw_parts(title as *const u8, n).iter().filter(|&&b| b != 0).count()); + let win = crate::gpu::uma::get().and_then(|u| u.window_of(title as usize).map(|w| (w, u.window(w), u.is_sparse(title as usize)))); + let mut mbi: windows_sys::Win32::System::Memory::MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + let q = windows_sys::Win32::System::Memory::VirtualQuery(title as *const c_void, &mut mbi, std::mem::size_of_val(&mbi)); + crate::xlog_info!( + "frame trace: vertex buffer #{i} slot {}: title {title:#x} → PC {:#x}, {} bytes, stride {}; non-zero in the first {n} bytes (CPU view): {data:?}; window (index, (base, size), sparse) {win:x?}; memory state {:#x} protect {:#x} (query {q})", + start + k as u32, + v.BufferLocation, + v.SizeInBytes, + v.StrideInBytes, + mbi.State, + mbi.Protect + ); + } + } v }) .collect(); @@ -1468,6 +1513,13 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 } b[5] &= PC_STATES; b[6] &= PC_STATES; + // VERTEX_AND_CONSTANT_BUFFER / INDEX_BUFFER are buffer states on the PC; the console + // takes them for textures too (Minecraft moves a texture to a generic-read + // combination) – the PC list then fails to close + if (b[5] | b[6]) & BUFFER_ONLY_STATES != 0 && !is_buffer((b[2] as u64 | (b[3] as u64) << 32) as usize) { + b[5] &= !BUFFER_ONLY_STATES; + b[6] &= !BUFFER_ONLY_STATES; + } if b[5] == b[6] { continue; } @@ -1479,6 +1531,15 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 } } +/// D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER | INDEX_BUFFER: valid for buffers only +const BUFFER_ONLY_STATES: u32 = 0x1 | 0x2; + +/// Whether `res` is a buffer (null / unknown: taken as one – its states are left alone). +unsafe fn is_buffer(res: usize) -> bool { + let r = res as *mut c_void; + ID3D12Resource::from_raw_borrowed(&r).is_none_or(|x| x.GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) +} + /// DMA list #9 Close: as on the PC; a failure is logged (the title stops on it) pub(super) unsafe extern "system" fn dma_close_x(this: *mut c_void) -> i32 { let hr = pc:: i32>(this, 9)(this); @@ -1574,6 +1635,66 @@ pub(super) unsafe extern "system" fn copy_texture_region_flags_x(this: *mut c_vo copy_texture_region_x(this, dst, x, y, z, src, bx) } +const PC_CLEAR_DEPTH_STENCIL_VIEW: usize = 47; + +/// command list #51 ClearDepthStencilView(dsv, flags, depth, stencil, rects, rect list) (PC #47) +pub(super) unsafe extern "system" fn clear_depth_stencil_x(this: *mut c_void, dsv: usize, flags: u32, depth: f32, stencil: u8, n: u32, rects: *const windows::Win32::Foundation::RECT) { + if super::present::trace_frame() { + static N: AtomicU64 = AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed); + if k < 8 || k.is_power_of_two() { + crate::xlog_info!("frame trace: ClearDepthStencilView #{k} {dsv:#x}: flags {flags:#x} (1 depth, 2 stencil), depth {depth}, stencil {stencil}, {n} rects"); + } + } + pc::(this, PC_CLEAR_DEPTH_STENCIL_VIEW)(this, dsv, flags, depth, stencil, n, rects) +} + +const PC_RESOLVE_SUBRESOURCE: usize = 19; +const PC_RESOLVE_SUBRESOURCE_REGION: usize = 64; + +/// `XCL_TRACE_FRAME`: a resolve (first 12 and powers of two) – what goes where +unsafe fn trace_resolve(what: &str, dst: usize, src: usize, format: i32, extra: &str) { + if !super::present::trace_frame() { + return; + } + static N: AtomicU64 = AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed); + if k >= 12 && !k.is_power_of_two() { + return; + } + let desc = |r: usize| { + let p = r as *mut c_void; + ID3D12Resource::from_raw_borrowed(&p).map(|x| { + let d = x.GetDesc(); + (d.Width, d.Height, d.Format.0, d.SampleDesc.Count) + }) + }; + crate::xlog_info!( + "frame trace: {what} #{k} {src:#x} {:?} → {dst:#x} {:?}{} format {format}{extra}", + desc(src), + desc(dst), + if super::present::is_presented(dst) { " (presented)" } else { "" } + ); +} + +/// command list #19 ResolveSubresource(dst, dst sub, src, src sub, format) (PC #19) +pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, dst: usize, dst_sub: u32, src: usize, src_sub: u32, format: i32) { + super::present::note_use(dst, super::present::USE_COPY); + trace_resolve("ResolveSubresource", dst, src, format, ""); + pc::(this, PC_RESOLVE_SUBRESOURCE)(this, dst, dst_sub, src, src_sub, format) +} + +/// command list #108 ResolveSubresourceRegion(dst, dst sub, x, y, src, src sub, rect, format, +/// mode) (PC #64) +#[allow(clippy::too_many_arguments)] +pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_void, dst: usize, dst_sub: u32, x: u32, y: u32, src: usize, src_sub: u32, rect: *const windows::Win32::Foundation::RECT, format: i32, mode: i32) { + super::present::note_use(dst, super::present::USE_COPY); + if super::present::trace_frame() { + trace_resolve("ResolveSubresourceRegion", dst, src, format, &format!(" mode {mode} at ({x}, {y}) rect {:?}", rect.as_ref().map(|r| (r.left, r.top, r.right, r.bottom)))); + } + pc::(this, PC_RESOLVE_SUBRESOURCE_REGION)(this, dst, dst_sub, x, y, src, src_sub, rect, format, mode) +} + /// CopyResource(dst, src) (PC #17; DMA list #13): buffers placed below their console address /// are copied as their own bytes (the PC resources also hold what lies before them) pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usize, src: usize) { diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 2f9ea29..d0cb776 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -597,9 +597,11 @@ fn rgb(format: DXGI_FORMAT, t: u32) -> Option<[u8; 3]> { }) } -/// the resource bound as a render target most often (`XCL_TRACE_FRAME`) +/// the single-sampled resource bound as a render target most often (`XCL_TRACE_FRAME`; a +/// multisampled one cannot be copied to a buffer – the present list would not close) fn busiest_rt() -> Option { - USES.lock().unwrap().as_ref()?.iter().filter(|(_, u)| u[USE_RT] > 0).max_by_key(|(_, u)| u[USE_RT]).map(|(&r, _)| r) + let single = |r: usize| unsafe { ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).is_some_and(|x| x.GetDesc().SampleDesc.Count <= 1) }; + USES.lock().unwrap().as_ref()?.iter().filter(|(&r, u)| u[USE_RT] > 0 && single(r)).max_by_key(|(_, u)| u[USE_RT]).map(|(&r, _)| r) } /// an 11- / 10-bit unsigned float (5-bit exponent) -> f32 diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index faec7b5..3dedbc2 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -708,6 +708,9 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (15, l::copy_buffer_region_x as usize), (16, l::copy_texture_region_x as usize), (17, l::copy_resource_x as usize), + (19, l::resolve_subresource_x as usize), + (51, l::clear_depth_stencil_x as usize), + (108, l::resolve_subresource_region_x as usize), (13, b::draw_indexed_instanced as usize), (14, b::dispatch as usize), (48, l::ia_set_vertex_buffers_x as usize), @@ -1592,6 +1595,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { Kind::Resource => v.extend_from_slice(&[("Release", res_release as usize), ("Map", res_map as usize), ("Unmap", res_unmap as usize)]), Kind::PipelineState => v.push(("Release", pso_release as usize)), Kind::DescriptorHeap => v.push(("Release", heap_release as usize)), + Kind::Heap => v.push(("Release", mem_heap_release as usize)), _ => {} } v @@ -1768,6 +1772,18 @@ const PC_RESOURCE_STATES: u32 = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x40 | 0x8 /// buffers-only heap) is made the PC's way (`device_x::pc_resource_desc`, the console's state /// bits dropped). Logged with the console's values. pub(super) unsafe extern "system" fn dev_create_placed_resource_x(this: *mut c_void, heap: usize, offset: usize, desc: usize, state: usize, clear: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + // a buffer in a heap that has unified memory (`note_heap_uma`): that memory at its offset + if desc != 0 && crate::gpu::shader::readable(desc, 0x38) { + let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); + let is_buffer = u32::from_le_bytes(x[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32; + if let Some(block) = is_buffer.then(|| heap_block(heap)).flatten() { + let d = super::device_x::pc_resource_desc(&x); + let st = state as u32 & PC_RESOURCE_STATES; + if let Some(hr) = place_at_title_address(this, block + offset, &d, st, clear as *const c_void, riid, ppv) { + return hr; + } + } + } let hr = dev_create_placed_resource(this, heap, offset, desc, state, clear, riid, ppv); if hr >= 0 || desc == 0 || !crate::gpu::shader::readable(desc, 0x38) { return hr; @@ -1803,6 +1819,9 @@ const PC_HEAP_FLAGS: u32 = 0x3FED; /// covers it, an unknown type as DEFAULT. Logged with the console's values. pub(super) unsafe extern "system" fn dev_create_heap(this: *mut c_void, desc: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let hr = dev_create_heap_pc(this, desc, riid, ppv); + if hr >= 0 { + note_heap_uma(desc, ppv); + } if hr >= 0 || desc == 0 || !crate::gpu::shader::readable(desc, std::mem::size_of::()) { return hr; } @@ -1815,6 +1834,9 @@ pub(super) unsafe extern "system" fn dev_create_heap(this: *mut c_void, desc: us } d.SizeInBytes = d.SizeInBytes.div_ceil(0x1_0000) * 0x1_0000; let hr2 = dev_create_heap_pc(this, &d as *const _ as usize, riid, ppv); + if hr2 >= 0 { + note_heap_uma(desc, ppv); + } static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 8 { crate::xlog_info!( @@ -1825,6 +1847,67 @@ pub(super) unsafe extern "system" fn dev_create_heap(this: *mut c_void, desc: us hr2 } creator!(dev_create_heap1, "CreateHeap1", Kind::Heap, [a1, a2]); + +/// heap → (its size, the block of unified memory its buffers live in once one is placed) +static HEAP_UMA: Mutex)>>> = Mutex::new(None); + +/// A heap the title made that may hold buffers: a block of unified memory as large stands for +/// it. On the console every heap is memory the CPU and the GPU address alike, and console code +/// reads buffers (root descriptors, V#s) from that memory – a PC heap's buffer has a GPU +/// address only (Minecraft's constant and vertex buffers: a heap of its own; its UI drew +/// nothing – the constants read as zero). Buffers placed in the heap are placed in the block +/// (`dev_create_placed_resource_x`); textures stay in the PC heap. The block is taken when the +/// first buffer is placed (most heaps hold textures only: a block for each filled the 2 GiB of +/// unified memory, and draws then found no room for their arguments – the image flickered); +/// none when unified memory is full (the PC heap as before). +unsafe fn note_heap_uma(desc: usize, ppv: *mut *mut c_void) { + const DENY_BUFFERS: i32 = 0x4; + if desc == 0 || ppv.is_null() || (*ppv).is_null() || !crate::gpu::shader::readable(desc, std::mem::size_of::()) { + return; + } + let d: D3D12_HEAP_DESC = std::ptr::read_unaligned(desc as *const D3D12_HEAP_DESC); + if d.Flags.0 & DENY_BUFFERS != 0 || d.SizeInBytes == 0 || UMA_HEAPS.lock().unwrap().is_empty() { + return; + } + HEAP_UMA.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (d.SizeInBytes as usize, None)); +} + +/// The block of unified memory standing for `heap` (taken now if it has none yet; None: not a +/// heap that takes one, or unified memory is full). +fn heap_block(heap: usize) -> Option { + let mut g = HEAP_UMA.lock().unwrap(); + let e = g.as_mut()?.get_mut(&heap)?; + if let Some(p) = e.1 { + return Some(p); + } + let u = crate::gpu::uma::get()?; + let Some(p) = u.alloc(e.0.div_ceil(0x1_0000) * 0x1_0000, 0x1_0000) else { + static FULL: AtomicU64 = AtomicU64::new(0); + if FULL.fetch_add(1, Ordering::Relaxed) == 0 { + crate::xlog_warn!("D3D12.X: heap of {:#x} bytes: unified memory is full ({} MB used) – its buffers stay PC-only", e.0, u.used() >> 20); + } + return None; + }; + e.1 = Some(p as usize); + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!("D3D12.X: heap {heap:#x} ({:#x} bytes) holds buffers: in unified memory at {:#x}", e.0, p as usize); + } + Some(p as usize) +} + +/// ID3D12Heap::Release: its block of unified memory goes with it. +unsafe extern "system" fn mem_heap_release(this: *mut c_void) -> u32 { + let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + let n = f(this); + if n == 0 { + let gone = HEAP_UMA.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))).and_then(|e| e.1); + if let (Some(p), Some(u)) = (gone, crate::gpu::uma::get()) { + u.free(p); + } + } + n +} creator!(dev_create_fence_pc, "CreateFence", Kind::Fence, [a1, a2]); /// fences created through the device (AddRef'd: they are released at the end only) @@ -2206,6 +2289,44 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo if super::present::trace_frame() { let ps = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(vs), ps)); + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 24 { + let b = &d.BlendState.RenderTarget[0]; + let z = &d.DepthStencilState; + crate::xlog_info!( + "frame trace: PSO vs {:016x} ps {ps:016x}: RTs {} {:?} DSV {} samples {}, depth (enable {}, write {}, func {}), stencil {}, blend0 (enable {}, src {} dst {} op {}, alpha src {} dst {}, mask {:#x}), cull {} fill {} depth clip {}, sample mask {:#x}", + crate::gpu::shader::fnv64(vs), + d.NumRenderTargets, + &d.RTVFormats[..d.NumRenderTargets.min(8) as usize].iter().map(|f| f.0).collect::>(), + d.DSVFormat.0, + d.SampleDesc.Count, + z.DepthEnable.as_bool(), + z.DepthWriteMask.0, + z.DepthFunc.0, + z.StencilEnable.as_bool(), + b.BlendEnable.as_bool(), + b.SrcBlend.0, + b.DestBlend.0, + b.BlendOp.0, + b.SrcBlendAlpha.0, + b.DestBlendAlpha.0, + b.RenderTargetWriteMask, + d.RasterizerState.CullMode.0, + d.RasterizerState.FillMode.0, + d.RasterizerState.DepthClipEnable.as_bool(), + d.SampleMask + ); + if z.StencilEnable.as_bool() { + let f = |o: &D3D12_DEPTH_STENCILOP_DESC| (o.StencilFunc.0, o.StencilPassOp.0, o.StencilFailOp.0, o.StencilDepthFailOp.0); + crate::xlog_info!( + "frame trace: … its stencil: read mask {:#x} write mask {:#x}, front (func, pass, fail, depth fail) {:?}, back {:?}", + z.StencilReadMask, + z.StencilWriteMask, + f(&z.FrontFace), + f(&z.BackFace) + ); + } + } } if n < 5 || n % 1000 == 0 { crate::xlog_info!("D3D12.X: graphics PSO from translated console shaders (#{})", n + 1); diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 0e7adce..7338790 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -89,6 +89,7 @@ pub fn exports() -> Vec<(&'static str, usize)> { GetModuleFileNameW, GetModuleFileNameA, FreeLibrary, + FreeLibraryWhenCallbackReturns, DisableThreadLibraryCalls, ] } @@ -164,7 +165,9 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: let uma = crate::gpu::uma::get(); // committing inside one of the title's reservations in a sparse window if !addr.is_null() && t & 0x1000 != 0 && uma.is_some_and(|u| u.is_sparse(addr as usize)) { - return commit_sparse(addr as usize, size, p); + let q = commit_sparse(addr as usize, size, p); + trace_mem("VirtualAlloc (sparse commit)", addr as usize, size, t as u64, p, q as usize); + return q; } // the title's own reservations of 64 KiB pages: in a sparse window, so the GPU sees them if addr.is_null() && t & 0x2000 != 0 && t & MEM_64K_PAGES == MEM_64K_PAGES { @@ -173,11 +176,13 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: uma.map(|u| u.sparse_release(q)); return std::ptr::null_mut(); } + trace_mem("VirtualAlloc (64K pages, sparse)", 0, size, t as u64, p, q); return q as *mut c_void; } } if addr.is_null() && t & MEM_GRAPHICS != 0 && t & 0x1000 != 0 { if let Some(q) = crate::gpu::uma::get().and_then(|u| u.alloc(size, 0)) { + trace_mem("VirtualAlloc (graphics, UMA)", 0, size, t as u64, p, q as usize); return q as *mut c_void; } } @@ -186,9 +191,11 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: // reserve a range, then commit or map pages and place resources in it): a range of // unified memory, which is committed already if let Some(q) = crate::gpu::uma::get().and_then(|u| u.reserve(size, 0x1_0000)) { + trace_mem("VirtualAlloc (graphics reserve, UMA)", 0, size, t as u64, p, q as usize); return q as *mut c_void; } if let Some(q) = uma.and_then(|u| u.sparse_reserve(size)) { + trace_mem("VirtualAlloc (graphics reserve, sparse)", 0, size, t as u64, p, q); return q as *mut c_void; } let q = mem::VirtualAlloc(addr, size, mem::MEM_RESERVE | MEM_WRITE_WATCH, sanitize_protect(p)); @@ -1117,6 +1124,18 @@ pub unsafe extern "system" fn FreeLibrary(h: usize) -> BOOL { fnd::FreeLibrary(h as _) } +/// A thread-pool callback asks for its module to be freed when it returns (the title's +/// msvcp140 does, for the reference it took on itself). A module XCL mapped is not in Windows' +/// loader – the pool's FreeLibrary fails and raises 0xC000070E in the worker (Minecraft: 20 +/// workers at once, then a fail-fast). XCL's modules are never unloaded: nothing to do for them. +pub unsafe extern "system" fn FreeLibraryWhenCallbackReturns(instance: *mut c_void, h: usize) { + let main = modules::main_module().is_some_and(|m| m.base == h); + if main || modules::find_mapped_by_base(h).is_some() || modules::hle_name_by_handle(h).is_some() { + return; + } + thr::FreeLibraryWhenCallbackReturns(instance as _, h as _) +} + pub unsafe extern "system" fn DisableThreadLibraryCalls(h: usize) -> BOOL { if let Some(m) = modules::find_mapped_by_base(h) { m.no_thread_calls.store(true, Ordering::Relaxed); diff --git a/crates/xcl/src/hle/user.rs b/crates/xcl/src/hle/user.rs index 2d51f1a..15e7167 100644 --- a/crates/xcl/src/hle/user.rs +++ b/crates/xcl/src/hle/user.rs @@ -6,6 +6,14 @@ //! text show as CJK characters (8-bit text read as UTF-16). The console's user32 is Unicode //! underneath, so the ANSI calls are made as Unicode ones here – the window is a Unicode window //! with the text converted. +//! +//! A console title's window is the screen: no caption or frame, its client area the whole +//! window, 1920x1080 (GetClientRect gives that on every console; titles pick 4K output +//! themselves). On the PC a 1920x1080 overlapped window has a 1904x1041 client area, and a title +//! that sizes its back buffer from it (Minecraft) resolved its 1920x1080 scene past the end of +//! it – the list failed to close and the device was removed. So the title's top-level windows +//! are made frameless, the console's size, kept frameless through style changes +//! (WM_NCCALCSIZE) and cloaked: the game's frames are shown in XCL's own window. #![allow(non_snake_case)] @@ -16,6 +24,9 @@ use crate::util::{from_ansi_ptr, wide}; #[link(name = "user32")] extern "system" { fn RegisterClassExW(c: *const WndClassEx) -> u16; + fn SetWindowLongPtrW(hwnd: *mut c_void, index: i32, value: isize) -> isize; + fn CallWindowProcW(proc_: isize, hwnd: *mut c_void, msg: u32, wp: usize, lp: isize) -> isize; + fn SetWindowPos(hwnd: *mut c_void, after: *mut c_void, x: i32, y: i32, w: i32, h: i32, flags: u32) -> i32; #[allow(clippy::too_many_arguments)] fn CreateWindowExW(ex_style: u32, class: *const u16, title: *const u16, style: u32, x: i32, y: i32, w: i32, h: i32, parent: *mut c_void, menu: *mut c_void, instance: *mut c_void, param: *const c_void) -> *mut c_void; } @@ -79,5 +90,78 @@ pub unsafe extern "system" fn CreateWindowExA(ex_style: u32, class: *const u8, t let mut keep = Vec::new(); let class = name(class, &mut keep); let title = if title.is_null() { std::ptr::null() } else { name(title, &mut keep) }; - CreateWindowExW(ex_style, class, title, style, x, y, w, h, parent, menu, instance, param) + console_window(ex_style, class, title, style, x, y, w, h, parent, menu, instance, param) +} + +#[link(name = "dwmapi")] +extern "system" { + fn DwmSetWindowAttribute(hwnd: *mut c_void, attr: u32, value: *const c_void, size: u32) -> i32; +} + +/// the console's screen as a title's window sees it +const CONSOLE_W: i32 = 1920; +const CONSOLE_H: i32 = 1080; +const WS_CHILD: u32 = 0x4000_0000; +const WS_POPUP: u32 = 0x8000_0000; +/// caption, border, sizing frame, system menu, minimize / maximize boxes +const WS_FRAME: u32 = 0x00C0_0000 | 0x0004_0000 | 0x0008_0000 | 0x0002_0000 | 0x0001_0000; +/// dialog / window / client / static edges +const WS_EX_FRAME: u32 = 0x1 | 0x100 | 0x200 | 0x2_0000; +const GWLP_WNDPROC: i32 = -4; +const WM_NCDESTROY: u32 = 0x82; +const WM_NCCALCSIZE: u32 = 0x83; +const WM_GETMINMAXINFO: u32 = 0x24; +const DWMWA_CLOAK: u32 = 13; + +/// the window procedure each console window had (hwnd → procedure) +static PROCS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// A console title's top-level window: frameless, 1920x1080, cloaked (see the module notes). +#[allow(clippy::too_many_arguments)] +unsafe fn console_window(ex_style: u32, class: *const u16, title: *const u16, style: u32, x: i32, y: i32, w: i32, h: i32, parent: *mut c_void, menu: *mut c_void, instance: *mut c_void, param: *const c_void) -> *mut c_void { + if style & WS_CHILD != 0 { + return CreateWindowExW(ex_style, class, title, style, x, y, w, h, parent, menu, instance, param); + } + let style = style & !WS_FRAME | WS_POPUP; + let hwnd = CreateWindowExW(ex_style & !WS_EX_FRAME, class, title, style, 0, 0, CONSOLE_W, CONSOLE_H, parent, menu, instance, param); + if hwnd.is_null() { + return hwnd; + } + let cloak: i32 = 1; + DwmSetWindowAttribute(hwnd, DWMWA_CLOAK, &cloak as *const i32 as *const c_void, 4); + let old = SetWindowLongPtrW(hwnd, GWLP_WNDPROC, console_wndproc as usize as isize); + if old != 0 { + PROCS.lock().unwrap().push((hwnd as usize, old)); + // SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED + SetWindowPos(hwnd, std::ptr::null_mut(), 0, 0, 0, 0, 0x2 | 0x1 | 0x4 | 0x10 | 0x20); + } + crate::xlog_info!("user: the title's window {hwnd:p} is the console's screen ({CONSOLE_W}x{CONSOLE_H}, no frame, cloaked)"); + hwnd +} + +/// A console window has no non-client area whatever its style, and may be the screen's size +/// on a smaller PC monitor. +unsafe extern "system" fn console_wndproc(hwnd: *mut c_void, msg: u32, wp: usize, lp: isize) -> isize { + let orig = PROCS.lock().unwrap().iter().find(|e| e.0 == hwnd as usize).map(|e| e.1); + let Some(orig) = orig else { return 0 }; + match msg { + // the client area is the whole window (wp != 0: rgrc[0] already holds the window rect) + WM_NCCALCSIZE => 0, + WM_GETMINMAXINFO => { + let r = CallWindowProcW(orig, hwnd, msg, wp, lp); + // MINMAXINFO: ptMaxSize (+8), ptMaxTrackSize (+24) + if let Some(m) = (lp as *mut [i32; 10]).as_mut() { + m[2] = m[2].max(CONSOLE_W); + m[3] = m[3].max(CONSOLE_H); + m[6] = m[6].max(CONSOLE_W); + m[7] = m[7].max(CONSOLE_H); + } + r + } + WM_NCDESTROY => { + PROCS.lock().unwrap().retain(|e| e.0 != hwnd as usize); + CallWindowProcW(orig, hwnd, msg, wp, lp) + } + _ => CallWindowProcW(orig, hwnd, msg, wp, lp), + } }