diff --git a/crates/xcl/src/report.rs b/crates/xcl/src/report.rs index 45b886e103..8d53b8345b 100644 --- a/crates/xcl/src/report.rs +++ b/crates/xcl/src/report.rs @@ -17,6 +17,12 @@ pub struct StubCall { pub function: String, pub calls: u64, pub first_caller: String, + /// first call's R8/R9 (3rd/4th Win64 argument registers), hex `"{r8:#x} {r9:#x}"` + #[serde(default, skip_serializing_if = "Option::is_none")] + pub first_args: Option, + /// most recent call's R8/R9, same format + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_args: Option, } #[derive(Debug, Serialize, Deserialize, Default)] @@ -113,11 +119,16 @@ pub fn build() -> Report { let mut called: Vec = crate::stubs::all_stubs() .into_iter() .filter(|s| s.calls.load(Ordering::Relaxed) > 0) - .map(|s| StubCall { - dll: s.dll.clone(), - function: s.name.clone(), - calls: s.calls.load(Ordering::Relaxed), - first_caller: crate::modules::describe_address(s.first_caller.load(Ordering::Relaxed)), + .map(|s| { + let args = crate::stubs::stub_args(s); + StubCall { + dll: s.dll.clone(), + function: s.name.clone(), + calls: s.calls.load(Ordering::Relaxed), + first_caller: crate::modules::describe_address(s.first_caller.load(Ordering::Relaxed)), + first_args: args.map(|(fr8, fr9, _, _)| format!("{fr8:#x} {fr9:#x}")), + last_args: args.map(|(_, _, lr8, lr9)| format!("{lr8:#x} {lr9:#x}")), + } }) .collect(); called.sort_by(|a, b| b.calls.cmp(&a.calls)); diff --git a/crates/xcl/src/stubs.rs b/crates/xcl/src/stubs.rs index 1fd0eca24c..8b516fd393 100644 --- a/crates/xcl/src/stubs.rs +++ b/crates/xcl/src/stubs.rs @@ -36,6 +36,39 @@ pub type StubHook = fn(&StubInfo, usize); static ALL: Mutex> = Mutex::new(Vec::new()); static ARENA: Mutex<(usize, usize)> = Mutex::new((0, 0)); // (next, end) static BY_KEY: OnceLock>> = OnceLock::new(); +/// (first_ord, last_ord, first_r8, first_r9, last_r8, last_r9) of every thunk-called stub, +/// keyed by info address. The ordinal pair travels with the args so a caller that grabs its +/// ordinal before another but enters the table after it still records its args as first/last. +static ARGS: OnceLock>> = OnceLock::new(); + +/// Test-only injection point: blocks the ordinal-holding caller between fetch_add and the +/// side-table update so a two-thread fixture can force the first caller into the table second. +/// Only the caller whose info matches the armed key waits; others proceed. Consumed (taken) +/// on use; None in release builds. +#[cfg(test)] +static BEFORE_TABLE_UPDATE: Mutex, std::sync::mpsc::Receiver<()>, usize)>> = + Mutex::new(None); + +#[cfg(test)] +fn arm_before_table_update(key: usize) -> (std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>) { + let (resume_tx, resume_rx) = std::sync::mpsc::channel(); + let (arrived, arrive_rx) = std::sync::mpsc::channel(); + *BEFORE_TABLE_UPDATE.lock().unwrap() = Some((arrived, resume_rx, key)); + (resume_tx, arrive_rx) +} + +#[cfg(test)] +fn pause_before_table_update(info: &StubInfo) { + let mut guard = BEFORE_TABLE_UPDATE.lock().unwrap(); + if let Some((_, _, armed_key)) = guard.as_ref() { + if (info as *const StubInfo as usize) == *armed_key { + let Some((arrived, resume, _)) = guard.take() else { return }; + drop(guard); + let _ = arrived.send(()); + let _ = resume.recv(); + } + } +} const THUNK_SIZE: usize = 48; const ARENA_CHUNK: usize = 64 * 1024; @@ -60,12 +93,63 @@ pub fn record_call(info: &StubInfo, caller: usize) { } } -unsafe extern "system" fn stub_report(info: *const StubInfo, caller: usize) -> u64 { +unsafe extern "system" fn stub_report(info: *const StubInfo, caller: usize, r8: u64, r9: u64) -> u64 { let info = &*info; - record_call(info, caller); + record_call_with_args(info, caller, r8, r9); info.ret } +/// Count a call, log the first one, run the hook. `r8`/`r9` are the 3rd/4th Win64 argument +/// registers of the stub call (recorded in the side table keyed by `info`). +pub fn record_call_with_args(info: &StubInfo, caller: usize, r8: u64, r9: u64) { + let n = info.calls.fetch_add(1, Ordering::Relaxed); + #[cfg(test)] + pause_before_table_update(info); + // Hold the ARGS mutex across the table update so the args recorded first/last always + // match the ordinal implied by their label. The first-call log and hook stay outside the mutex. + { + let key = info as *const StubInfo as usize; + let mut g = ARGS.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap(); + let entry = g.entry(key).or_insert((n, n, r8, r9, r8, r9)); + if n < entry.0 { + // an earlier ordinal arrived late: this is the first call + entry.0 = n; + entry.2 = r8; + entry.3 = r9; + } + if n > entry.1 { + // a later ordinal arrived (last) + entry.1 = n; + entry.4 = r8; + entry.5 = r9; + } + } + if n == 0 { + info.first_caller.store(caller, Ordering::Relaxed); + crate::xlog_warn!( + "[STUB] {}!{} first called from {} → returning {:#x}", + info.dll, + info.name, + crate::modules::describe_address(caller), + info.ret + ); + } + let h = info.hook.load(Ordering::Acquire); + if h != 0 { + let f: StubHook = unsafe { std::mem::transmute(h) }; + f(info, caller); + } +} + +/// (first_r8, first_r9, last_r8, last_r9) recorded for `info`, if any call went through +/// a thunk (or `record_call_with_args`). +pub fn stub_args(info: &'static StubInfo) -> Option<(u64, u64, u64, u64)> { + let key = info as *const StubInfo as usize; + let g = ARGS.get()?.lock().ok()?; + let (_, _, fr8, fr9, lr8, lr9) = g.get(&key).copied()?; + Some((fr8, fr9, lr8, lr9)) +} + /// A StubInfo that is not backed by a stub thunk (used by D3D12.X slot guards). pub fn new_info(dll: &str, name: &str, ret: u64) -> &'static StubInfo { let info: &'static StubInfo = Box::leak(Box::new(StubInfo { @@ -262,6 +346,10 @@ pub fn db() -> &'static StubDb { DB.get_or_init(|| StubDb::parse(BUILTIN_DB, &Default::default())) } +#[cfg(test)] +#[path = "stubs_args_tests.rs"] +mod stubs_args_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/xcl/src/stubs_args_tests.rs b/crates/xcl/src/stubs_args_tests.rs new file mode 100644 index 0000000000..775173c021 --- /dev/null +++ b/crates/xcl/src/stubs_args_tests.rs @@ -0,0 +1,82 @@ +use super::*; + +#[test] +fn ordinal_first_caller_arriving_late_still_records_as_first_and_last() { + let (addr, info) = make_stub_info("args-race.dll", "ArgsRace", 9); + let key = info as *const StubInfo as usize; + let (resume_tx, arrived_rx) = arm_before_table_update(key); + let f: extern "system" fn(u64, u64, u64, u64) -> u64 = + unsafe { std::mem::transmute(addr) }; + let handle = std::thread::spawn(move || f(0, 0, 0x0A01, 0x0A02)); + arrived_rx.recv().unwrap(); // A holds ordinal 0, paused before the table update + let b = std::thread::spawn(move || f(0, 0, 0x0B01, 0x0B02)); + // Let B (ordinal 1) enter and update the table before A resumes. + let mut tries = 0; + while stub_args(info).is_none() { + std::thread::sleep(std::time::Duration::from_millis(1)); + tries += 1; + assert!(tries < 1000, "B never entered the side table"); + } + resume_tx.send(()).unwrap(); + handle.join().unwrap(); + b.join().unwrap(); + let (fr8, fr9, lr8, lr9) = stub_args(info).expect("args recorded"); + // A (ordinal 0) is the first call even though it entered the table second + assert_eq!((fr8, fr9), (0x0A01, 0x0A02)); + assert_eq!((lr8, lr9), (0x0B01, 0x0B02)); + assert_eq!(info.calls.load(Ordering::Relaxed), 2); +} + +#[test] +fn thunk_records_first_and_last_r8_r9_args() { + let (addr, info) = make_stub_info("args.dll", "ArgsRecord", 7); + let f: extern "system" fn(u64, u64, u64, u64) -> u64 = + unsafe { std::mem::transmute(addr) }; + assert_eq!(f(0, 0, 0x1111, 0x2222), 7); + assert_eq!(f(0, 0, 0x3333, 0x4444), 7); + let (fr8, fr9, lr8, lr9) = stub_args(info).expect("args recorded"); + assert_eq!(fr8, 0x1111); + assert_eq!(fr9, 0x2222); + assert_eq!(lr8, 0x3333); + assert_eq!(lr9, 0x4444); + assert_eq!(info.calls.load(Ordering::Relaxed), 2); +} + +#[test] +fn record_call_without_args_leaves_side_table_empty() { + let info = new_info("args-noargs.dll", "NoArgs", 0); + record_call(info, 0x1234); + assert_eq!(info.calls.load(Ordering::Relaxed), 1); + assert!(stub_args(info).is_none()); +} + +#[test] +fn stub_call_serializes_args_only_when_present() { + let (addr, info) = make_stub_info("args-ser.dll", "ArgsSer", 1); + let f: extern "system" fn(u64, u64, u64, u64) -> u64 = + unsafe { std::mem::transmute(addr) }; + f(0, 0, 0xabc, 0xdef); + let (fr8, fr9, lr8, lr9) = stub_args(info).unwrap(); + let call = crate::report::StubCall { + dll: info.dll.clone(), + function: info.name.clone(), + calls: info.calls.load(Ordering::Relaxed), + first_caller: String::new(), + first_args: Some(format!("{fr8:#x} {fr9:#x}")), + last_args: Some(format!("{lr8:#x} {lr9:#x}")), + }; + let s = serde_json::to_string(&call).unwrap(); + assert!(s.contains("first_args")); + assert!(s.contains("last_args")); + let call2 = crate::report::StubCall { + dll: "d.dll".into(), + function: "no-args".into(), + calls: 1, + first_caller: String::new(), + first_args: None, + last_args: None, + }; + let s2 = serde_json::to_string(&call2).unwrap(); + assert!(!s2.contains("first_args")); + assert!(!s2.contains("last_args")); +}