diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 2041690262..67bada0f19 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -733,7 +733,7 @@ pub fn run_with_statics( tex_back.push((i, rb)); } list.Close().map_err(e)?; - gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]); + submit_list(&gpu.queue, &list)?; gpu.value += 1; wait_for_submission(dev, &gpu.queue, &gpu.fence, gpu.value, "kernel dispatch")?; let mut p = std::ptr::null_mut(); @@ -1222,7 +1222,7 @@ fn draw_indexed_on( }; list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); list.Close().map_err(e)?; - queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]); + submit_list(&queue, &list)?; wait_for_submission(dev, &queue, &fence, 1, "draw")?; let mut p = std::ptr::null_mut(); readback.Map(0, None, Some(&mut p)).map_err(e)?; @@ -1425,7 +1425,7 @@ pub fn mesh_draw_split( list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); list.CopyBufferRegion(&readback, total, &res_buf, 0, res_bytes); list.Close().map_err(e)?; - gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]); + submit_list(&gpu.queue, &list)?; gpu.value += 1; wait_for_submission(dev, &gpu.queue, &gpu.fence, gpu.value, "mesh draw")?; let mut q = std::ptr::null_mut(); @@ -1561,7 +1561,7 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result Result<(), String> { + let cmd: ID3D12CommandList = list.cast().map_err(e)?; + let _guard = crate::hle::d3d12x::real::UnadoptGuard::new(cmd.as_raw()); + queue.ExecuteCommandLists(&[Some(cmd)]); + Ok(()) +} diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 8b81b85913..d10f1a5a49 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -198,7 +198,7 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { let key = queue as usize; if !s.fences.contains_key(&key) { let mut dev: Option = None; - let Some(f) = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| d.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()) else { return }; + let Some(f) = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| super::real::create_raw_fence(&d).ok()) else { return }; s.fences.insert(key, (f, 0)); } let (fence, value) = { @@ -452,12 +452,15 @@ mod tests { if !super::super::real::is_adopted(a) { super::super::real::adopt(a, super::super::real::Kind::CommandAllocator); } - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let list: ID3D12GraphicsCommandList = { + let _alloc_guard = super::super::real::UnadoptGuard::new(a); + dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap() + }; let l = list.as_raw(); created_on(l as usize, a as usize, D3D12_COMMAND_LIST_TYPE_DIRECT.0); list.Close().unwrap(); let lists = [Some(list.cast::().unwrap())]; - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let fence: ID3D12Fence = super::super::real::create_raw_fence(&dev).unwrap(); let done = |v: u64| { queue.Signal(&fence, v).unwrap(); let start = std::time::Instant::now(); @@ -467,7 +470,10 @@ mod tests { assert!(fence.GetCompletedValue() >= v, "the queue finishes"); }; - queue.ExecuteCommandLists(&lists); + { + let _list_guard = super::super::real::UnadoptGuard::new(l); + queue.ExecuteCommandLists(&lists); + } executed(queue.as_raw(), &[l]); done(1); @@ -476,7 +482,10 @@ mod tests { let second = current(a as usize); assert_ne!(second, a as usize, "the list still holds its recording: another PC allocator takes the place"); // … and submits the recording again - queue.ExecuteCommandLists(&lists); + { + let _list_guard = super::super::real::UnadoptGuard::new(l); + queue.ExecuteCommandLists(&lists); + } executed(queue.as_raw(), &[l]); done(2); assert!(dev.GetDeviceRemovedReason().is_ok(), "the recording was still there"); @@ -485,10 +494,14 @@ mod tests { let second_alloc = ID3D12CommandAllocator::from_raw_borrowed(&(second as *mut c_void)).unwrap().clone(); assert_eq!(reset_list(l as usize, a as usize, D3D12_COMMAND_LIST_TYPE_DIRECT.0, |pc| { assert_eq!(pc, second); + let _alloc_guard = super::super::real::UnadoptGuard::new(pc as *mut c_void); list.Reset(&second_alloc, None).map_or_else(|e| e.code().0, |_| 0) }), 0); list.Close().unwrap(); - queue.ExecuteCommandLists(&lists); + { + let _list_guard = super::super::real::UnadoptGuard::new(l); + queue.ExecuteCommandLists(&lists); + } executed(queue.as_raw(), &[l]); done(3); @@ -501,6 +514,7 @@ mod tests { // it stays (the next allocator at its address is its own) assert_eq!(reset_list(l as usize, a as usize, D3D12_COMMAND_LIST_TYPE_DIRECT.0, |pc| { assert_eq!(pc, a as usize); + let _alloc_guard = super::super::real::UnadoptGuard::new(pc as *mut c_void); list.Reset(&alloc, None).map_or_else(|e| e.code().0, |_| 0) }), 0); list.Close().unwrap(); diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 0b20bfbd6a..b0958615f0 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -173,7 +173,7 @@ pub(super) unsafe fn after(queue: *mut c_void, writes: Vec) { return; } let Some(dev) = dev else { return }; - let Ok(fence) = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) else { return }; + let Ok(fence) = super::real::create_raw_fence(&dev) else { return }; v.insert(QueueFence { fence, value: 0 }) } }; diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 18ddc684e7..a26cc7833f 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -54,7 +54,7 @@ impl Held { let key = q.as_raw() as usize; if !self.fences.contains_key(&key) { let mut dev: Option = None; - let made = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| d.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()); + let made = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| super::real::create_raw_fence(&d).ok()); let Some(f) = made else { ok = false; break; diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..4994d37d3e 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1661,7 +1661,7 @@ unsafe fn ensure_cell_fence(va: u64, dev: &ID3D12Device, dev_raw: usize) -> Opti } } } - let created: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let created: ID3D12Fence = real::create_raw_fence(&dev).ok()?; let mut g = SYNC_GRAPH.lock().unwrap(); let cell = g.get_or_insert_with(SyncGraph::default).cells.entry(va).or_default(); if cell.non_monotonic { @@ -2306,7 +2306,7 @@ pub(super) unsafe fn copy_scratch_submitted(queue: *mut c_void, lists: &[*mut c_ if let std::collections::hash_map::Entry::Vacant(entry) = cache.fences.entry(key) { let mut dev: Option = None; q.GetDevice(&mut dev).ok()?; - entry.insert((dev?.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()?, 0)); + entry.insert((real::create_raw_fence(&dev?).ok()?, 0)); } let (fence, value) = cache.fences.get_mut(&key)?; let next = *value + 1; @@ -2689,7 +2689,10 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { None => super::alloc_pool::title_reset(own).unwrap_or_else(|| real::reset_pc_allocator(own)), }; if hr >= 0 { - hr = super::alloc_pool::reset_list(seg as usize, own as usize, ty.0, |pc_alloc| pc:: i32>(seg, PC_RESET)(seg, pc_alloc, 0)); + hr = super::alloc_pool::reset_list(seg as usize, own as usize, ty.0, |pc_alloc| { + let _alloc_guard = real::UnadoptGuard::new(pc_alloc as *mut c_void); + pc:: i32>(seg, PC_RESET)(seg, pc_alloc, 0) + }); } real::preserve_vtable(seg, ext); if hr < 0 { @@ -2806,6 +2809,8 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ if let Some(spare) = super::title_list::pop_spare(wrapper) { let ext_spare = *(spare as *const usize); let reset_hr = super::alloc_pool::reset_list(spare as usize, alloc, ty.0, |pc_alloc| { + let _alloc_guard = real::UnadoptGuard::new(pc_alloc as *mut c_void); + let _pso_guard = real::UnadoptGuard::new(init_pso as *mut c_void); pc:: i32>(spare, PC_RESET)(spare, pc_alloc, init_pso) }); real::preserve_vtable(spare, ext_spare); @@ -2960,7 +2965,10 @@ unsafe fn deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_CO let emptied = |p: &*mut c_void| { let p = *p; let ext = *(p as *const usize); - let hr = super::alloc_pool::reset_list(p as usize, own, ty.0, |pc_alloc| pc:: i32>(p, PC_RESET)(p, pc_alloc, 0)); + let hr = super::alloc_pool::reset_list(p as usize, own, ty.0, |pc_alloc| { + let _alloc_guard = real::UnadoptGuard::new(pc_alloc as *mut c_void); + pc:: i32>(p, PC_RESET)(p, pc_alloc, 0) + }); real::preserve_vtable(p, ext); hr >= 0 }; @@ -3331,7 +3339,10 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if let Some((_, ref prior, _)) = kickoff_split { if !prior.is_empty() { execute_with_waits_on(q_raw, prior, |chunk| { - exec(q_raw, chunk.len() as u32, chunk.as_ptr()); + { + let _list_guards: Vec<_> = chunk.iter().filter_map(|&l| real::UnadoptGuard::new(l)).collect(); + exec(q_raw, chunk.len() as u32, chunk.as_ptr()); + } copy_scratch_submitted(q_raw, chunk); super::alloc_pool::executed(q_raw, chunk); signal_write64_fences(q_raw, chunk); @@ -3350,7 +3361,10 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } let one = [this]; - exec(q_raw, 1, one.as_ptr()); + { + let _list_guard = real::UnadoptGuard::new(this); + exec(q_raw, 1, one.as_ptr()); + } copy_scratch_submitted(q_raw, &one); super::alloc_pool::executed(q_raw, &one); signal_write64_pairs(q_raw, &write64_signals); @@ -3403,6 +3417,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let ext_closed = *(target as *const usize); let init_pso = super::pso_async::resolve_for_bind(bound_pso); let reset_hr = super::alloc_pool::reset_list(target as usize, alloc, list_type(target).0, |pc_alloc| { + let _alloc_guard = real::UnadoptGuard::new(pc_alloc as *mut c_void); + let _pso_guard = real::UnadoptGuard::new(init_pso as *mut c_void); pc:: i32>(target, PC_RESET)(target, pc_alloc, init_pso) }); real::preserve_vtable(target, ext_closed); @@ -4063,6 +4079,8 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 // (the PC allocator the title's allocator stands for now: `alloc_pool`) let ty = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).and_then(|s| s.list_type).map_or(-1, |t| t.0); let hr = super::alloc_pool::reset_list(this as usize, alloc, ty, |pc_alloc| { + let _alloc_guard = real::UnadoptGuard::new(pc_alloc as *mut c_void); + let _pso_guard = real::UnadoptGuard::new(resolved as *mut c_void); pc:: i32>(this, PC_RESET)(this, pc_alloc, resolved) }); real::preserve_vtable(this, ext); @@ -6948,15 +6966,18 @@ mod tests { let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(slot(2)); let exec: unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) = std::mem::transmute(*(*(q.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); - let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); - let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let gate: ID3D12Fence = real::create_raw_fence(dev).unwrap(); + let done: ID3D12Fence = real::create_raw_fence(dev).unwrap(); // Close, then submit as ExecuteCommandLists does: the PC lists the title's list stands for let submit = || { assert_eq!(close(w), 0); let mut segs = Vec::new(); assert!(super::super::title_list::push_segments(w, &mut segs)); let again = super::super::alloc_pool::note_resubmits(q.as_raw(), &segs); - exec(q.as_raw(), segs.len() as u32, segs.as_ptr()); + { + let _list_guards: Vec<_> = segs.iter().filter_map(|&l| real::UnadoptGuard::new(l)).collect(); + exec(q.as_raw(), segs.len() as u32, segs.as_ptr()); + } super::super::alloc_pool::executed(q.as_raw(), &segs); (segs, again) }; @@ -7020,7 +7041,7 @@ mod tests { let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); let raw: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &alloc, None).unwrap(); - let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let done: ID3D12Fence = real::create_raw_fence(&dev).unwrap(); let standin = 0x7E57_D001usize; static BUILD: AtomicBool = AtomicBool::new(false); @@ -7069,7 +7090,10 @@ mod tests { type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = std::mem::transmute(*(*(queue.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); - exec(queue.as_raw(), segs.len() as u32, segs.as_ptr()); + { + let _list_guards: Vec<_> = segs.iter().filter_map(|&l| real::UnadoptGuard::new(l)).collect(); + exec(queue.as_raw(), segs.len() as u32, segs.as_ptr()); + } queue.Signal(&done, 1).unwrap(); crate::gpu::fence::wait(&done, 1, &dev, None, 2000).expect("the split list runs"); @@ -7188,7 +7212,10 @@ mod tests { execute_with_waits_on(q_comp.as_raw(), &segs_c, |chunk| { type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = std::mem::transmute(*(*(q_comp.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); - exec(q_comp.as_raw(), chunk.len() as u32, chunk.as_ptr()); + { + let _guards: Vec<_> = chunk.iter().filter_map(|&l| real::UnadoptGuard::new(l)).collect(); + exec(q_comp.as_raw(), chunk.len() as u32, chunk.as_ptr()); + } signal_write64_fences(q_comp.as_raw(), chunk); if chunk.contains(&pc_c0) { cell_a.store(frame, Ordering::Release); @@ -7201,7 +7228,10 @@ mod tests { execute_with_waits_on(q_dir.as_raw(), &one_d, |chunk| { type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = std::mem::transmute(*(*(q_dir.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); - exec(q_dir.as_raw(), chunk.len() as u32, chunk.as_ptr()); + { + let _guards: Vec<_> = chunk.iter().filter_map(|&l| real::UnadoptGuard::new(l)).collect(); + exec(q_dir.as_raw(), chunk.len() as u32, chunk.as_ptr()); + } signal_write64_fences(q_dir.as_raw(), chunk); cell_b.store(frame, Ordering::Release); }); diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d47e67841e..3ab2538e41 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -947,7 +947,7 @@ unsafe fn new_presenter(queue: usize) -> Option { let actual_slots = if spare_alloc.is_some() { 2 } else { 1 }; let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).ok()?; list.Close().ok()?; - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let fence: ID3D12Fence = super::real::create_raw_fence(dev).ok()?; let event = CreateEventW(None, false, false, None).ok()?; Some(Presenter { queue, dev: dev.clone(), sc: None, w: 0, h: 0, fmt: DXGI_FORMAT_UNKNOWN, diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 91085d3933..6f148d2996 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -622,14 +622,73 @@ struct Class { static CLASSES: Mutex> = Mutex::new(Vec::new()); static EXTS: Mutex>> = Mutex::new(None); +const EXT_FAST_CAP: usize = 64; +static EXT_FAST: [AtomicUsize; EXT_FAST_CAP] = [const { AtomicUsize::new(0) }; EXT_FAST_CAP]; +static EXT_FAST_N: AtomicUsize = AtomicUsize::new(0); +static NATIVE_FAST: [AtomicUsize; EXT_FAST_CAP] = [const { AtomicUsize::new(0) }; EXT_FAST_CAP]; +static NATIVE_FAST_N: AtomicUsize = AtomicUsize::new(0); +static NATIVE_FAST_LOCK: Mutex<()> = Mutex::new(()); + +fn register_ext(ext: usize) { + let mut g = EXTS.lock().unwrap(); + if g.get_or_insert_with(HashSet::new).insert(ext) { + let n = EXT_FAST_N.load(Ordering::Relaxed); + if n < EXT_FAST_CAP { + EXT_FAST[n].store(ext, Ordering::Relaxed); + EXT_FAST_N.store(n + 1, Ordering::Release); + } + } +} + +fn is_ext_fast(v: usize) -> bool { + let n = EXT_FAST_N.load(Ordering::Acquire); + for slot in &EXT_FAST[..n.min(EXT_FAST_CAP)] { + if slot.load(Ordering::Relaxed) == v { + return true; + } + } + n >= EXT_FAST_CAP && is_ext(v) +} + +fn register_native(orig: usize) { + if is_known_native(orig) { + return; + } + let _g = NATIVE_FAST_LOCK.lock().unwrap(); + let n = NATIVE_FAST_N.load(Ordering::Relaxed); + for slot in &NATIVE_FAST[..n.min(EXT_FAST_CAP)] { + if slot.load(Ordering::Relaxed) == orig { + return; + } + } + if n < EXT_FAST_CAP { + NATIVE_FAST[n].store(orig, Ordering::Relaxed); + NATIVE_FAST_N.store(n + 1, Ordering::Release); + } +} + +fn is_known_native(v: usize) -> bool { + let n = NATIVE_FAST_N.load(Ordering::Acquire); + for slot in &NATIVE_FAST[..n.min(EXT_FAST_CAP)] { + if slot.load(Ordering::Relaxed) == v { + return true; + } + } + false +} unsafe fn vt(obj: *mut c_void) -> *const usize { - *(obj as *const *const usize) + (*(obj as *const AtomicUsize)).load(Ordering::Acquire) as *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 crate::util::under_wine() && is_known_native(ext as usize) { + // Another thread's UnadoptGuard temporarily restored the native vtable on this + // shared object (e.g. a pipeline state); `ext` is already the original table. + return *ext.add(slot); + } let orig = *ext.sub(1) as *const usize; *orig.add(slot) } @@ -712,6 +771,101 @@ pub(super) unsafe fn readopt(obj: *mut c_void, kind: Kind) { *(obj as *mut usize) = class_for(obj, orig, kind); } +/// Active `UnadoptGuard` counts per object pointer so concurrent guards on a shared object +/// (such as a pipeline state, heap, or resource) keep the native vtable installed until the +/// last guard drops, while pinning a COM reference (`AddRef` before unadopt, hooked `Release` +/// after restoring the extended vtable) so a concurrent `Release` through the native vtable +/// cannot drop the refcount to zero and bypass XCL's final-release cleanup (`pso_release`, +/// `heap_release`, `res_release`, `cl_release`, `alloc_release`). +static UNADOPTED: Mutex>> = Mutex::new(None); + +/// Temporarily restores an adopted object's native vtable for a call into `d3d12core.dll` +/// (vkd3d-proton validates `iface->lpVtbl` on command allocators and command lists). +pub(crate) struct UnadoptGuard { + obj: *mut c_void, +} + +impl UnadoptGuard { + pub(crate) unsafe fn new(obj: *mut c_void) -> Option { + if !crate::util::under_wine() || obj.is_null() || (obj as usize) & 7 != 0 || !crate::gpu::shader::readable(obj as usize, 8) { + return None; + } + let mut g = UNADOPTED.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + if let Some((_, count)) = map.get_mut(&(obj as usize)) { + *count += 1; + return Some(Self { obj }); + } + let cur = (*(obj as *const AtomicUsize)).load(Ordering::Acquire); + if !is_ext_fast(cur) { + return None; + } + let orig = *(cur as *const usize).sub(1); + // Pin +1 COM reference via native AddRef before exposing `orig`, so any concurrent + // Release observing the native vtable sees refcount >= 2 and cannot finalize the object. + let add_ref: RefFn = std::mem::transmute(*(orig as *const usize).add(1)); + add_ref(obj); + register_native(orig); + (*(obj as *const AtomicUsize)).store(orig, Ordering::Release); + map.insert(obj as usize, (cur, 1)); + Some(Self { obj }) + } + + #[cfg(test)] + unsafe fn enter(obj: *mut c_void) -> Self { + let mut g = UNADOPTED.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + if let Some((_, count)) = map.get_mut(&(obj as usize)) { + *count += 1; + return Self { obj }; + } + let ext = (*(obj as *const AtomicUsize)).load(Ordering::Acquire); + let orig = *(ext as *const usize).sub(1); + let add_ref: RefFn = std::mem::transmute(*(orig as *const usize).add(1)); + add_ref(obj); + register_native(orig); + (*(obj as *const AtomicUsize)).store(orig, Ordering::Release); + map.insert(obj as usize, (ext, 1)); + Self { obj } + } +} + +impl Drop for UnadoptGuard { + fn drop(&mut self) { + let release_ext = { + let mut g = UNADOPTED.lock().unwrap(); + if let Some(map) = g.as_mut() { + if let Some((ext, count)) = map.get_mut(&(self.obj as usize)) { + *count -= 1; + if *count == 0 { + let ext = *ext; + map.remove(&(self.obj as usize)); + unsafe { + (*(self.obj as *const AtomicUsize)).store(ext, Ordering::Release); + } + Some(ext) + } else { + None + } + } else { + None + } + } else { + None + } + }; + // Release our pinned reference outside `UNADOPTED` via XCL's hooked Release slot so if + // another thread dropped the last title reference while the guard was active, the final + // 1 -> 0 transition always runs XCL's cleanup hook. + if let Some(ext) = release_ext { + unsafe { + let rel: RefFn = std::mem::transmute(*(ext as *const usize).add(2)); + rel(self.obj); + } + } + } +} + /// Give a genuine D3D12 object the extended vtable for `kind`. pub unsafe fn adopt(obj: *mut c_void, kind: Kind) { if obj.is_null() { @@ -834,7 +988,7 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { } 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); + register_ext(ext); crate::xlog_info!( "D3D12.X: {} – {public} PC methods, {} internal slots under the guard, +{EXTRA_SLOTS} stubs ({kind:?}, PC vtable {})", iface.name, @@ -2902,7 +3056,12 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ("Close", cl_close as usize), ("Reset", cl_reset as usize), ]), - Kind::CommandQueue => v.extend_from_slice(&[("Release", q_release as usize), ("ExecuteCommandLists", q_execute_command_lists as usize)]), + Kind::CommandQueue => v.extend_from_slice(&[ + ("Release", q_release as usize), + ("ExecuteCommandLists", q_execute_command_lists as usize), + ("Signal", q_signal_pc as usize), + ("Wait", q_wait_pc as usize), + ]), Kind::CommandAllocator => v.extend_from_slice(&[("Release", alloc_release as usize), ("Reset", alloc_reset as usize)]), Kind::Resource => v.extend_from_slice(&[ ("Release", res_release as usize), @@ -2983,7 +3142,11 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, in let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "Reset"))); let resolved = super::pso_async::resolve_for_bind(initial_state as usize) as *mut c_void; - let hr = f(this, allocator, resolved); + let hr = { + let _alloc_guard = UnadoptGuard::new(allocator); + let _pso_guard = UnadoptGuard::new(resolved); + f(this, allocator, resolved) + }; preserve_vtable(this, ext); if hr >= 0 { super::list_x::on_pc_reset(this); @@ -3160,7 +3323,12 @@ macro_rules! creator { creator!(dev_create_command_queue, "CreateCommandQueue", Kind::CommandQueue, [a1]); creator!(dev_create_command_queue1, "CreateCommandQueue1", Kind::CommandQueue, [a1, a2]); creator!(dev_create_command_allocator, "CreateCommandAllocator", Kind::CommandAllocator, [a1]); -creator!(dev_create_command_list, "CreateCommandList", Kind::CommandList, [a1, a2, a3, a4]); +creator!(dev_create_command_list_inner, "CreateCommandList", Kind::CommandList, [a1, a2, a3, a4]); +pub(super) unsafe extern "system" fn dev_create_command_list(this: *mut c_void, a1: usize, a2: usize, a3: usize, a4: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let _alloc_guard = UnadoptGuard::new(a3 as *mut c_void); + let _pso_guard = UnadoptGuard::new(a4 as *mut c_void); + dev_create_command_list_inner(this, a1, a2, a3, a4, riid, ppv) +} creator!(dev_create_command_list1, "CreateCommandList1", Kind::CommandList, [a1, a2, a3]); /// Create a raw adopted PC `ID3D12GraphicsCommandList` without wrapping it in `title_list` @@ -3182,6 +3350,8 @@ pub(super) unsafe fn create_raw_pc_command_list( type F = unsafe extern "system" fn(*mut c_void, u32, D3D12_COMMAND_LIST_TYPE, usize, usize, *const GUID, *mut *mut c_void) -> HRESULT; let slot = layout::slot(layout::find("ID3D12Device")?, "CreateCommandList")?; let f: F = std::mem::transmute(*vt(dev).add(slot)); + let _alloc_guard = UnadoptGuard::new(alloc as *mut c_void); + let _pso_guard = UnadoptGuard::new(init_pso as *mut c_void); let hr = f(dev, 0, ty, alloc, init_pso, &iid, &mut out); if hr >= 0 && !out.is_null() { adopt(out, Kind::CommandList); @@ -3194,7 +3364,11 @@ creator!(dev_create_descriptor_heap, "CreateDescriptorHeap", Kind::DescriptorHea creator!(dev_create_committed_resource, "CreateCommittedResource", Kind::Resource, [a1, a2, a3, a4, a5]); creator!(dev_create_committed_resource1, "CreateCommittedResource1", Kind::Resource, [a1, a2, a3, a4, a5, a6]); creator!(dev_create_committed_resource2, "CreateCommittedResource2", Kind::Resource, [a1, a2, a3, a4, a5, a6]); -creator!(dev_create_placed_resource, "CreatePlacedResource", Kind::Resource, [a1, a2, a3, a4, a5]); +creator!(dev_create_placed_resource_inner, "CreatePlacedResource", Kind::Resource, [a1, a2, a3, a4, a5]); +pub(super) unsafe extern "system" fn dev_create_placed_resource(this: *mut c_void, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let _heap_guard = UnadoptGuard::new(a1 as *mut c_void); + dev_create_placed_resource_inner(this, a1, a2, a3, a4, a5, riid, ppv) +} /// D3D12_RESOURCE_STATES the PC knows (as `list_x::PC_STATES`) pub(super) const PC_RESOURCE_STATES: u32 = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x40 | 0x80 | 0x100 | 0x200 | 0x400 | 0x800 | 0x1000 | 0x2000 | 0xF_0000 | 0x20_0000 | 0x40_0000 | 0x80_0000 | 0x100_0000; @@ -3338,7 +3512,11 @@ unsafe fn pc_allocation_size(device: *mut c_void, d: &[u8; 0x38]) -> u64 { f(device, &mut r, 0, 1, &safe); r[0] } -creator!(dev_create_placed_resource1, "CreatePlacedResource1", Kind::Resource, [a1, a2, a3, a4, a5]); +creator!(dev_create_placed_resource1_inner, "CreatePlacedResource1", Kind::Resource, [a1, a2, a3, a4, a5]); +unsafe extern "system" fn dev_create_placed_resource1(this: *mut c_void, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let _heap_guard = UnadoptGuard::new(a1 as *mut c_void); + dev_create_placed_resource1_inner(this, a1, a2, a3, a4, a5, riid, ppv) +} creator!(pc_create_reserved_resource, "CreateReservedResource", Kind::Resource, [a1, a2, a3]); creator!(pc_create_reserved_resource1, "CreateReservedResource1", Kind::Resource, [a1, a2, a3, a4]); @@ -3556,6 +3734,108 @@ unsafe extern "system" fn mem_heap_release(this: *mut c_void) -> u32 { } creator!(dev_create_fence_pc, "CreateFence", Kind::Fence, [a1, a2]); +/// Thin COM proxy around `ID3D12Fence1` used under Wine/vkd3d-proton so the underlying +/// fence's native `lpVtbl` stays intact (`vkd3d-proton` compares `fence->lpVtbl` against +/// `&d3d12_fence_vtbl` in `CommandQueue::Signal` / `Wait` and on its queue thread). +#[repr(C)] +struct FenceProxy { + vt: usize, + pc: *mut c_void, +} + +fn fence_proxy_vtable() -> usize { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| { + const SLOTS: usize = 32; + let mut v = vec![0usize; SLOTS]; + for slot in 0..12 { + // mov rcx, [rcx + 8]; mov rax, [rcx]; jmp [rax + slot * 8] + let mut c = vec![0x48u8, 0x8B, 0x49, 0x08, 0x48, 0x8B, 0x01, 0xFF, 0xA0]; + c.extend_from_slice(&((slot * 8) as u32).to_le_bytes()); + let p = crate::stubs::alloc_code(c.len()); + unsafe { std::ptr::copy_nonoverlapping(c.as_ptr(), p, c.len()) }; + v[slot] = p as usize; + } + v[0] = fence_proxy_qi as usize; + v[2] = fence_proxy_release as usize; + v[10] = fence_proxy_signal as usize; + v[12] = super::fence_x::completed_value_address as usize; + for slot in 13..SLOTS { + let (addr, _) = stubs::make_stub_info(DLL, &format!("ID3D12Fence1::#{slot} (not on PC)"), 0); + v[slot] = addr; + } + Box::leak(v.into_boxed_slice()).as_ptr() as usize + }) +} + +unsafe extern "system" fn fence_proxy_qi(this: *mut c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let pc = (*(this as *const FenceProxy)).pc; + let f: QiFn = std::mem::transmute(*vt(pc)); + let hr = f(pc, riid, ppv); + if hr >= 0 && !ppv.is_null() && *ppv == pc { + *ppv = this; + } else if hr == E_NOINTERFACE && !riid.is_null() { + let s = layout::guid_string(&*riid); + if UNKNOWN_IIDS.lock().unwrap().insert(s.clone()) { + crate::xlog_warn!("D3D12.X: QueryInterface({s}) – interface unknown on the PC (console-only?)"); + } + } + hr +} + +unsafe extern "system" fn fence_proxy_release(this: *mut c_void) -> u32 { + let pc = (*(this as *const FenceProxy)).pc; + let f: RefFn = std::mem::transmute(*vt(pc).add(2)); + let n = f(pc); + if n == 0 { + drop(Box::from_raw(this as *mut FenceProxy)); + } + n +} + +unsafe extern "system" fn fence_proxy_signal(this: *mut c_void, value: u64) -> HRESULT { + let pc = (*(this as *const FenceProxy)).pc; + let f: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(*vt(pc).add(10)); + let hr = f(pc, value); + super::fence_x::note_cpu_signal(this as usize); + hr +} + +unsafe fn wrap_fence_proxy(pc: *mut c_void) -> *mut c_void { + Box::into_raw(Box::new(FenceProxy { vt: fence_proxy_vtable(), pc })) as *mut c_void +} + +unsafe fn unwrap_fence(p: *mut c_void) -> *mut c_void { + if crate::util::under_wine() { unwrap_fence_proxy(p) } else { p } +} + +unsafe fn unwrap_fence_proxy(p: *mut c_void) -> *mut c_void { + if !p.is_null() && crate::gpu::shader::readable(p as usize, 16) && *(p as *const usize) == fence_proxy_vtable() { + (*(p as *const FenceProxy)).pc + } else { + p + } +} + +/// Create an un-adopted, un-proxied `ID3D12Fence` for XCL's own internal queue tracking +/// (`late_release`, `alloc_pool`, `list_x`, `cpu_writes`, `present`, `vram`, `drain_gpu`) +/// so under Wine/vkd3d-proton it can be signalled on raw internal queues (`sparse::queue()`) +/// and passed to native APIs without hitting `FenceProxy` vtable mismatches. +pub(super) unsafe fn create_raw_fence(dev: &ID3D12Device) -> windows::core::Result { + let raw = dev.as_raw(); + if is_ext(vt(raw) as usize) { + type F = unsafe extern "system" fn(*mut c_void, u64, D3D12_FENCE_FLAGS, *const GUID, *mut *mut c_void) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(raw, slot_of(raw, "CreateFence"))); + let mut out: *mut c_void = std::ptr::null_mut(); + let hr = f(raw, 0, D3D12_FENCE_FLAG_NONE, (&ID3D12Fence::IID as *const windows::core::GUID).cast(), &mut out); + if hr < 0 { + return Err(windows::core::Error::from_hresult(windows::core::HRESULT(hr))); + } + return Ok(ID3D12Fence::from_raw(out)); + } + dev.CreateFence(0, D3D12_FENCE_FLAG_NONE) +} + /// fences created through the device (AddRef'd: they are released at the end only) /// (a read-write lock: `is_fence` reads it on every queue call, and `end_title` reads it with /// the title's threads suspended – a reader that holds it then blocks no other reader) @@ -3563,7 +3843,21 @@ static FENCES: std::sync::RwLock> = std::sync::RwLock::new(Vec::new() /// CreateFence: as on the PC; the fence is remembered for `end_title` unsafe extern "system" fn dev_create_fence(this: *mut c_void, value: usize, flags: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - let hr = dev_create_fence_pc(this, value, flags, riid, ppv); + let hr = if crate::util::under_wine() { + type F = unsafe extern "system" fn(*mut c_void, usize, usize, *const GUID, *mut *mut c_void) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateFence"))); + let mut hr = f(this, value, flags, riid, ppv); + if hr == E_NOINTERFACE { + let iid = pc_iid(Kind::Fence); + hr = f(this, value, flags, &iid, ppv); + } + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + *ppv = wrap_fence_proxy(*ppv); + } + hr + } else { + dev_create_fence_pc(this, value, flags, riid, ppv) + }; if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { let add: RefFn = std::mem::transmute(*vt(*ppv).add(1)); add(*ppv); @@ -6816,7 +7110,10 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32) as i32); } let desc = copy.as_ref().map_or(desc, |c| c as *const _ as *const c_void); - f(this, res, desc, handle); + { + let _res_guard = UnadoptGuard::new(res); + f(this, res, desc, handle); + } super::present::note_rtv(handle, res); if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); @@ -6878,7 +7175,10 @@ unsafe extern "system" fn cl_set_pipeline_state(this: *mut c_void, pso: *mut c_v type F = unsafe extern "system" fn(*mut c_void, *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "SetPipelineState"))); let bound = super::pso_async::resolve(pso as usize); - f(this, bound as *mut c_void); + { + let _pso_guard = UnadoptGuard::new(bound as *mut c_void); + f(this, bound as *mut c_void); + } super::dred::mark_pipeline(this, pso as usize, bound); super::list_x::on_set_pipeline_state(this, pso as usize); } @@ -6894,10 +7194,13 @@ unsafe extern "system" fn cl_set_marker(this: *mut c_void, metadata: u32, data: unsafe extern "system" fn cl_clear_state(this: *mut c_void, pso: *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ClearState"))); - let bound = super::pso_async::resolve_for_bind(pso as usize); - f(this, bound as *mut c_void); + let resolved = super::pso_async::resolve_for_bind(pso as usize); + { + let _pso_guard = UnadoptGuard::new(resolved as *mut c_void); + f(this, resolved as *mut c_void); + } if !pso.is_null() { - super::dred::mark_pipeline(this, pso as usize, bound); + super::dred::mark_pipeline(this, pso as usize, resolved); } super::list_x::on_clear_state(this, pso as usize); super::bind::clear_state(this, pso as usize); @@ -6968,7 +7271,10 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT { type F = unsafe extern "system" fn(*mut c_void) -> HRESULT; let f: F = std::mem::transmute(orig_fn(raw, slot_of(raw, "Reset"))); - let hr = f(raw); + let hr = { + let _alloc_guard = UnadoptGuard::new(raw); + f(raw) + }; if hr >= 0 { dispatch_chain::allocator_reset(raw as usize); } hr } @@ -7068,7 +7374,8 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a super::list_x::break_cycles_before_title_signal(this as usize, a1, a2 as u64); } let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(pc(if older == 14 { PC_SIGNAL } else { PC_WAIT })); - let hr = f(this, a1, a2); + let raw_fence = unwrap_fence(a1 as *mut c_void) as usize; + let hr = f(this, raw_fence, a2); if hr >= 0 { if older == 14 { super::fence_x::note_queue_signal(a1, a2 as u64); @@ -7154,6 +7461,18 @@ macro_rules! queue_slots { } queue_slots!(14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35); +/// command queue #14 Signal (PC callers, e.g. XCL's own drain/present/sparse helpers) +unsafe extern "system" fn q_signal_pc(this: *mut c_void, fence: *mut c_void, value: u64) -> HRESULT { + let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "Signal"))); + f(this, unwrap_fence(fence), value) +} + +/// command queue #15 Wait (PC callers) +unsafe extern "system" fn q_wait_pc(this: *mut c_void, fence: *mut c_void, value: u64) -> HRESULT { + let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "Wait"))); + f(this, unwrap_fence(fence), value) +} + /// command queue #23 SignalX(fence, value, flush flags): Signal with the console's cache flush /// options – the PC's Signal makes the queue's writes visible itself. (A stub that signalled /// nothing left Fortnite's render fences pending: its render thread waited, textures were @@ -7162,7 +7481,7 @@ unsafe extern "system" fn q_signal_x(this: *mut c_void, fence: *mut c_void, valu const PC_SIGNAL: usize = 14; super::list_x::break_cycles_before_title_signal(this as usize, fence as usize, value); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, PC_SIGNAL)); - let hr = f(this, fence, value); + let hr = f(this, unwrap_fence(fence), value); if hr >= 0 { super::fence_x::note_queue_signal(fence as usize, value); super::list_x::note_title_queue_signal(this as usize, fence as usize, value); @@ -7208,7 +7527,10 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis super::list_x::note_queue_for_lists(this as usize, &mapped); super::list_x::execute_with_waits_on(this, &mapped, |chunk| { let _ = super::alloc_pool::note_resubmits(this, chunk); - f(this, chunk.len() as u32, chunk.as_ptr()); + { + let _list_guards: Vec<_> = chunk.iter().filter_map(|&l| UnadoptGuard::new(l)).collect(); + f(this, chunk.len() as u32, chunk.as_ptr()); + } super::list_x::copy_scratch_submitted(this, chunk); super::alloc_pool::executed(this, chunk); super::list_x::signal_write64_fences(this, chunk); @@ -7235,7 +7557,7 @@ pub fn drain_gpu() { let qr = q as *mut c_void; let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&qr) else { continue }; let submit = || { - let f: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE) + let f: ID3D12Fence = create_raw_fence(dev) .map_err(|e| fence::api_error(dev, "CreateFence", e))?; q.Signal(&f, 1).map_err(|e| fence::api_error(dev, "Signal", e))?; Ok(f) @@ -8905,3 +9227,166 @@ void main() { } } +#[cfg(test)] +mod wine_vtable_tests { + use super::*; + use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + + #[test] + fn unadopt_guard_restores_native_vtable_and_reapplies_extended_on_drop() { + #[repr(C)] + struct FakeObj { + vt: usize, + refs: AtomicU32, + hook_releases: AtomicU32, + } + unsafe extern "system" fn native_add_ref(this: *mut c_void) -> u32 { + (*(this as *const FakeObj)).refs.fetch_add(1, Ordering::AcqRel) + 1 + } + unsafe extern "system" fn native_release(this: *mut c_void) -> u32 { + (*(this as *const FakeObj)).refs.fetch_sub(1, Ordering::AcqRel) - 1 + } + unsafe extern "system" fn hooked_release(this: *mut c_void) -> u32 { + (*(this as *const FakeObj)).hook_releases.fetch_add(1, Ordering::AcqRel); + native_release(this) + } + + // Place a zero word immediately before `orig_vt` (matching vkd3d-proton's layout) so a + // buggy `orig_fn` that reads `native[-1]` would dereference null instead of `orig_vt[2]`. + let mut orig_buf = [0usize; 9]; + orig_buf[1 + 1] = native_add_ref as usize; + orig_buf[1 + 2] = native_release as usize; + let orig_vt = unsafe { orig_buf.as_ptr().add(1) as usize }; + let mut ext_buf = [0usize; 9]; + ext_buf[0] = orig_vt; + ext_buf[1 + 1] = native_add_ref as usize; + ext_buf[1 + 2] = hooked_release as usize; + let ext_vt = unsafe { ext_buf.as_ptr().add(1) as usize }; + let mut fake = FakeObj { vt: ext_vt, refs: AtomicU32::new(1), hook_releases: AtomicU32::new(0) }; + let obj = &mut fake as *mut FakeObj as *mut c_void; + + unsafe { + assert_eq!(*(obj as *const usize), ext_vt); + { + let g1 = UnadoptGuard::enter(obj); + assert_eq!(*(obj as *const usize), orig_vt); + assert_eq!(fake.refs.load(Ordering::Acquire), 2, "guard must pin +1 COM ref"); + // Overlapping guard on the same shared object must keep the native vtable until + // the last guard drops. + let g2 = UnadoptGuard::enter(obj); + assert_eq!(fake.refs.load(Ordering::Acquire), 2, "nested guard reuses outer ref pin"); + drop(g1); + assert_eq!(*(obj as *const usize), orig_vt, "first drop must not restore ext while g2 is active"); + if crate::util::under_wine() { + assert_eq!(orig_fn(obj, 2), native_release as usize, "orig_fn must read native slot while guarded"); + } + drop(g2); + } + assert_eq!(*(obj as *const usize), ext_vt); + assert_eq!(fake.refs.load(Ordering::Acquire), 1, "refcount restored on drop"); + assert_eq!(fake.hook_releases.load(Ordering::Acquire), 1, "drop releases via hooked Release slot"); + } + } + + /// Regression for concurrent COM `Release` while `UnadoptGuard` temporarily exposes the + /// native vtable on a shared object: even if another thread loads the native vtable and calls + /// native `Release` directly, the guard's pinned reference keeps the object alive (rc >= 1) + /// and the guard's drop restores the extended vtable and performs the final 1 -> 0 release + /// through XCL's hooked `Release` so cleanup bookkeeping is never bypassed. + #[test] + fn concurrent_release_during_unadopt_guard_still_runs_hooked_cleanup() { + #[repr(C)] + struct SharedPso { + vt: usize, + refs: AtomicU32, + cleanup_ran: AtomicU32, + } + unsafe extern "system" fn native_add_ref(this: *mut c_void) -> u32 { + (*(this as *const SharedPso)).refs.fetch_add(1, Ordering::AcqRel) + 1 + } + unsafe extern "system" fn native_release(this: *mut c_void) -> u32 { + (*(this as *const SharedPso)).refs.fetch_sub(1, Ordering::AcqRel) - 1 + } + unsafe extern "system" fn hooked_pso_release(this: *mut c_void) -> u32 { + let f: RefFn = std::mem::transmute(orig_fn(this, 2)); + let rc = f(this); + if rc == 0 { + (*(this as *const SharedPso)).cleanup_ran.fetch_add(1, Ordering::AcqRel); + } + rc + } + + let mut orig_buf = [0usize; 9]; + orig_buf[1 + 1] = native_add_ref as usize; + orig_buf[1 + 2] = native_release as usize; + let orig_vt = unsafe { orig_buf.as_ptr().add(1) as usize }; + let mut ext_buf = [0usize; 9]; + ext_buf[0] = orig_vt; + ext_buf[1 + 1] = native_add_ref as usize; + ext_buf[1 + 2] = hooked_pso_release as usize; + let ext_vt = unsafe { ext_buf.as_ptr().add(1) as usize }; + + let mut pso = Box::new(SharedPso { vt: ext_vt, refs: AtomicU32::new(1), cleanup_ran: AtomicU32::new(0) }); + let raw = pso.as_mut() as *mut SharedPso as usize; + + unsafe { + let guard = UnadoptGuard::enter(raw as *mut c_void); + // Concurrent thread loads `*obj` during the guard window (seeing `orig_vt`) and + // invokes COM slot #2 (`Release`) directly through the native vtable. + let concurrent_rc = std::thread::spawn(move || { + let p = raw as *mut c_void; + let vt_seen = (*(p as *const AtomicUsize)).load(Ordering::Acquire); + assert_eq!(vt_seen, orig_vt, "concurrent caller observes native vtable during guard"); + let rel: RefFn = std::mem::transmute(*(vt_seen as *const usize).add(2)); + rel(p) + }) + .join() + .unwrap(); + assert_eq!(concurrent_rc, 1, "pinned ref must prevent native Release from finalizing the object"); + assert_eq!(pso.cleanup_ran.load(Ordering::Acquire), 0); + + drop(guard); + assert_eq!((*(raw as *const AtomicUsize)).load(Ordering::Acquire), ext_vt, "extended vtable restored"); + assert_eq!(pso.refs.load(Ordering::Acquire), 0, "final reference dropped on guard exit"); + assert_eq!(pso.cleanup_ran.load(Ordering::Acquire), 1, "hooked pso_release cleanup must run on 1 -> 0"); + } + } + + #[test] + fn fence_proxy_forwards_signal_unwraps_and_frees_on_final_release() { + #[repr(C)] + struct FakeFence { + vt: *const usize, + refs: AtomicU32, + signaled: AtomicU64, + } + unsafe extern "system" fn fake_release(this: *mut c_void) -> u32 { + (*(this as *const FakeFence)).refs.fetch_sub(1, Ordering::Relaxed) - 1 + } + unsafe extern "system" fn fake_signal(this: *mut c_void, value: u64) -> HRESULT { + (*(this as *const FakeFence)).signaled.store(value, Ordering::Relaxed); + 0 + } + + let mut vt = [0usize; 16]; + vt[2] = fake_release as usize; + vt[10] = fake_signal as usize; + let fake = Box::new(FakeFence { vt: vt.as_ptr(), refs: AtomicU32::new(1), signaled: AtomicU64::new(0) }); + let raw = &*fake as *const FakeFence as *mut c_void; + + unsafe { + let proxy = wrap_fence_proxy(raw); + assert_ne!(proxy, raw); + assert_eq!(unwrap_fence_proxy(proxy), raw); + assert_eq!(unwrap_fence_proxy(raw), raw); + assert_eq!(*(raw as *const usize), vt.as_ptr() as usize, "native fence vtable must remain unmodified"); + + let signal_fn: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(*(*(proxy as *const *const usize)).add(10)); + assert_eq!(signal_fn(proxy, 42), 0); + assert_eq!(fake.signaled.load(Ordering::Relaxed), 42); + + let release_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(proxy as *const *const usize)).add(2)); + assert_eq!(release_fn(proxy), 0); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index b7560f861e..dd2a340d4d 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -523,8 +523,8 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { } let made = (|| -> windows::core::Result { let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; - let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let fence: ID3D12Fence = super::real::create_raw_fence(dev)?; + let rb_fence: ID3D12Fence = super::real::create_raw_fence(dev)?; let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None)?; let mut slots = Vec::with_capacity(UPLOAD_SLOTS); for _ in 0..UPLOAD_SLOTS { @@ -1428,7 +1428,7 @@ impl State { if q.GetDevice(&mut qdev).is_err() || qdev.as_ref().is_none_or(|d| d.as_raw() != self.dev.as_raw()) { return true; } - match self.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) { + match super::real::create_raw_fence(&self.dev) { Ok(fence) => { self.queue_fences.insert(key, (q.clone(), fence, 0)); true diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index ea49ce6b89..409c180482 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -626,7 +626,7 @@ impl Pages { } let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).ok()?; let _ = queue.SetName(windows::core::w!("xcl vram tile-mapping queue")); - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let fence: ID3D12Fence = super::real::create_raw_fence(&dev).ok()?; crate::xlog_info!("D3D12.X: textures in title memory: tiled resources on 64 KiB pages of video memory, one per page of the title's"); Some(Pages { queue, @@ -1181,7 +1181,7 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla if newly_reclaimed.is_empty() && !map.contains_key(&dev_key) { return; } let rq = map.entry(dev_key).or_insert_with(RetireQueue::new); let before = rq.batches.len(); - let immediate = rq.retire_with(newly_reclaimed, unmap_mark, &queues, || dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok(), |q, f, v| q.Signal(f, v).is_ok()); + let immediate = rq.retire_with(newly_reclaimed, unmap_mark, &queues, || super::real::create_raw_fence(dev).ok(), |q, f, v| q.Signal(f, v).is_ok()); let (done, pruned) = rq.sweep_with(&live_keys, |f| f.GetCompletedValue()); RETIRING_BATCHES.fetch_add(rq.batches.len().wrapping_sub(before), std::sync::atomic::Ordering::AcqRel); (immediate, done, pruned)