From fd97d91e6c09532dfeb130280bf34201c6e28721 Mon Sep 17 00:00:00 2001 From: Christian Thackston Date: Tue, 24 Nov 2026 06:28:42 -0800 Subject: [PATCH] D3D12.X: under Wine, vkd3d-proton's assert-checked classes keep their vtable vkd3d-proton takes a heap, resource, descriptor heap, query heap, root signature, pipeline state or command signature only with its own vtable: an assert(iface->lpVtbl == &..._vtbl) in each of its methods and wherever one is passed in (vkd3d_private.h). The official release builds keep these asserts, so adoption, which replaces the vtable pointer, ends the process (status 3) at the first such object: under Wine with the v3.1 release DLLs the test title stops at its first heap after 6 checks. Under Wine (util::under_wine) these classes now get XCL's PC slots written into the runtime's own table instead (VirtualProtect, as XAudio2's patch does), only up to the PC interface's method count, and only when the object answered QueryInterface for that interface with itself and every slot up to there is in the runtime's module. orig_fn finds the entries from before by the table. Classes are made one at a time, so no thread scans a table another is writing. The table is shared by every object of the class (swap-chain buffers too); the overrides already take objects XCL did not create. These classes have no console slots past the PC interface, so nothing is lost there. Not covered, by design: fences (console #12 is past the PC table), command allocators and lists (vkd3d-proton checks those at run time, E_INVALIDARG; #867 handles them), bundles. On Windows nothing changes: every new path is behind under_wine(), and orig_fn's lookup has no table there. Part of #175. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/real.rs | 154 +++++++++++++++++++++++++++++- 1 file changed, 152 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index f1ea87c8ba..e883533503 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -616,10 +616,88 @@ unsafe fn vt(obj: *mut c_void) -> *const usize { /// Original function of `slot` for an adopted object. pub unsafe fn orig_fn(this: *mut c_void, slot: usize) -> usize { let ext = vt(this); + if let Some(f) = in_place_original(ext as usize, slot) { + return f; + } let orig = *ext.sub(1) as *const usize; *orig.add(slot) } +// vkd3d-proton takes an object (as `this` of its own methods, or as an argument) only with its own +// vtable: for heaps, resources, descriptor / query heaps, root signatures, pipeline states and +// command signatures an assertion, which its release builds keep (the process ends). So under +// Wine those classes keep their table and XCL's PC slots are written into it (`in_place_kind`), as +// XAudio2's `patch` does; the entries it had before are kept here for `orig_fn`. Only +// `class_for`'s Wine branch adds a table, so on Windows the list stays empty and `orig_fn` reads +// ext[-1] as before. + +struct InPlace { + table: AtomicUsize, + /// the table's first `len` entries before XCL wrote its own + saved: AtomicUsize, + len: AtomicUsize, +} + +const IN_PLACE_MAX: usize = 32; +static IN_PLACE: [InPlace; IN_PLACE_MAX] = [const { InPlace { table: AtomicUsize::new(0), saved: AtomicUsize::new(0), len: AtomicUsize::new(0) } }; IN_PLACE_MAX]; +/// entries of `IN_PLACE` in use (published with Release after the entry is written) +static IN_PLACE_N: AtomicUsize = AtomicUsize::new(0); +static IN_PLACE_LOCK: Mutex<()> = Mutex::new(()); + +/// For a vtable patched in place: the runtime's function of `slot` (lock-free: `orig_fn`). +fn in_place_original(table: usize, slot: usize) -> Option { + let n = IN_PLACE_N.load(Ordering::Acquire); + let e = IN_PLACE[..n].iter().find(|e| e.table.load(Ordering::Relaxed) == table)?; + let len = e.len.load(Ordering::Relaxed); + // SAFETY: `saved` holds `len` entries (leaked); past them the table is the runtime's own + Some(unsafe { if slot < len { *(e.saved.load(Ordering::Relaxed) as *const usize).add(slot) } else { *(table as *const usize).add(slot) } }) +} + +/// The classes vkd3d-proton checks only by an assertion on their vtable, whose console slots all +/// sit inside the PC interface: patched in place under Wine. (Not fences: console #12 is past the +/// PC table's end. Not command allocators and lists: vkd3d-proton checks those at run time, and a +/// title calls an allocator past its 9 PC methods.) +fn in_place_kind(kind: Kind) -> bool { + matches!(kind, Kind::Heap | Kind::Resource | Kind::DescriptorHeap | Kind::RootSignature | Kind::PipelineState | Kind::QueryHeap | Kind::CommandSignature) +} + +/// Write `entries` over the first `entries.len()` entries of the runtime's vtable `table`, keeping +/// the ones there for `orig_fn`. `register` (the class into EXTS / CLASSES) runs under the same +/// lock before the first entry is written, so whatever reaches an XCL entry finds its class. +/// Ok(false): `table` was patched already (another thread, another kind) – nothing written. +/// The caller bounds `entries` by the PC interface the object answered for itself. +unsafe fn patch_in_place(table: *mut usize, entries: &[usize], register: impl FnOnce()) -> Result { + use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_READWRITE}; + let _g = IN_PLACE_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let n = IN_PLACE_N.load(Ordering::Acquire); + if IN_PLACE[..n].iter().any(|e| e.table.load(Ordering::Relaxed) == table as usize) { + return Ok(false); + } + if n == IN_PLACE_MAX { + return Err(format!("more than {IN_PLACE_MAX} vtables")); + } + let bytes = std::mem::size_of_val(entries); + let mut old = 0u32; + if VirtualProtect(table as *const c_void, bytes, PAGE_READWRITE, &mut old) == 0 { + return Err(format!("VirtualProtect: error {}", windows_sys::Win32::Foundation::GetLastError())); + } + let saved: &'static [usize] = Box::leak((0..entries.len()).map(|i| table.add(i).read()).collect::>().into_boxed_slice()); + let e = &IN_PLACE[n]; + e.table.store(table as usize, Ordering::Relaxed); + e.saved.store(saved.as_ptr() as usize, Ordering::Relaxed); + e.len.store(saved.len(), Ordering::Relaxed); + IN_PLACE_N.store(n + 1, Ordering::Release); + register(); + for (i, &f) in entries.iter().enumerate() { + if saved[i] != f { + // other threads call through the table meanwhile: one aligned store per entry + (*(table.add(i) as *const AtomicUsize)).store(f, Ordering::Release); + } + } + VirtualProtect(table as *const c_void, bytes, old, &mut old); + Ok(true) +} + fn module_of(addr: usize) -> usize { use windows_sys::Win32::System::LibraryLoader::{ GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, @@ -712,6 +790,19 @@ pub unsafe fn adopt(obj: *mut c_void, kind: Kind) { } unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { + if in_place_kind(kind) && crate::util::under_wine() { + // one class at a time: a thread that scanned the table while another wrote XCL's entries + // into it would stop at the first of them and make an extended copy of a table that is + // half XCL's (its `orig_fn` would then call XCL's own entries) + static MAKING: Mutex<()> = Mutex::new(()); + let _g = MAKING.lock().unwrap_or_else(|e| e.into_inner()); + return make_class(obj, orig, kind, true); + } + make_class(obj, orig, kind, false) +} + +/// `class_for`; `in_place`: the class may get its slots in the runtime's own table (Wine). +unsafe fn make_class(obj: *mut c_void, orig: usize, kind: Kind, in_place: bool) -> usize { if let Some(c) = CLASSES.lock().unwrap().iter().find(|c| c.orig == orig && c.kind == kind) { return c.ext; } @@ -721,10 +812,14 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { let qi: QiFn = std::mem::transmute(*ot); let release: RefFn = std::mem::transmute(*ot.add(2)); let mut iface = *chain.last().expect("layout chain"); + // the object answered for it itself (not another object's table): its table has the + // interface's methods + let mut own = false; for i in &chain { let iid = layout::parse_guid(i.iid); let mut out = std::ptr::null_mut(); if qi(obj, &iid, &mut out) >= 0 && !out.is_null() { + own = out == obj; release(out); iface = i; break; @@ -736,14 +831,18 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { while scanned < public + MAX_SCAN && module_of(*ot.add(scanned)) == m0 { scanned += 1; } - let scanned = scanned.max(public); let max_console = console_slots(kind) .iter() .map(|e| e.0 + 1) .chain(console_remap(kind).iter().map(|e| e.0 + 1)) .max() .unwrap_or(0); - let total = (scanned + EXTRA_SLOTS).max(max_console); + // in place only the PC interface's slots are written: the table's length is known only up to + // there (the object's own answer to QueryInterface; each of those slots in the runtime's + // module), and nothing XCL puts past it would be reachable + let in_place = in_place && own && scanned >= public && max_console <= public; + let scanned = if in_place { public } else { scanned.max(public) }; + let total = if in_place { public } else { (scanned + EXTRA_SLOTS).max(max_console) }; let mut v: Vec = Vec::with_capacity(total + 1); v.push(orig); for i in 0..scanned { @@ -818,6 +917,28 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { v[1 + i] = super::guard::make_tracer(v[1 + i], name); } } + if in_place { + let register = || { + EXTS.lock().unwrap().get_or_insert_with(HashSet::new).insert(orig); + CLASSES.lock().unwrap().push(Class { orig, kind, ext: orig, iface, public, scanned }); + }; + match patch_in_place(orig as *mut usize, &v[1..], register) { + Ok(written) => { + if written { + crate::xlog_info!( + "D3D12.X: {} – {public} PC methods written into the runtime's own vtable (Wine: vkd3d-proton checks it; {kind:?}, PC vtable {})", + iface.name, + crate::modules::describe_address(orig) + ); + } + return orig; + } + Err(e) => { + crate::xlog_warn!("D3D12.X: {} – its vtable cannot be written ({e}): an extended copy instead", iface.name); + return make_class(obj, orig, kind, false); + } + } + } let leaked: &'static [usize] = Box::leak(v.into_boxed_slice()); let ext = leaked.as_ptr() as usize + 8; EXTS.lock().unwrap().get_or_insert_with(HashSet::new).insert(ext); @@ -5474,6 +5595,35 @@ mod this_first_tests { } } +#[cfg(test)] +mod in_place_tests { + use super::*; + + /// `patch_in_place` on a fake vtable: only the given entries are written (the next one – a + /// neighbouring table's – stays), `orig_fn` gives the entries from before for those and the + /// table's own past them, and a second patch of the same table writes nothing (its "originals" + /// would be XCL's own entries). No GPU. + #[test] + fn a_vtable_patched_in_place_keeps_its_originals_and_its_neighbour() { + const NEIGHBOUR: usize = 0x5e17_1e1; + let table: &'static mut [usize] = Box::leak(vec![0x10, 0x11, 0x12, 0x13, NEIGHBOUR, 0x15].into_boxed_slice()); + let t = table.as_mut_ptr(); + let obj = Box::into_raw(Box::new([t as usize])) as *mut c_void; + let registered = std::cell::Cell::new(0); + unsafe { + assert_eq!(in_place_original(t as usize, 0), None); + assert_eq!(patch_in_place(t, &[0x10, 0xA1, 0xA2, 0xA3], || registered.set(registered.get() + 1)), Ok(true)); + assert_eq!(std::slice::from_raw_parts(t, 6), &[0x10, 0xA1, 0xA2, 0xA3, NEIGHBOUR, 0x15]); + assert_eq!((0..6).map(|s| orig_fn(obj, s)).collect::>(), [0x10, 0x11, 0x12, 0x13, NEIGHBOUR, 0x15]); + assert_eq!(patch_in_place(t, &[0xB0, 0xB1], || registered.set(registered.get() + 1)), Ok(false)); + assert_eq!(std::slice::from_raw_parts(t, 6), &[0x10, 0xA1, 0xA2, 0xA3, NEIGHBOUR, 0x15]); + assert_eq!(orig_fn(obj, 1), 0x11); + drop(Box::from_raw(obj as *mut [usize; 1])); + } + assert_eq!(registered.get(), 1, "registered once, before the first write"); + } +} + #[cfg(test)] mod cache_report_tests { use super::*;