From 0797336ee0c4ef4d24b79f9c65aa5bf1c51fa92d Mon Sep 17 00:00:00 2001 From: John Howard <49204095+Royalflamejlh@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:40:54 -0700 Subject: [PATCH] D3D12.X: keep vkd3d-proton's vtables under Wine and wrap the title's fences (#175) vkd3d-proton takes an object only with its own vtable. For command lists and allocators it checks at run time and returns NULL, which its submit path then reads (`NULL+0x2b28`); for heaps, resources, descriptor and query heaps, root signatures, pipeline states and command signatures an assertion ends the process; a fence is cast without a check on its queue thread. Under Wine only: - the assert-checked classes keep the runtime's table and XCL's PC slots are written into it, with the entries it had kept for `orig_fn`; - `UnadoptGuard` gives a list, allocator, heap or pipeline its native table back for the length of the host call that takes it as an argument; - the title's fences are thin proxies over the runtime's fence, unwrapped at the queue's Signal and Wait and the device's CreateSharedHandle and SetEventOnMultipleFenceCompletion; their GetCompletedValue, SetEventOnCompletion and Signal run XCL's fence hooks on the runtime's fence, as an adopted fence's do on Windows. XCL's own fences (`create_raw_fence`, and those made in its own work) stay the runtime's, as `main` leaves them unadopted. This is #867 and #2477 by gustavsi, which were closed unmerged, carried onto the current `main`: the submit, fence and reset sites `main` has gained since (`native_queue_execute`, the sparse queues, the two-pass feedback poll, the own-work submit, the retire and upload fences) get the same guard or raw fence. One test new on `main` signalled a device fence on a PC queue and takes a raw fence now. On Windows nothing changes: `under_wine()` gates each branch. Co-authored-by: gustavsi <86445165+gustavsi@users.noreply.github.com> Co-Authored-By: Claude Fable 5.2 Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 28 +- crates/xcl/src/hle/d3d12x/bind.rs | 18 +- crates/xcl/src/hle/d3d12x/cpu_writes.rs | 2 +- crates/xcl/src/hle/d3d12x/late_release.rs | 2 +- crates/xcl/src/hle/d3d12x/list_x.rs | 75 +- crates/xcl/src/hle/d3d12x/present.rs | 4 +- crates/xcl/src/hle/d3d12x/real.rs | 980 +++++++++++++++++++- crates/xcl/src/hle/d3d12x/sparse.rs | 13 +- crates/xcl/src/hle/d3d12x/title_textures.rs | 4 +- crates/xcl/src/hle/d3d12x/vram.rs | 6 +- 10 files changed, 1054 insertions(+), 78 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index bbb56bdc3f..14c236c17b 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -657,7 +657,7 @@ impl PendingSubmit { || { let mut dev: Option = None; q.GetDevice(&mut dev).ok()?; - dev?.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok() + super::real::create_raw_fence(&dev?).ok() }, |fence, value| super::real::native_queue_signal(q, fence, value).is_ok(), )) @@ -674,7 +674,7 @@ impl PendingSubmit { || { let mut dev: Option = None; q.GetDevice(&mut dev).ok()?; - dev?.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok() + super::real::create_raw_fence(&dev?).ok() }, |fence, value| super::real::native_queue_signal(q, fence, value).is_ok(), )) @@ -2724,12 +2724,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(); @@ -2739,7 +2742,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); @@ -2748,7 +2754,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"); @@ -2757,10 +2766,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); @@ -2773,6 +2786,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/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 0c064f8f93..f9f8f5a6b2 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -2938,6 +2938,7 @@ pub(super) unsafe fn poll_two_pass_feedback(queue: *mut c_void) { let mut raw = [cl.as_raw()]; type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = std::mem::transmute(super::real::orig_fn(queue, 10)); + let _list_guard = super::real::UnadoptGuard::new(raw[0]); exec(queue, 1, raw.as_mut_ptr()); } else { q.ExecuteCommandLists(&[Some(cl)]); @@ -5658,7 +5659,10 @@ void main(uint t : SV_GroupIndex) { }; let run = |list: &ID3D12GraphicsCommandList, close: &dyn Fn()| { close(); - queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + { + let _list_guard = real::UnadoptGuard::new(list.as_raw()); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + } let v = done.GetCompletedValue() + 1; queue.Signal(&done, v).unwrap(); fence::wait(&done, v, &dev, None, 10_000).unwrap(); @@ -9347,7 +9351,7 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); let list_obj: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); let list = list_obj.as_raw(); - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let fence: ID3D12Fence = real::create_raw_fence(&dev).unwrap(); let make_buf = |heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| -> ID3D12Resource { let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, @@ -9401,7 +9405,10 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) // Execution #1 of closed list. write_upload(0x1122_3344); clear_readback(); - queue.ExecuteCommandLists(&[Some(cl.clone())]); + { + let _list_guard = real::UnadoptGuard::new(list); + queue.ExecuteCommandLists(&[Some(cl.clone())]); + } queue.Signal(&fence, 1).unwrap(); two_pass_submitted(queue.as_raw(), Some(&fence), 1, &[list]); while super::super::real::fence_completed(&fence) < 1 { @@ -9419,7 +9426,10 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) // Replay #2 of the SAME closed list without Reset. write_upload(0x5566_7788); clear_readback(); - queue.ExecuteCommandLists(&[Some(cl)]); + { + let _list_guard = real::UnadoptGuard::new(list); + queue.ExecuteCommandLists(&[Some(cl)]); + } queue.Signal(&fence, 2).unwrap(); two_pass_submitted(queue.as_raw(), Some(&fence), 2, &[list]); while super::super::real::fence_completed(&fence) < 2 { diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index f672e42f0a..44afd4636a 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -262,7 +262,7 @@ unsafe fn schedule(queue: *mut c_void, writes: Vec, completion: bool) -> return None; } let Some(dev) = dev else { return None }; - let Ok(fence) = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) else { return None }; + let Ok(fence) = super::real::create_raw_fence(&dev) else { return None }; 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 1c17726248..7c452a5ac2 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -76,7 +76,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()); // (no fence: the device is gone – the batch stays open, and held) self.fences.insert(key, (made?, 0)); } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 638b133d13..a0bbe151fc 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3094,17 +3094,23 @@ 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 mut g = SYNC_GRAPH.lock().unwrap(); - let cell = g.get_or_insert_with(SyncGraph::default).cells.entry(va).or_default(); - if cell.non_monotonic { - return None; - } - if let Some(ref existing) = cell.fence { - return (cell.device == dev_raw).then(|| existing.clone()); + let created: ID3D12Fence = real::create_raw_fence(&dev).ok()?; + let installed = { + 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 { + return None; + } + if let Some(ref existing) = cell.fence { + return (cell.device == dev_raw).then(|| existing.clone()); + } + cell.fence = Some(created.clone()); + cell.device = dev_raw; + true + }; + if installed { + real::track_end_title_fence(&created); } - cell.fence = Some(created.clone()); - cell.device = dev_raw; Some(created) } @@ -3969,7 +3975,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; @@ -4455,7 +4461,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 { @@ -4837,6 +4846,8 @@ fn note_reserved_closed(list: usize, ty: D3D12_COMMAND_LIST_TYPE) { unsafe fn reset_reserved_segment(list: *mut c_void, alloc: usize, ty: D3D12_COMMAND_LIST_TYPE, init_pso: usize) -> bool { let ext = *(list as *const usize); let hr = super::alloc_pool::reset_list(list 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>(list, PC_RESET)(list, pc_alloc, init_pso) }); real::preserve_vtable(list, ext); @@ -5389,7 +5400,10 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { chunk.has_native_generations(), chunk.native_generations(), || {}, - || exec(q_raw, lists.len() as u32, lists.as_ptr()), + || { + let _list_guards: Vec<_> = lists.iter().filter_map(|&l| real::UnadoptGuard::new(l)).collect(); + exec(q_raw, lists.len() as u32, lists.as_ptr()) + }, ) { return (false, None); } @@ -5433,7 +5447,10 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { !native_generations.is_empty(), native_generations.iter(), || {}, - || exec(q_raw, 1, one.as_ptr()), + || { + let _list_guard = real::UnadoptGuard::new(this); + exec(q_raw, 1, one.as_ptr()) + }, ); if submitted { if let Some(trace) = ¤t_trace { @@ -5515,6 +5532,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let ext_closed = *(target as *const usize); let (init_pso, init_generation) = super::bind::initial_pipeline(target); 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); @@ -6300,6 +6319,8 @@ unsafe fn reset_pc_inner(this: *mut c_void, alloc: usize, pso: usize) -> i32 { 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 mut on = alloc; 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); on = pc_alloc; pc:: i32>(this, PC_RESET)(this, pc_alloc, resolved) }); @@ -11544,15 +11565,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) }; @@ -11652,7 +11676,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); @@ -11701,7 +11725,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"); @@ -12020,7 +12047,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); @@ -12033,7 +12063,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 cf37a356d8..17a6633026 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -649,7 +649,7 @@ pub(super) unsafe fn retire_released_queue(raw: usize) { let mark = (|| { let mut dev: Option = None; queue.GetDevice(&mut dev).ok()?; - let fence = dev?.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()?; + let fence = super::real::create_raw_fence(&dev?).ok()?; super::real::native_queue_signal(&queue, &fence, 1).ok()?; Some(QueueRetirementMark { fence, value: 1 }) })(); @@ -1340,7 +1340,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 a9dad2dd11..dd95251374 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1104,6 +1104,69 @@ 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) +} + +/// Whether `UnadoptGuard::new` leaves an object whose vtable is `cur` alone: not an extended +/// vtable, or a runtime table XCL patched in place (its `ext[-1]` is not the native table). +fn skips_guard(cur: usize) -> bool { + !is_ext_fast(cur) || in_place_original(cur, 0).is_some() +} + +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); + } else { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: more than {EXT_FAST_CAP} native vtables under UnadoptGuard – {} is not recorded, so orig_fn on an object guarded with it reads a wrong entry", crate::modules::describe_address(orig))); + } +} + +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 +} #[cfg(test)] pub(super) struct TestCommandListClass { @@ -1134,16 +1197,99 @@ pub(super) fn test_command_list_class(orig: usize, ext: usize) -> TestCommandLis } 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 let Some(f) = in_place_original(ext as usize, slot) { + return f; + } + 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) } +// 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) +} + /// `slot_of(this, method)`, looked up once for this call site. COM interface versions append /// methods, so one method keeps its slot throughout the interface family served by a hook. macro_rules! slot { @@ -1179,6 +1325,7 @@ pub(crate) unsafe fn native_queue_execute(queue: &ID3D12CommandQueue, list: &ID3 super::queue_submit::with(raw as usize, || { let f: F = std::mem::transmute(f); let list = list.as_raw(); + let _list_guard = UnadoptGuard::new(list); f(raw, 1, &list); }); } @@ -1191,7 +1338,7 @@ pub(crate) unsafe fn native_queue_signal(queue: &ID3D12CommandQueue, fence: &ID3 let f = native_queue_fn(raw, 14); super::queue_submit::with(raw as usize, || { let f: F = std::mem::transmute(f); - windows::core::HRESULT(f(raw, fence.as_raw(), value)).ok() + windows::core::HRESULT(f(raw, unwrap_fence(fence.as_raw()), value)).ok() }) } @@ -1202,12 +1349,12 @@ pub(crate) unsafe fn native_queue_wait(queue: &ID3D12CommandQueue, fence: &ID3D1 let f = native_queue_fn(raw, 15); super::queue_submit::with(raw as usize, || { let f: F = std::mem::transmute(f); - windows::core::HRESULT(f(raw, fence.as_raw(), value)).ok() + windows::core::HRESULT(f(raw, unwrap_fence(fence.as_raw()), value)).ok() }) } pub(crate) unsafe fn native_fence_completed(fence: &ID3D12Fence) -> u64 { - let raw = fence.as_raw(); + let raw = unwrap_fence(fence.as_raw()); let slot = std::mem::offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / std::mem::size_of::(); type F = unsafe extern "system" fn(*mut c_void) -> u64; let f: F = std::mem::transmute(if is_ext(vt(raw) as usize) { orig_fn(raw, slot) } else { *vt(raw).add(slot) }); @@ -1299,6 +1446,93 @@ 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; + } + Self::enter(obj) + } + + /// `new` past its Wine and pointer checks. + unsafe fn enter(obj: *mut c_void) -> Option { + // (a native table may be another guard's: that one is counted under the lock) + let cur = (*(obj as *const AtomicUsize)).load(Ordering::Acquire); + if !is_known_native(cur) && skips_guard(cur) { + 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 skips_guard(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 }) + } +} + +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() { @@ -1357,6 +1591,19 @@ unsafe fn release_through_its_own_vtable(p: *mut c_void) -> u32 { } 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; } @@ -1365,10 +1612,14 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { let chain = layout::chain(kind.base()); let qi: QiFn = std::mem::transmute(*ot); 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; // (through the result's own vtable: under the debug layer QueryInterface gives // another object than `obj`, and `obj`'s Release on it read a null pointer in // D3D12Core 1.5 s into a retail title's start) @@ -1383,14 +1634,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 { @@ -1472,9 +1727,31 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { *e = super::guard::make_before(*e, (i - 1) as u64, super::bind::before_list_call); } } + if in_place { + let register = || { + register_ext(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); + register_ext(ext); crate::xlog_info!( "D3D12.X: {} – {public} PC methods, {} internal slots under the guard, +{EXTRA_SLOTS} stubs ({kind:?}, PC vtable {})", iface.name, @@ -3999,6 +4276,21 @@ unsafe extern "system" fn dev_enqueue_make_resident( f(this, flags, n, objects, fence, value) } +/// device #31 CreateSharedHandle (Wine): the runtime gets its own fence, not the title's proxy +unsafe extern "system" fn dev_create_shared_handle(this: *mut c_void, object: *mut c_void, attributes: *const c_void, access: u32, name: *const u16, handle: *mut *mut c_void) -> HRESULT { + let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *const c_void, u32, *const u16, *mut *mut c_void) -> HRESULT = + std::mem::transmute(orig_fn(this, pc_slot!("ID3D12Device", "CreateSharedHandle"))); + f(this, unwrap_fence(object), attributes, access, name, handle) +} + +/// device #45 SetEventOnMultipleFenceCompletion (Wine): the runtime gets its own fences, not the title's proxies +unsafe extern "system" fn dev_set_event_on_multiple_fence_completion(this: *mut c_void, fences: *const *mut c_void, values: *const u64, n: u32, flags: u32, event: *mut c_void) -> HRESULT { + let f: unsafe extern "system" fn(*mut c_void, *const *mut c_void, *const u64, u32, u32, *mut c_void) -> HRESULT = + std::mem::transmute(orig_fn(this, pc_slot!("ID3D12Device1", "SetEventOnMultipleFenceCompletion"))); + let pc: Vec<*mut c_void> = (0..n as usize).map(|i| unwrap_fence(*fences.add(i))).collect(); + f(this, pc.as_ptr(), values, n, flags, event) +} + fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { let mut v: Vec<(&'static str, usize)> = vec![("QueryInterface", qi_override as usize)]; match kind { @@ -4054,7 +4346,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)]); + if crate::util::under_wine() { + v.extend_from_slice(&[("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), @@ -4075,6 +4372,9 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ]), _ => {} } + if kind == Kind::Device && crate::util::under_wine() { + v.extend_from_slice(&[("CreateSharedHandle", dev_create_shared_handle as usize), ("SetEventOnMultipleFenceCompletion", dev_set_event_on_multiple_fence_completion as usize)]); + } v } @@ -4179,6 +4479,8 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, in let resolved = prepared.raw(); let hr = { let _in_reset = super::late_release::InListReset::enter(); + let _alloc_guard = UnadoptGuard::new(allocator); + let _pso_guard = UnadoptGuard::new(resolved as *mut c_void); f(this, allocator, resolved as *mut c_void) }; preserve_vtable(this, ext); @@ -4377,7 +4679,12 @@ fn is_own_object(kind: Kind) -> bool { 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` @@ -4399,6 +4706,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); @@ -4436,7 +4745,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; @@ -4599,7 +4912,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]); @@ -4826,6 +5143,126 @@ 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, +} + +static FENCE_PROXY_VT: std::sync::OnceLock = std::sync::OnceLock::new(); + +fn fence_proxy_vtable() -> usize { + *FENCE_PROXY_VT.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[8] = fence_get_completed_value as usize; + v[9] = fence_set_event_on_completion as usize; + v[10] = fence_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 +} + +/// The fence a fence hook calls and its PC method `slot`: the runtime's fence behind a proxy, or +/// the adopted fence's original. +unsafe fn fence_pc_fn(this: *mut c_void, slot: usize) -> (*mut c_void, usize) { + if FENCE_PROXY_VT.get() == Some(&(vt(this) as usize)) { + let pc = (*(this as *const FenceProxy)).pc; + return (pc, *vt(pc).add(slot)); + } + (this, orig_fn(this, slot)) +} + +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 crate::util::under_wine() && 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) +} + +/// Remember a raw fence (e.g. a `list_x` cell fence created via `create_raw_fence` under Wine) +/// in `FENCES` so `end_title` signals it to `u64::MAX` before `drain_gpu`. No-op if already +/// tracked (e.g. off Wine, where `create_raw_fence` goes through `dev_create_fence`). +pub(super) unsafe fn track_end_title_fence(fence: &ID3D12Fence) { + let raw = fence.as_raw(); + let mut g = FENCES.write().unwrap(); + if !g.contains(&(raw as usize)) { + let add: RefFn = std::mem::transmute(*vt(raw).add(1)); + add(raw); + g.push(raw as usize); + } +} + /// 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) @@ -4850,7 +5287,21 @@ unsafe extern "system" fn dev_create_fence(this: *mut c_void, value: usize, flag crate::xlog_info!("D3D12.X: fence flags {:#x} – console-only bits dropped (passing {pc_flags:#x})", flags as u32); } } - let hr = dev_create_fence_pc(this, value, pc_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, pc_flags, riid, ppv); + if hr == E_NOINTERFACE { + let iid = pc_iid(Kind::Fence); + hr = f(this, value, pc_flags, &iid, ppv); + } + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() && !is_own_object(Kind::Fence) { + *ppv = wrap_fence_proxy(*ppv); + } + hr + } else { + dev_create_fence_pc(this, value, pc_flags, riid, ppv) + }; if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { let add: RefFn = std::mem::transmute(*vt(*ppv).add(1)); add(*ppv); @@ -11345,7 +11796,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::capture::enabled() { super::capture::note_view(handle, res as usize, false, (!desc.is_null()).then(|| (desc as *const [u32; 6]).read_unaligned())); @@ -11426,7 +11880,10 @@ unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rt pub(super) unsafe fn bind_pipeline_exact(this: *mut c_void, original: usize, raw: usize) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot!(this, "SetPipelineState"))); - f(this, raw as *mut c_void); + { + let _pso_guard = UnadoptGuard::new(raw as *mut c_void); + f(this, raw as *mut c_void); + } super::dred::mark_pipeline(this, original, raw); } @@ -11435,7 +11892,10 @@ pub(super) unsafe fn bind_pipeline_exact(this: *mut c_void, original: usize, raw pub(super) unsafe fn clear_pipeline_exact(this: *mut c_void, original: usize, raw: usize) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ClearState"))); - f(this, raw as *mut c_void); + { + let _pso_guard = UnadoptGuard::new(raw as *mut c_void); + f(this, raw as *mut c_void); + } if original != 0 && raw != 0 { super::dred::mark_pipeline(this, original, raw); } @@ -11566,7 +12026,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!(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); // The GPU is done with allocations owned by this exact native backing. @@ -11692,7 +12155,7 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a // (work that waits for it may use memory committed since it was submitted) super::sparse::send_pending(); let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(pc(PC_SIGNAL)); - let hr = f(this, a1, a2); + let hr = f(this, unwrap_fence(a1 as *mut c_void) as usize, a2); if hr >= 0 { super::fence_x::note_queue_signal(a1, a2 as u64); super::list_x::note_title_queue_signal(this as usize, a1, a2 as u64); @@ -11710,7 +12173,7 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a }, 15 if is_fence(a1) => super::queue_submit::with(this as usize, || { let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(pc(PC_WAIT)); - let hr = f(this, a1, a2); + let hr = f(this, unwrap_fence(a1 as *mut c_void) as usize, a2); if hr >= 0 { super::fence_x::note_queue_wait(a1, a2 as u64); super::list_x::note_title_queue_wait(this as usize, a1, a2 as u64); @@ -11792,6 +12255,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, pc_slot!("ID3D12CommandQueue", "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, pc_slot!("ID3D12CommandQueue", "Wait"))); + f(this, unwrap_fence(fence), value) +} + /// The calls of the queue's page-mapping method recorded so far and what they did, summed, and /// when their line was logged last. static PAGE_MAPPINGS: Mutex<(u64, crate::hle::kernelx::mirrors::Mapped, Option)> = @@ -11871,7 +12346,7 @@ unsafe fn q_signal_x_serialized(this: *mut c_void, fence: *mut c_void, value: u6 // (work that waits for it may use memory committed since it was submitted) super::sparse::send_pending(); 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); @@ -11886,7 +12361,7 @@ unsafe fn q_signal_x_serialized(this: *mut c_void, fence: *mut c_void, value: u6 /// with every submitting thread behind it. pub(super) unsafe fn fence_completed(fence: &ID3D12Fence) -> u64 { const PC_GET_COMPLETED_VALUE: usize = 8; - let p = fence.as_raw(); + let p = unwrap_fence(fence.as_raw()); // (a fence XCL holds a reference to: no need to ask Windows whether it can be read, as // `is_adopted` does) let f: unsafe extern "system" fn(*mut c_void) -> u64 = if is_ext(vt(p) as usize) { @@ -11900,8 +12375,9 @@ pub(super) unsafe fn fence_completed(fence: &ID3D12Fence) -> u64 { /// Fence::GetCompletedValue. What the title's lists wrote into its sparse memory comes back /// asynchronously (`sparse::readback_after_execute`): the copies back the value covers land first. unsafe extern "system" fn fence_get_completed_value(this: *mut c_void) -> u64 { - let f: unsafe extern "system" fn(*mut c_void) -> u64 = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12Fence", "GetCompletedValue"))); - let v = f(this); + let (pc, f) = fence_pc_fn(this, pc_slot!("ID3D12Fence", "GetCompletedValue")); + let f: unsafe extern "system" fn(*mut c_void) -> u64 = std::mem::transmute(f); + let v = f(pc); super::sparse::settle_readbacks_try(); super::title_textures::safe_fence_value(this as usize, v) } @@ -11936,14 +12412,15 @@ unsafe extern "system" fn fence_wait_fired(ctx: *mut c_void, _timed_out: bool) { /// (a blocking wait) settles them after it. unsafe extern "system" fn fence_set_event_on_completion(this: *mut c_void, value: u64, event: *mut c_void) -> HRESULT { use windows_sys::Win32::System::Threading::{CreateEventW, RegisterWaitForSingleObject, UnregisterWaitEx, INFINITE, WT_EXECUTEONLYONCE}; - let f: unsafe extern "system" fn(*mut c_void, u64, *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12Fence", "SetEventOnCompletion"))); + let (pc, f) = fence_pc_fn(this, pc_slot!("ID3D12Fence", "SetEventOnCompletion")); + let f: unsafe extern "system" fn(*mut c_void, u64, *mut c_void) -> HRESULT = std::mem::transmute(f); if event.is_null() || !super::sparse::readbacks_async() { let hr = { let _t = crate::hle::api_cost::time_if( event.is_null() && super::look_stats::deep() && !super::title_textures::is_own_work() && !super::present::presenting(), crate::hle::api_cost::Call::FenceWait, ); - f(this, value, event) + f(pc, value, event) }; if event.is_null() { super::sparse::settle_readbacks_try(); @@ -11952,17 +12429,17 @@ unsafe extern "system" fn fence_set_event_on_completion(this: *mut c_void, value } let own = CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()); if own.is_null() { - return f(this, value, event); + return f(pc, value, event); } let w = Box::into_raw(Box::new(FenceWait { own, title: event, wait: AtomicUsize::new(0) })); let mut wh = std::ptr::null_mut(); if RegisterWaitForSingleObject(&mut wh, own, Some(fence_wait_fired), w as *const c_void, INFINITE, WT_EXECUTEONLYONCE) == 0 { windows_sys::Win32::Foundation::CloseHandle(own); drop(Box::from_raw(w)); - return f(this, value, event); + return f(pc, value, event); } (*w).wait.store(wh as usize, Ordering::Release); - let hr = f(this, value, own); + let hr = f(pc, value, own); if hr < 0 { // the event will not be set: take the wait back (waiting for a running callback) if UnregisterWaitEx(wh, windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE) != 0 { @@ -11975,10 +12452,11 @@ unsafe extern "system" fn fence_set_event_on_completion(this: *mut c_void, value /// Fence::Signal (CPU) unsafe extern "system" fn fence_signal(this: *mut c_void, value: u64) -> HRESULT { - let f: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12Fence", "Signal"))); + let (pc, f) = fence_pc_fn(this, pc_slot!("ID3D12Fence", "Signal")); + let f: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(f); // (work that waits for it may use memory committed since it was submitted) super::sparse::send_pending(); - let hr = f(this, value); + let hr = f(pc, value); super::fence_x::note_cpu_signal(this as usize); hr } @@ -11992,6 +12470,8 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis // `present::note_execute` -> `late_release::drain_known` -> `vram::recycle_ready`, preventing // re-entrant lock self-deadlocks and keeping internal queues out of `present::QUEUES`. if n == 0 || lists.is_null() || super::title_textures::is_own_work() { + let own = if lists.is_null() { &[][..] } else { std::slice::from_raw_parts(lists, n as usize) }; + let _list_guards: Vec<_> = own.iter().filter_map(|&l| UnadoptGuard::new(l)).collect(); super::queue_submit::with(this as usize, || f(this, n, lists)); stop_if_device_removed(); return; @@ -12065,6 +12545,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis let started = std::time::Instant::now(); { let _in_driver = super::watch::in_driver(super::watch::Call::Execute); + let _list_guards: Vec<_> = lists.iter().filter_map(|&l| UnadoptGuard::new(l)).collect(); f(this, lists.len() as u32, lists.as_ptr()); } let took = started.elapsed(); @@ -12129,7 +12610,7 @@ pub fn drain_gpu() { let mut fences = Vec::new(); for q in super::present::active_queues_held() { 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))?; native_queue_signal(&q, &f, 1).map_err(|e| fence::api_error(dev, "Signal", e))?; Ok(f) @@ -12712,6 +13193,123 @@ 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"); + } + + /// Concurrent callers invoking methods through a read-only vtable while multiple threads race + /// to `patch_in_place` must never observe a torn entry, a missing `orig_fn`, or a second + /// patch, and `UnadoptGuard::new` must skip the in-place patched table. + #[test] + fn concurrent_calls_and_patches_on_readonly_vtable_never_tear_or_miss_orig_fn() { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::{Arc, Barrier}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualProtect, MEM_COMMIT, MEM_RESERVE, PAGE_READONLY, PAGE_READWRITE}; + + unsafe extern "system" fn orig_slot(_this: *mut c_void) -> usize { + 0x1111_0001 + } + unsafe extern "system" fn hook_slot(this: *mut c_void) -> usize { + let f: unsafe extern "system" fn(*mut c_void) -> usize = std::mem::transmute(orig_fn(this, 1)); + f(this) + 1 + } + + unsafe { + let mem = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut usize; + assert!(!mem.is_null()); + for i in 0..8 { + mem.add(i).write(orig_slot as usize); + } + let mut old = 0u32; + assert_ne!(VirtualProtect(mem as *const c_void, 4096, PAGE_READONLY, &mut old), 0); + + let obj_box = Box::leak(Box::new([mem as usize])); + let obj_addr = obj_box.as_mut_ptr() as usize; + let table_addr = mem as usize; + + let barrier = Arc::new(Barrier::new(6)); + let stop = Arc::new(AtomicBool::new(false)); + let hook_hits = Arc::new(AtomicUsize::new(0)); + let reg_count = Arc::new(AtomicUsize::new(0)); + + let mut callers = Vec::new(); + for _ in 0..4 { + let b = barrier.clone(); + let s = stop.clone(); + let hits = hook_hits.clone(); + callers.push(std::thread::spawn(move || { + b.wait(); + let obj = obj_addr as *mut c_void; + let until = std::time::Instant::now() + std::time::Duration::from_secs(10); + while std::time::Instant::now() < until { + let vt = (*(obj as *const AtomicUsize)).load(Ordering::Acquire) as *const AtomicUsize; + let fp = (*vt.add(1)).load(Ordering::Acquire); + let f: unsafe extern "system" fn(*mut c_void) -> usize = std::mem::transmute(fp); + let r = f(obj); + assert!(r == 0x1111_0001 || r == 0x1111_0002, "unexpected slot result {r:#x}"); + if r == 0x1111_0002 { + hits.fetch_add(1, Ordering::Relaxed); + } + if s.load(Ordering::Relaxed) && hits.load(Ordering::Relaxed) > 0 { + break; + } + } + })); + } + + let mut patchers = Vec::new(); + for _ in 0..2 { + let b = barrier.clone(); + let rc = reg_count.clone(); + patchers.push(std::thread::spawn(move || { + b.wait(); + let entries = [orig_slot as usize, hook_slot as usize, orig_slot as usize, orig_slot as usize]; + patch_in_place(table_addr as *mut usize, &entries, || { + register_ext(table_addr); + rc.fetch_add(1, Ordering::SeqCst); + }) + })); + } + + let results: Vec> = patchers.into_iter().map(|h| h.join().unwrap()).collect(); + stop.store(true, Ordering::Relaxed); + for h in callers { + h.join().unwrap(); + } + + assert_eq!(results.iter().filter(|r| matches!(r, Ok(true))).count(), 1, "exactly one thread patches: {results:?}"); + assert_eq!(results.iter().filter(|r| matches!(r, Ok(false))).count(), 1, "other racer sees Ok(false): {results:?}"); + assert_eq!(reg_count.load(Ordering::SeqCst), 1, "register runs exactly once"); + assert!(hook_hits.load(Ordering::Relaxed) > 0, "callers must observe the patched hook"); + assert!(UnadoptGuard::enter(obj_addr as *mut c_void).is_none(), "UnadoptGuard must skip in-place patched vtables"); + } + } +} + #[cfg(test)] mod descriptor_heap_tests { use super::*; @@ -14794,6 +15392,326 @@ 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 orig_buf: &'static mut [usize] = Box::leak(vec![0usize; 9].into_boxed_slice()); + 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 ext_buf: &'static mut [usize] = Box::leak(vec![0usize; 9].into_boxed_slice()); + 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 }; + register_ext(ext_vt); + 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).expect("an extended table is guarded"); + 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).expect("a native table another guard put in is counted, not skipped"); + 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 orig_buf: &'static mut [usize] = Box::leak(vec![0usize; 9].into_boxed_slice()); + 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 ext_buf: &'static mut [usize] = Box::leak(vec![0usize; 9].into_boxed_slice()); + 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 }; + register_ext(ext_vt); + + 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).expect("an extended table is guarded"); + // 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); + } + } + + #[test] + fn track_end_title_fence_registers_once_and_addrefs() { + #[repr(C)] + struct FakeFence { + vt: *const usize, + refs: AtomicU32, + } + unsafe extern "system" fn fake_add_ref(this: *mut c_void) -> u32 { + (*(this as *const FakeFence)).refs.fetch_add(1, Ordering::AcqRel) + 1 + } + unsafe extern "system" fn fake_release(this: *mut c_void) -> u32 { + (*(this as *const FakeFence)).refs.fetch_sub(1, Ordering::AcqRel) - 1 + } + + let mut vt = [0usize; 4]; + vt[1] = fake_add_ref as usize; + vt[2] = fake_release as usize; + let fake = Box::new(FakeFence { vt: vt.as_ptr(), refs: AtomicU32::new(1) }); + let raw = &*fake as *const FakeFence as *mut c_void; + + unsafe { + let borrowed = ID3D12Fence::from_raw_borrowed(&raw).expect("borrowed fake fence"); + assert!(!is_fence(raw as usize)); + track_end_title_fence(borrowed); + assert!(is_fence(raw as usize), "tracked raw fence must be visible to end_title"); + assert_eq!(fake.refs.load(Ordering::Acquire), 2, "tracking must AddRef once"); + track_end_title_fence(borrowed); + assert_eq!(fake.refs.load(Ordering::Acquire), 2, "duplicate tracking must be a no-op"); + FENCES.write().unwrap().retain(|&f| f != raw as usize); + fake_release(raw); + assert_eq!(fake.refs.load(Ordering::Acquire), 1); + } + } + + #[test] + fn a_fence_proxy_runs_the_fence_hooks_on_the_runtime_fence() { + #[repr(C)] + struct FakeFence { + vt: *const usize, + completed: AtomicU64, + waited: AtomicU64, + asked_by: AtomicUsize, + } + unsafe extern "system" fn fake_completed(this: *mut c_void) -> u64 { + let f = &*(this as *const FakeFence); + f.asked_by.store(this as usize, Ordering::Relaxed); + f.completed.load(Ordering::Relaxed) + } + unsafe extern "system" fn fake_set_event(this: *mut c_void, value: u64, _event: *mut c_void) -> HRESULT { + (*(this as *const FakeFence)).waited.store(value, Ordering::Relaxed); + S_OK + } + unsafe extern "system" fn fake_signal(this: *mut c_void, value: u64) -> HRESULT { + (*(this as *const FakeFence)).completed.store(value, Ordering::Relaxed); + S_OK + } + + let vt: &'static mut [usize] = Box::leak(vec![0usize; 16].into_boxed_slice()); + vt[8] = fake_completed as usize; + vt[9] = fake_set_event as usize; + vt[10] = fake_signal as usize; + let fake = Box::new(FakeFence { vt: vt.as_ptr(), completed: AtomicU64::new(0), waited: AtomicU64::new(0), asked_by: AtomicUsize::new(0) }); + let raw = &*fake as *const FakeFence as *mut c_void; + + unsafe { + let proxy = wrap_fence_proxy(raw); + let t = *(proxy as *const *const usize); + assert_eq!( + [*t.add(8), *t.add(9), *t.add(10)], + [fence_get_completed_value as usize, fence_set_event_on_completion as usize, fence_signal as usize] + ); + let signal: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(*t.add(10)); + let completed: unsafe extern "system" fn(*mut c_void) -> u64 = std::mem::transmute(*t.add(8)); + let set_event: unsafe extern "system" fn(*mut c_void, u64, *mut c_void) -> HRESULT = std::mem::transmute(*t.add(9)); + assert_eq!(signal(proxy, 7), S_OK); + assert_eq!(completed(proxy), 7); + assert_eq!(fake.asked_by.load(Ordering::Relaxed), raw as usize); + assert_eq!(set_event(proxy, 9, std::ptr::null_mut()), S_OK); + assert_eq!(fake.waited.load(Ordering::Relaxed), 9); + drop(Box::from_raw(proxy as *mut FenceProxy)); + } + } + + #[test] + fn xcl_signal_and_wait_on_a_queue_unwrap_a_fence_proxy_only_under_wine() { + static SEEN: AtomicUsize = AtomicUsize::new(0); + unsafe extern "system" fn fake_queue_call(_this: *mut c_void, fence: *mut c_void, _value: u64) -> HRESULT { + SEEN.store(fence as usize, Ordering::Relaxed); + S_OK + } + + let names: Vec<_> = overrides(Kind::CommandQueue).into_iter().map(|e| e.0).collect(); + assert_eq!(names.contains(&"Signal"), crate::util::under_wine()); + assert_eq!(names.contains(&"Wait"), crate::util::under_wine()); + + let orig: &'static mut [usize] = Box::leak(vec![0usize; 16].into_boxed_slice()); + orig[14] = fake_queue_call as usize; + orig[15] = fake_queue_call as usize; + let ext: &'static [usize] = Box::leak(vec![orig.as_ptr() as usize; 2].into_boxed_slice()); + let queue = Box::into_raw(Box::new([ext.as_ptr() as usize + 8])) as *mut c_void; + let fence = Box::into_raw(Box::new([0usize; 2])) as *mut c_void; + + unsafe { + let proxy = wrap_fence_proxy(fence); + let passed = if crate::util::under_wine() { fence } else { proxy } as usize; + assert_eq!(q_signal_pc(queue, proxy, 1), S_OK); + assert_eq!(SEEN.swap(0, Ordering::Relaxed), passed); + assert_eq!(q_wait_pc(queue, proxy, 1), S_OK); + assert_eq!(SEEN.swap(0, Ordering::Relaxed), passed); + drop(Box::from_raw(proxy as *mut FenceProxy)); + drop(Box::from_raw(fence as *mut [usize; 2])); + drop(Box::from_raw(queue as *mut [usize; 1])); + } + } + + #[test] + fn a_shared_handle_and_a_multiple_fence_wait_unwrap_a_fence_proxy_only_under_wine() { + static SEEN: Mutex> = Mutex::new(Vec::new()); + unsafe extern "system" fn fake_create_shared_handle(_this: *mut c_void, object: *mut c_void, _attributes: *const c_void, _access: u32, _name: *const u16, _handle: *mut *mut c_void) -> HRESULT { + SEEN.lock().unwrap().push(object as usize); + S_OK + } + unsafe extern "system" fn fake_set_event_on_multiple(_this: *mut c_void, fences: *const *mut c_void, _values: *const u64, n: u32, _flags: u32, _event: *mut c_void) -> HRESULT { + SEEN.lock().unwrap().extend((0..n as usize).map(|i| *fences.add(i) as usize)); + S_OK + } + + let names: Vec<_> = overrides(Kind::Device).into_iter().map(|e| e.0).collect(); + assert_eq!(names.contains(&"CreateSharedHandle"), crate::util::under_wine()); + assert_eq!(names.contains(&"SetEventOnMultipleFenceCompletion"), crate::util::under_wine()); + + let orig: &'static mut [usize] = Box::leak(vec![0usize; 48].into_boxed_slice()); + orig[31] = fake_create_shared_handle as usize; + orig[45] = fake_set_event_on_multiple as usize; + let ext: &'static [usize] = Box::leak(vec![orig.as_ptr() as usize; 2].into_boxed_slice()); + let device = Box::into_raw(Box::new([ext.as_ptr() as usize + 8])) as *mut c_void; + let fence = Box::into_raw(Box::new([0usize; 2])) as *mut c_void; + let plain = Box::into_raw(Box::new([0usize; 2])) as *mut c_void; + + unsafe { + let proxy = wrap_fence_proxy(fence); + let passed = if crate::util::under_wine() { fence } else { proxy } as usize; + let mut handle = std::ptr::null_mut(); + assert_eq!(dev_create_shared_handle(device, proxy, std::ptr::null(), 0, std::ptr::null(), &mut handle), S_OK); + assert_eq!(std::mem::take(&mut *SEEN.lock().unwrap()), [passed]); + assert_eq!(dev_set_event_on_multiple_fence_completion(device, [proxy, plain].as_ptr(), [1u64, 2].as_ptr(), 2, 0, std::ptr::null_mut()), S_OK); + assert_eq!(std::mem::take(&mut *SEEN.lock().unwrap()), [passed, plain as usize]); + drop(Box::from_raw(proxy as *mut FenceProxy)); + drop(Box::from_raw(fence as *mut [usize; 2])); + drop(Box::from_raw(plain as *mut [usize; 2])); + drop(Box::from_raw(device as *mut [usize; 1])); + } + } +} + #[cfg(test)] mod depth_uav_twin_tests { use super::*; @@ -15142,7 +16060,7 @@ mod depth_uav_twin_tests { l.CopyTextureRegion(&dst, 0, 0, 0, &src, None); l.Close().expect("close list"); f.queue.ExecuteCommandLists(&[Some(l.cast().unwrap())]); - let fence: ID3D12Fence = f.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + let fence: ID3D12Fence = create_raw_fence(&f.dev).expect("fence"); f.queue.Signal(&fence, 1).expect("signal"); crate::gpu::fence::wait(&fence, 1, &f.dev, None, 5000).expect("the clear and the copy complete"); diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index cae13913f2..fa4ed52a0a 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -3262,13 +3262,13 @@ unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) - crate::xlog_warn!("sparse windows: XCL_SPARSE_LAZY=1 is left out - on this device a tile with no video memory does not read zeros (tiled resources tier under 2)"); } 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 rbq = (|| -> windows::core::Result<(ID3D12CommandQueue, ID3D12Fence)> { let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; let _ = q.SetName(windows::core::w!("xcl sparse readback queue")); - Ok((q, dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?)) + Ok((q, super::real::create_raw_fence(dev)?)) })() .ok(); let mut slots = Vec::with_capacity(UPLOAD_SLOTS); @@ -5094,7 +5094,7 @@ unsafe fn submit_async_readback_inner( // on this queue: [the title's lists] Signal(first, v) [the copies] Signal(second, v) let key = queue.as_raw() as usize; if !sub.rb_queue_fences.contains_key(&key) { - let (Ok(a), Ok(b)) = (sub.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE), sub.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE)) else { + let (Ok(a), Ok(b)) = (super::real::create_raw_fence(&sub.dev), super::real::create_raw_fence(&sub.dev)) else { return; }; sub.rb_queue_fences.insert(key, (a, b, 0)); @@ -5216,6 +5216,7 @@ pub(super) unsafe fn pc_execute(queue: &ID3D12CommandQueue, list: &ID3D12Graphic let q = queue.as_raw(); let f: ExecFn = if super::real::is_adopted(q) { std::mem::transmute(super::real::orig_fn(q, SLOT)) } else { std::mem::transmute(*(*(q as *const *const usize)).add(SLOT)) }; let one = [list.as_raw()]; + let _list_guard = super::real::UnadoptGuard::new(one[0]); // (main's ordered queue turn: re-entrant, so a caller already in it keeps it) super::queue_submit::with(q as usize, || f(q, 1, one.as_ptr())); } @@ -5912,7 +5913,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, (fence, 0)); true @@ -5947,7 +5948,7 @@ impl State { seen.push(key); let entry = match self.queue_fences.entry(key) { std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(), - std::collections::hash_map::Entry::Vacant(entry) => match self.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) { + std::collections::hash_map::Entry::Vacant(entry) => match super::real::create_raw_fence(&self.dev) { Ok(fence) => entry.insert((fence, 0)), Err(_) => { ok = false; diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d809b1c2a2..f604c558c9 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -2666,7 +2666,7 @@ unsafe fn submit_on(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[tex let mut slot = state.lock().unwrap(); if slot.is_none() { // (before anything runs that it would have to follow) - let fence = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE).map_err(|e| e.to_string())?; + let fence = super::real::create_raw_fence(dev).map_err(|e| e.to_string())?; *slot = Some(QueueUploads { fence, value: 0, in_flight: std::collections::VecDeque::new(), bytes: 0 }); } let Some(q) = slot.as_mut() else { return Err("no fence for the queue".into()) }; @@ -4284,7 +4284,7 @@ pub(super) unsafe fn prepare_texture_download( } graphics.Close().map_err(|e| e.to_string())?; let list: ID3D12CommandList = graphics.cast().map_err(|e| e.to_string())?; - let fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(|e| e.to_string())?; + let fence = super::real::create_raw_fence(&dev).map_err(|e| e.to_string())?; Ok(TextureDownloadPlan { device: dev.clone(), queue_type, tex, source: source.clone(), readback, allocator, list, fence, footprints, bytes }) } diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 5281099647..c2b2403328 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1837,7 +1837,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, @@ -2004,7 +2004,7 @@ impl Pages { let entry = match self.unmap_fences.entry(key) { std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(), std::collections::hash_map::Entry::Vacant(entry) => { - let fence = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()?; + let fence = super::real::create_raw_fence(dev).ok()?; entry.insert((fence, 0)) } }; @@ -2694,7 +2694,7 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla let (immediate, mut probes) = { let mut rq = state.lock().unwrap(); 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| super::real::native_queue_signal(q, f, v).is_ok()); + let immediate = rq.retire_with(newly_reclaimed, unmap_mark, &queues, || super::real::create_raw_fence(dev).ok(), |q, f, v| super::real::native_queue_signal(q, f, v).is_ok()); RETIRING_BATCHES.fetch_add(rq.batches.len() - before, std::sync::atomic::Ordering::AcqRel); (immediate, rq.completion_fences()) };