diff --git a/README.md b/README.md index 1bd0c54868..8b6d0756e9 100644 --- a/README.md +++ b/README.md @@ -136,7 +136,7 @@ A gamepad is recommended ([Controls](#controls)). The game folder is never modif | Feature | State | What it does | Verified by | |---|---|---|---| -| **XGameRuntime** | ✅ | the GDK thunk protocol real titles use, laid out from a table of all 396 GDK runtime functions; offline XUser, XGameSave, persistent local storage, XPackage, XGame (title id), XSystem – the title sees an Xbox Series X / S; task queues, async, networking and dialogs through the PC's XGameRuntime | the game's libHttpClient initialises; users, saves and storage through the real call path; slot layout cross-checked against the game's own thunks | +| **XGameRuntime** | ✅ | the GDK thunk protocol real titles use, laid out from a table of all 396 GDK runtime functions; offline XUser, XGameSave, persistent local storage, XPackage, XGame (title id), XSystem – the title sees an Xbox Series X / S; task queues with monitor callback draining, async, networking and dialogs through the PC's XGameRuntime | the game's libHttpClient initialises; users, saves and storage through the real call path; slot layout cross-checked against the game's own thunks | | **Input** | ✅ | GameInput: one gamepad – the PC's XInput controller or a PlayStation controller, and keyboard and mouse as a gamepad (see [Controls](#controls)) | unit tests; an Xbox controller in Minecraft; a DualShock 4 (USB) | | **Audio** | ✅ | XAudio2 → system XAudio2.9 (PCM / float voices; Opus 0x704F decoded via `MSOpusDecoder.dll`; XMA1 / XMA2 decoded in pure Rust) | unit + end-to-end tests | diff --git a/crates/xcl/src/hle/xgameruntime/taskqueue.rs b/crates/xcl/src/hle/xgameruntime/taskqueue.rs index e5565ad699..c60e09d8a6 100644 --- a/crates/xcl/src/hle/xgameruntime/taskqueue.rs +++ b/crates/xcl/src/hle/xgameruntime/taskqueue.rs @@ -52,12 +52,63 @@ struct QueuedItem { port: u32, } -#[derive(Clone, Copy)] struct Monitor { token: u64, queue_handle: usize, ctx: usize, cb: usize, + state: Mutex, + idle: Condvar, +} + +#[derive(Default)] +struct MonitorState { + revoked: bool, + running: usize, +} + +thread_local! { + static MONITOR_DEPTH: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +impl Monitor { + /// Returns true when a revoked registration has no callbacks left. + fn invoke(&self, port: u32) -> bool { + { + let mut state = self.state.lock().unwrap(); + if state.revoked { + return false; + } + state.running += 1; + } + + MONITOR_DEPTH.with(|depth| depth.set(depth.get() + 1)); + unsafe { + let callback: XTaskQueueMonitorCallback = std::mem::transmute(self.cb); + callback(self.ctx as *mut c_void, self.queue_handle as *mut c_void, port); + } + MONITOR_DEPTH.with(|depth| depth.set(depth.get() - 1)); + + let mut state = self.state.lock().unwrap(); + state.running -= 1; + let drained = state.revoked && state.running == 0; + if drained { + self.idle.notify_all(); + } + drained + } + + fn revoke(&self) -> bool { + // Keep callback-stack unregistration nonblocking. Waiting from a monitor can + // deadlock with itself or with another monitor that unregisters it. + let outside_monitor = MONITOR_DEPTH.with(|depth| depth.get() == 0); + let mut state = self.state.lock().unwrap(); + state.revoked = true; + while outside_monitor && state.running != 0 { + state = self.idle.wait(state).unwrap(); + } + state.running == 0 + } } pub struct Port { @@ -89,7 +140,7 @@ pub struct Queue { owns_ports: bool, state: Mutex, idle_cv: Condvar, - monitors: Mutex>, + monitors: Mutex>>, } /// What an `XTaskQueueHandle` points to. @@ -237,14 +288,17 @@ impl Queue { } fn notify_monitors(&self, port: u32) { - let snapshot: Vec = self.monitors.lock().unwrap().clone(); - for m in snapshot { - unsafe { - let f: XTaskQueueMonitorCallback = std::mem::transmute(m.cb); - f(m.ctx as *mut c_void, m.queue_handle as *mut c_void, port); + let snapshot = self.monitors.lock().unwrap().clone(); + for monitor in snapshot { + if monitor.invoke(port) { + self.remove_monitor(monitor.token); } } } + + fn remove_monitor(&self, token: u64) { + self.monitors.lock().unwrap().retain(|monitor| monitor.token != token); + } } fn drain_serialized(p: Arc) { @@ -716,19 +770,28 @@ pub unsafe extern "system" fn XTaskQueueRegisterMonitor( return E_INVALIDARG; } let id = NEXT_MONITOR_TOKEN.fetch_add(1, Ordering::Relaxed); - q.monitors.lock().unwrap().push(Monitor { + q.monitors.lock().unwrap().push(Arc::new(Monitor { token: id, queue_handle: h as usize, ctx: ctx as usize, cb, - }); + state: Mutex::new(MonitorState::default()), + idle: Condvar::new(), + })); (*token).token = id; S_OK } pub unsafe extern "system" fn XTaskQueueUnregisterMonitor(h: *mut c_void, token: RegistrationToken) { let Some(q) = queue_from(h) else { return }; - q.monitors.lock().unwrap().retain(|m| m.token != token.token); + // Keep the registration discoverable until its callbacks finish so concurrent + // unregistration calls can wait for the same drain. Never wait with the queue lock held. + let monitor = q.monitors.lock().unwrap().iter().find(|m| m.token == token.token).cloned(); + if let Some(monitor) = monitor { + if monitor.revoke() { + q.remove_monitor(monitor.token); + } + } } #[cfg(test)] @@ -757,6 +820,147 @@ mod tests { } } + #[test] + fn unregister_monitor_waits_for_an_active_invocation() { + struct Capture { + entered: mpsc::Sender<()>, + release: Mutex>, + calls: AtomicU32, + } + + unsafe extern "system" fn monitor(ctx: *mut c_void, _: *mut c_void, _: u32) { + let capture = &*ctx.cast::(); + if capture.calls.fetch_add(1, Ordering::Relaxed) == 0 { + let _ = capture.entered.send(()); + let _ = capture.release.lock().unwrap().recv_timeout(Duration::from_secs(5)); + } + } + + unsafe extern "system" fn work(_: *mut c_void, _: bool) {} + + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let capture = Box::new(Capture { entered: entered_tx, release: Mutex::new(release_rx), calls: AtomicU32::new(0) }); + let mut h = std::ptr::null_mut(); + let mut token = RegistrationToken { token: 0 }; + unsafe { + assert_eq!(XTaskQueueCreate(MODE_IMMEDIATE, MODE_IMMEDIATE, &mut h), S_OK); + assert_eq!(XTaskQueueRegisterMonitor(h, (&*capture as *const Capture).cast_mut().cast(), monitor as usize, &mut token), S_OK); + } + + let handle = h as usize; + let submit = std::thread::spawn(move || unsafe { + XTaskQueueSubmitCallback(handle as *mut c_void, PORT_WORK, std::ptr::null_mut(), work as usize) + }); + let entered = entered_rx.recv_timeout(Duration::from_secs(2)); + let (started_tx, started_rx) = mpsc::channel(); + let (finished_tx, finished_rx) = mpsc::channel(); + let unregister: [_; 2] = std::array::from_fn(|_| { + let started = started_tx.clone(); + let finished = finished_tx.clone(); + let id = token.token; + std::thread::spawn(move || unsafe { + let _ = started.send(()); + XTaskQueueUnregisterMonitor(handle as *mut c_void, RegistrationToken { token: id }); + let _ = finished.send(()); + }) + }); + let started = (0..2).all(|_| started_rx.recv_timeout(Duration::from_secs(2)).is_ok()); + let early = finished_rx.recv_timeout(Duration::from_millis(250)); + let _ = release_tx.send(()); + let remaining = 2 - usize::from(early.is_ok()); + let finished = (0..remaining).all(|_| finished_rx.recv_timeout(Duration::from_secs(2)).is_ok()); + let submitted = submit.join().unwrap(); + for call in unregister { + call.join().unwrap(); + } + let second = unsafe { XTaskQueueSubmitCallback(h, PORT_WORK, std::ptr::null_mut(), work as usize) }; + unsafe { XTaskQueueCloseHandle(h) }; + + assert!(entered.is_ok() && started && finished, "monitor control threads did not finish their steps"); + assert!(matches!(early, Err(mpsc::RecvTimeoutError::Timeout)), "unregister returned before the active monitor ended"); + assert_eq!((submitted, second), (S_OK, S_OK)); + assert_eq!(capture.calls.load(Ordering::Relaxed), 1); + } + + #[test] + fn unregister_monitor_inside_its_callback_stops_later_invocations() { + struct Capture { + token: RegistrationToken, + calls: u32, + } + + unsafe extern "system" fn monitor(ctx: *mut c_void, queue: *mut c_void, _: u32) { + let capture = &mut *ctx.cast::(); + capture.calls += 1; + XTaskQueueUnregisterMonitor(queue, RegistrationToken { token: capture.token.token }); + } + + unsafe extern "system" fn work(_: *mut c_void, _: bool) {} + + let mut capture = Capture { token: RegistrationToken { token: 0 }, calls: 0 }; + let mut h = std::ptr::null_mut(); + unsafe { + assert_eq!(XTaskQueueCreate(MODE_IMMEDIATE, MODE_IMMEDIATE, &mut h), S_OK); + let ctx = (&mut capture as *mut Capture).cast(); + assert_eq!(XTaskQueueRegisterMonitor(h, ctx, monitor as usize, &mut capture.token), S_OK); + assert_eq!(XTaskQueueSubmitCallback(h, PORT_WORK, std::ptr::null_mut(), work as usize), S_OK); + assert_eq!(XTaskQueueSubmitCallback(h, PORT_WORK, std::ptr::null_mut(), work as usize), S_OK); + XTaskQueueCloseHandle(h); + } + assert_eq!(capture.calls, 1); + } + + #[test] + fn unregister_monitor_skips_a_revoked_snapshot_entry() { + struct Gate { + entered: mpsc::Sender<()>, + release: Mutex>, + } + + unsafe extern "system" fn hold(ctx: *mut c_void, _: *mut c_void, _: u32) { + let gate = &*ctx.cast::(); + let _ = gate.entered.send(()); + let _ = gate.release.lock().unwrap().recv_timeout(Duration::from_secs(5)); + } + + unsafe extern "system" fn count(ctx: *mut c_void, _: *mut c_void, _: u32) { + (*ctx.cast::()).fetch_add(1, Ordering::Relaxed); + } + + unsafe extern "system" fn work(_: *mut c_void, _: bool) {} + + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let gate = Gate { entered: entered_tx, release: Mutex::new(release_rx) }; + let calls = AtomicU32::new(0); + let mut h = std::ptr::null_mut(); + let mut blocker = RegistrationToken { token: 0 }; + let mut revoked = RegistrationToken { token: 0 }; + unsafe { + assert_eq!(XTaskQueueCreate(MODE_IMMEDIATE, MODE_IMMEDIATE, &mut h), S_OK); + assert_eq!(XTaskQueueRegisterMonitor(h, (&gate as *const Gate).cast_mut().cast(), hold as usize, &mut blocker), S_OK); + assert_eq!(XTaskQueueRegisterMonitor(h, (&calls as *const AtomicU32).cast_mut().cast(), count as usize, &mut revoked), S_OK); + } + + let handle = h as usize; + let submit = std::thread::spawn(move || unsafe { + XTaskQueueSubmitCallback(handle as *mut c_void, PORT_WORK, std::ptr::null_mut(), work as usize) + }); + let entered = entered_rx.recv_timeout(Duration::from_secs(2)); + unsafe { XTaskQueueUnregisterMonitor(h, revoked) }; + let _ = release_tx.send(()); + let submitted = submit.join().unwrap(); + unsafe { + XTaskQueueUnregisterMonitor(h, blocker); + XTaskQueueCloseHandle(h); + } + + assert!(entered.is_ok(), "first monitor did not hold the notification snapshot"); + assert_eq!(submitted, S_OK); + assert_eq!(calls.load(Ordering::Relaxed), 0, "revoked monitor still ran from an old snapshot"); + } + #[test] fn closed_and_stray_handles_are_not_read() { unsafe {