diff --git a/d3d12/apps/leonida/src/run.rs b/d3d12/apps/leonida/src/run.rs index 2d2e383d66..5bfd35f86d 100644 --- a/d3d12/apps/leonida/src/run.rs +++ b/d3d12/apps/leonida/src/run.rs @@ -72,6 +72,15 @@ pub fn run( drop(prepared); drop(original); leonida_hle::runtime::set_main_image(image.base()); + // `LEONIDA_CALL_TRACE=`: every import call of the title goes to that file (call_trace.rs); the file must be + // new, and the title does not start without it. Unset: nothing changes. + if leonida_loader::call_trace::open_from_env()? { + leonida_loader::call_trace::add_module( + "game", + image.base(), + image.info().size_of_image as usize, + ); + } // Where the Lua mods' memory scan looks (`LEONIDA_LUA=0`: nothing reads it). leonida_lua::set_image(image.base(), image.info().size_of_image as usize); leonida_hle::runtime::set_image_path(image.base(), exe); @@ -123,6 +132,7 @@ pub fn run( leonida_hle::modules::ffx::set_real_create(real); } println!("title dll {name} at {:#x}", dll.base()); + leonida_loader::call_trace::add_module(name, dll.base(), dll.info().size_of_image as usize); leonida_hle::runtime::set_image_path(dll.base(), &title_dir.join(name)); } let imported: Vec<&str> = image @@ -449,6 +459,11 @@ impl LateDlls { "title dll {name} at {:#x} (loaded by the title)", dll.base() ); + leonida_loader::call_trace::add_module( + name, + dll.base(), + dll.info().size_of_image as usize, + ); show(name, dll.bind_imports(&resolver, self.policy)?); set_image_path(dll.base(), &self.title_dir.join(name)); } diff --git a/d3d12/crates/leonida-loader/Cargo.toml b/d3d12/crates/leonida-loader/Cargo.toml index 1bec91272e..532ebfc633 100644 --- a/d3d12/crates/leonida-loader/Cargo.toml +++ b/d3d12/crates/leonida-loader/Cargo.toml @@ -19,6 +19,8 @@ blake3.workspace = true windows-sys = { workspace = true, features = [ "Wdk_System_Threading", "Win32_Foundation", + "Win32_Security", + "Win32_Storage_FileSystem", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", diff --git a/d3d12/crates/leonida-loader/src/call_trace.rs b/d3d12/crates/leonida-loader/src/call_trace.rs new file mode 100644 index 0000000000..37a8332163 --- /dev/null +++ b/d3d12/crates/leonida-loader/src/call_trace.rs @@ -0,0 +1,1181 @@ +//! The import call trace (`LEONIDA_CALL_TRACE=`): a file of every call the title makes through its import +//! address tables, in the format both runtimes write so their traces can be compared (`tools/call_trace_diff.py`). +//! +//! With the switch unset nothing happens: [`wrap`] returns the address it was given and no code is generated. +//! With it set, each import of the main image and the title's DLLs gets a 24-byte thunk that loads its +//! [`Site`] into `r10` and jumps to one of two stubs of a common block (bytes in [`BLOB`], assembled from the +//! `global_asm!` source in the harness that tested them: 20 integer arguments, float arguments, a struct return, +//! the last error and a panic unwinding through both stubs): +//! +//! - the entry stub records an `E` line, restores the argument registers and jumps to the target, so no frame is +//! left between the title and the callee (setjmp, the exit and unwind functions, printf); +//! - the wrap stub records a `C` line, copies 16 stack-argument qwords, calls the target and records the `R` line. +//! +//! There is no shadow stack and no TLS: a longjmp or an exception past a wrap frame leaves a `C` without an `R`. +//! The record functions call only host APIs directly, keep the last error and have no destructor-bearing +//! thread-locals (the title's own thread-exit registration must not be taken). +//! +//! Format (UTF-8, LF, TAB-separated; the file is memory-mapped, so it may end in NULs and a partial last line): +//! +//! ```text +//! # leonida-call-trace 1 stack=leonida-hle rules=<16 hex> +//! # title-bound +//! # truncated +//! T +//! C ! +//! R +//! E ! +//! ``` +//! +//! The rules (what is skipped, entry-only, and how a return value is classified) are +//! `tools/call_trace_rules.def`, parsed here and hashed into the header (FNV-1a 64 over each rule in file order: +//! macro name, NUL, then each argument and a NUL). Raw return values and buffers are never written. + +use std::cell::{Cell, UnsafeCell}; +use std::collections::HashSet; +use std::ffi::c_void; +use std::path::Path; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Mutex, MutexGuard, OnceLock, TryLockError}; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, bail}; +use windows_sys::Wdk::System::Threading::NtQueryInformationThread; +use windows_sys::Win32::Foundation::{ + CloseHandle, FILETIME, GENERIC_READ, GENERIC_WRITE, GetLastError, HANDLE, INVALID_HANDLE_VALUE, + SetLastError, +}; +use windows_sys::Win32::Storage::FileSystem::{ + CREATE_NEW, CreateFileW, DELETE, FILE_ATTRIBUTE_NORMAL, FILE_FLAG_DELETE_ON_CLOSE, + FILE_SHARE_READ, +}; +use windows_sys::Win32::System::Diagnostics::Debug::{FlushInstructionCache, RtlAddFunctionTable}; +use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MEMORY_BASIC_INFORMATION, + MapViewOfFile, PAGE_EXECUTE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, + PAGE_READWRITE, UnmapViewOfFile, VirtualAlloc, VirtualProtect, VirtualQuery, +}; +use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, GetCurrentThread, GetCurrentThreadId, GetThreadTimes, +}; + +/// The switch naming the file; unset or empty: no trace. +pub const ENV_PATH: &str = "LEONIDA_CALL_TRACE"; +/// Size cap of the file in MiB (default 4096); at the cap `# truncated` is written and tracing stops. +pub const ENV_MAX_MB: &str = "LEONIDA_CALL_TRACE_MAX_MB"; +const DEFAULT_MAX_MB: u64 = 4096; + +/// The shared rules, read by both runtimes. +const RULES: &str = include_str!("../../../../tools/call_trace_rules.def"); + +/// Who provides the import: the `bind` field of a record. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Bind { + /// A shim of the C++ runtime (never used by this stack). + Shim, + /// Our implementation of the console API. + Hle, + /// The host's own implementation. + Host, + /// The stub of an import nobody implements; traced at entry only. + Unimpl, +} + +impl Bind { + fn text(self) -> &'static str { + match self { + Bind::Shim => "shim", + Bind::Hle => "hle", + Bind::Host => "host", + Bind::Unimpl => "unimpl", + } + } +} + +// --------------------------------------------------------------------------------------------------------- +// Rules + +/// One parsed rule: the macro name and its string arguments, in file order. +type Rule = (String, Vec); + +/// Parses the rules text: one `CT_NAME("a"[, "b"])` per line, `//` comments and blank lines ignored. +pub fn parse_rules(text: &str) -> Result> { + let mut rules = Vec::new(); + for (n, raw) in text.lines().enumerate() { + let line = raw.trim(); + if line.is_empty() || line.starts_with("//") { + continue; + } + let at = |what: &str| format!("rules line {}: {what}: {line}", n + 1); + let open = line.find('(').with_context(|| at("no '('"))?; + let name = line[..open].trim(); + if !name.starts_with("CT_") || name[3..].is_empty() || !name.bytes().all(is_macro_char) { + bail!(at("not a CT_ macro name")); + } + let mut rest = line[open + 1..] + .strip_suffix(')') + .with_context(|| at("no closing ')'"))? + .trim(); + let mut args = Vec::new(); + loop { + let Some(body) = rest.strip_prefix('"') else { + bail!(at("argument is not a string literal")); + }; + let end = body + .find('"') + .with_context(|| at("unterminated string literal"))?; + if body[..end].contains('\\') { + bail!(at("escapes are not supported")); + } + args.push(body[..end].to_owned()); + rest = body[end + 1..].trim_start(); + if rest.is_empty() { + break; + } + let Some(next) = rest.strip_prefix(',') else { + bail!(at("expected ',' between arguments")); + }; + rest = next.trim_start(); + } + match arity(name) { + None => bail!(at("unknown rule")), + Some(n) if n != args.len() => { + bail!(at(&format!( + "{name} takes {n} argument(s), not {}", + args.len() + ))) + } + Some(_) => {} + } + rules.push((name.to_owned(), args)); + } + Ok(rules) +} + +/// How many string arguments a rule macro takes; `None` for a macro this build does not know. +fn arity(name: &str) -> Option { + match name { + "CT_SKIP" | "CT_SKIP_HAS" | "CT_SKIP_MODULE" | "CT_ENTRY" | "CT_ENTRY_HAS" | "CT_VOID" + | "CT_BOOL" | "CT_U32" | "CT_HR" | "CT_NOT_HR" => Some(1), + "CT_HR_MOD" => Some(2), + _ => None, + } +} + +fn is_macro_char(b: u8) -> bool { + b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_' +} + +/// FNV-1a 64 over each rule in file order: macro name, NUL, then each argument followed by a NUL. +pub fn hash_rules(rules: &[Rule]) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + let mut feed = |bytes: &[u8]| { + for &b in bytes { + h ^= u64::from(b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + }; + for (name, args) in rules { + feed(name.as_bytes()); + feed(&[0]); + for arg in args { + feed(arg.as_bytes()); + feed(&[0]); + } + } + h +} + +/// The hash of the committed rules file, as written in the header of every trace. +pub fn rules_hash() -> u64 { + rules().hash +} + +/// How a return value is written. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Class { + /// `p:0`, `p:1` or `p:-1`. + Ptr, + /// `-`. + Void, + /// `b:0|1` (AL). + Bool, + /// `u:0x%08x`. + U32, + /// `hr:0x%08x`. + Hr, +} + +/// What the rules say about one import. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Decision { + /// Bound as without the trace: no thunk, no record. + Skip, + /// An `E` record by a jump, no frame. + Entry, + /// A `C` record, the call, an `R` record with the return value in this class. + Wrap(Class), +} + +#[derive(Default)] +struct Rules { + skip: HashSet, + skip_has: Vec, + skip_module: Vec, + entry: HashSet, + entry_has: Vec, + void: HashSet, + boolean: HashSet, + u32: HashSet, + hr: HashSet, + hr_mod: Vec<(String, String)>, + not_hr: HashSet, + hash: u64, +} + +/// The committed rules, parsed once; an error is a rules file this build cannot use (reported by [`open`]). +fn rules_result() -> &'static Result { + static PARSED: OnceLock> = OnceLock::new(); + PARSED.get_or_init(|| build_rules(RULES).map_err(|e| format!("{e:#}"))) +} + +fn rules() -> &'static Rules { + // Only reached once `open` has accepted the file. + rules_result() + .as_ref() + .unwrap_or_else(|e| panic!("tools/call_trace_rules.def: {e}")) +} + +fn build_rules(text: &str) -> Result { + let parsed = parse_rules(text)?; + let mut r = Rules { + hash: hash_rules(&parsed), + ..Rules::default() + }; + for (name, args) in parsed { + let one = args.first().cloned().unwrap_or_default(); + match name.as_str() { + "CT_SKIP" => drop(r.skip.insert(one)), + "CT_SKIP_HAS" => r.skip_has.push(one), + "CT_SKIP_MODULE" => r.skip_module.push(one), + "CT_ENTRY" => drop(r.entry.insert(one)), + "CT_ENTRY_HAS" => r.entry_has.push(one), + "CT_VOID" => drop(r.void.insert(one)), + "CT_BOOL" => drop(r.boolean.insert(one)), + "CT_U32" => drop(r.u32.insert(one)), + "CT_HR" => drop(r.hr.insert(one)), + "CT_HR_MOD" => r.hr_mod.push((one, args[1].clone())), + "CT_NOT_HR" => drop(r.not_hr.insert(one)), + other => bail!("unknown rule {other}"), + } + } + Ok(r) +} + +/// Applies the rules to an import: `module` is the lower-case DLL name, `function` the import name or `#ordinal`. +/// Order of precedence: skip, then entry, then the class (void, bool, u32, hr, not-hr, hr-by-module, else pointer). +pub fn classify(module: &str, function: &str) -> Decision { + let r = rules(); + if r.skip.contains(function) + || r.skip_has.iter().any(|t| function.contains(t.as_str())) + || r.skip_module.iter().any(|p| module.starts_with(p.as_str())) + { + return Decision::Skip; + } + if r.entry.contains(function) || r.entry_has.iter().any(|t| function.contains(t.as_str())) { + return Decision::Entry; + } + let class = if r.void.contains(function) { + Class::Void + } else if r.boolean.contains(function) { + Class::Bool + } else if r.u32.contains(function) { + Class::U32 + } else if r.hr.contains(function) { + Class::Hr + } else if r.not_hr.contains(function) { + Class::Ptr + } else if r + .hr_mod + .iter() + .any(|(m, p)| module == m && function.starts_with(p.as_str())) + { + Class::Hr + } else { + Class::Ptr + }; + Decision::Wrap(class) +} + +// --------------------------------------------------------------------------------------------------------- +// The common stub + +/// The common stub: entry stub 0x000..0x082, wrap stub 0x090..0x19a, `enter` pointer at 0x1a0, `leave` pointer at +/// 0x1a8, UNWIND_INFO at 0x1b0 and 0x1b8, RUNTIME_FUNCTION[2] at 0x1c0 (relative to the blob start). +/// One byte differs from the assembled source: the entry function's EndAddress (0x1c4) is 0x7F, not 0x82, so the +/// final `jmp [r10]` (0x7F) is outside any unwind range, where the unwinder's leaf rule reads the return address +/// at RSP (it does not recognise that jump as an epilogue). The instruction bytes are untouched. +#[rustfmt::skip] +const BLOB: [u8; 0x1d8] = [ + 0x48, 0x81, 0xEC, 0x98, 0x00, 0x00, 0x00, 0x48, 0x89, 0x4C, 0x24, 0x20, 0x48, 0x89, 0x54, 0x24, + 0x28, 0x4C, 0x89, 0x44, 0x24, 0x30, 0x4C, 0x89, 0x4C, 0x24, 0x38, 0x0F, 0x29, 0x44, 0x24, 0x40, + 0x0F, 0x29, 0x4C, 0x24, 0x50, 0x0F, 0x29, 0x54, 0x24, 0x60, 0x0F, 0x29, 0x5C, 0x24, 0x70, 0x4C, + 0x89, 0x94, 0x24, 0x80, 0x00, 0x00, 0x00, 0x4C, 0x89, 0xD1, 0x48, 0x8B, 0x94, 0x24, 0x98, 0x00, + 0x00, 0x00, 0xFF, 0x15, 0x58, 0x01, 0x00, 0x00, 0x4C, 0x8B, 0x94, 0x24, 0x80, 0x00, 0x00, 0x00, + 0x48, 0x8B, 0x4C, 0x24, 0x20, 0x48, 0x8B, 0x54, 0x24, 0x28, 0x4C, 0x8B, 0x44, 0x24, 0x30, 0x4C, + 0x8B, 0x4C, 0x24, 0x38, 0x0F, 0x28, 0x44, 0x24, 0x40, 0x0F, 0x28, 0x4C, 0x24, 0x50, 0x0F, 0x28, + 0x54, 0x24, 0x60, 0x0F, 0x28, 0x5C, 0x24, 0x70, 0x48, 0x81, 0xC4, 0x98, 0x00, 0x00, 0x00, 0x41, + 0xFF, 0x22, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, + 0x48, 0x81, 0xEC, 0x38, 0x01, 0x00, 0x00, 0x48, 0x89, 0x8C, 0x24, 0xA0, 0x00, 0x00, 0x00, 0x48, + 0x89, 0x94, 0x24, 0xA8, 0x00, 0x00, 0x00, 0x4C, 0x89, 0x84, 0x24, 0xB0, 0x00, 0x00, 0x00, 0x4C, + 0x89, 0x8C, 0x24, 0xB8, 0x00, 0x00, 0x00, 0x0F, 0x29, 0x84, 0x24, 0xC0, 0x00, 0x00, 0x00, 0x0F, + 0x29, 0x8C, 0x24, 0xD0, 0x00, 0x00, 0x00, 0x0F, 0x29, 0x94, 0x24, 0xE0, 0x00, 0x00, 0x00, 0x0F, + 0x29, 0x9C, 0x24, 0xF0, 0x00, 0x00, 0x00, 0x4C, 0x89, 0x94, 0x24, 0x00, 0x01, 0x00, 0x00, 0x4C, + 0x89, 0xD1, 0x48, 0x8B, 0x94, 0x24, 0x38, 0x01, 0x00, 0x00, 0xFF, 0x15, 0xB0, 0x00, 0x00, 0x00, + 0x48, 0x89, 0x84, 0x24, 0x08, 0x01, 0x00, 0x00, 0x31, 0xC0, 0x4C, 0x8B, 0x9C, 0xC4, 0x60, 0x01, + 0x00, 0x00, 0x4C, 0x89, 0x5C, 0xC4, 0x20, 0xFF, 0xC0, 0x83, 0xF8, 0x10, 0x72, 0xEC, 0x4C, 0x8B, + 0x94, 0x24, 0x00, 0x01, 0x00, 0x00, 0x48, 0x8B, 0x8C, 0x24, 0xA0, 0x00, 0x00, 0x00, 0x48, 0x8B, + 0x94, 0x24, 0xA8, 0x00, 0x00, 0x00, 0x4C, 0x8B, 0x84, 0x24, 0xB0, 0x00, 0x00, 0x00, 0x4C, 0x8B, + 0x8C, 0x24, 0xB8, 0x00, 0x00, 0x00, 0x0F, 0x28, 0x84, 0x24, 0xC0, 0x00, 0x00, 0x00, 0x0F, 0x28, + 0x8C, 0x24, 0xD0, 0x00, 0x00, 0x00, 0x0F, 0x28, 0x94, 0x24, 0xE0, 0x00, 0x00, 0x00, 0x0F, 0x28, + 0x9C, 0x24, 0xF0, 0x00, 0x00, 0x00, 0x41, 0xFF, 0x12, 0x48, 0x89, 0x84, 0x24, 0x10, 0x01, 0x00, + 0x00, 0x0F, 0x29, 0x84, 0x24, 0x20, 0x01, 0x00, 0x00, 0x48, 0x8B, 0x8C, 0x24, 0x00, 0x01, 0x00, + 0x00, 0x48, 0x8B, 0x94, 0x24, 0x08, 0x01, 0x00, 0x00, 0x49, 0x89, 0xC0, 0xFF, 0x15, 0x26, 0x00, + 0x00, 0x00, 0x48, 0x8B, 0x84, 0x24, 0x10, 0x01, 0x00, 0x00, 0x0F, 0x28, 0x84, 0x24, 0x20, 0x01, + 0x00, 0x00, 0x48, 0x81, 0xC4, 0x38, 0x01, 0x00, 0x00, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x01, 0x07, 0x02, 0x00, 0x07, 0x01, 0x13, 0x00, 0x01, 0x07, 0x02, 0x00, 0x07, 0x01, 0x27, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x7F, 0x00, 0x00, 0x00, 0xB0, 0x01, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00, + 0x9A, 0x01, 0x00, 0x00, 0xB8, 0x01, 0x00, 0x00, +]; +const WRAP_AT: usize = 0x090; +const ENTER_AT: usize = 0x1a0; +const LEAVE_AT: usize = 0x1a8; +const RUNTIME_FUNCTIONS_AT: usize = 0x1c0; + +/// What one wrapped import knows. Leaked: lives as long as the process. `target` must stay at offset 0: the +/// entry stub ends in `jmp [r10]` and the wrap stub in `call [r10]`. +#[repr(C)] +struct Site { + target: usize, + wrap: bool, + class: Class, + bind: Bind, + /// `module!function`, at most [`NAME_MAX`] bytes. + name: Box, +} + +const NAME_MAX: usize = 160; + +/// The common block (its address), installed when the trace is opened. +static COMMON: AtomicUsize = AtomicUsize::new(0); + +fn install_common() -> Result { + // SAFETY: fresh anonymous allocation. + let page = unsafe { + VirtualAlloc( + std::ptr::null(), + 4096, + MEM_COMMIT | MEM_RESERVE, + PAGE_READWRITE, + ) + } as *mut u8; + if page.is_null() { + bail!( + "VirtualAlloc for the call trace stub failed: {}", + std::io::Error::last_os_error() + ); + } + // SAFETY: the page is 4096 bytes, writable, and the blob is smaller; the slots are 8-aligned qwords. + unsafe { + std::ptr::copy_nonoverlapping(BLOB.as_ptr(), page, BLOB.len()); + let enter: extern "system" fn(&Site, usize) -> u64 = enter; + let leave: extern "system" fn(&Site, u64, u64) = leave; + (page.add(ENTER_AT) as *mut u64).write(enter as *const () as u64); + (page.add(LEAVE_AT) as *mut u64).write(leave as *const () as u64); + // Unwinding (exceptions, panics, stack walks other than RtlCaptureStackBackTrace) crosses both stubs. + if !RtlAddFunctionTable( + page.add(RUNTIME_FUNCTIONS_AT) as *const _, + 2, + page as usize as u64, + ) { + bail!("RtlAddFunctionTable for the call trace stub failed"); + } + let mut old = 0; + if VirtualProtect(page as *const c_void, 4096, PAGE_EXECUTE_READ, &mut old) == 0 { + bail!( + "VirtualProtect for the call trace stub failed: {}", + std::io::Error::last_os_error() + ); + } + FlushInstructionCache(GetCurrentProcess(), page as *const c_void, 4096); + } + Ok(page as usize) +} + +// --------------------------------------------------------------------------------------------------------- +// Thunks: 24 bytes each, written into RW blocks and sealed RX by [`seal`]. + +const THUNK_SIZE: usize = 24; +const BLOCK_SIZE: usize = 64 * 1024; + +struct Pending { + base: *mut u8, + used: usize, +} +// SAFETY: the block is private memory only the holder of the mutex touches. +unsafe impl Send for Pending {} + +static PENDING: Mutex = Mutex::new(Pending { + base: std::ptr::null_mut(), + used: 0, +}); +static BLOCKS: AtomicUsize = AtomicUsize::new(0); + +/// How many thunk blocks were allocated (zero with the trace off). +pub fn thunk_blocks() -> usize { + BLOCKS.load(Ordering::Relaxed) +} + +fn emit_thunk(site: &'static Site, stub: usize) -> Option { + let mut p = PENDING.lock().unwrap_or_else(|e| e.into_inner()); + if p.base.is_null() || p.used + THUNK_SIZE > BLOCK_SIZE { + // A full block is sealed on the way (nothing writes into it again); `seal` reports a failure. + if !seal_locked(&mut p) { + SEAL_FAILED.store(true, Ordering::Relaxed); + } + // SAFETY: fresh anonymous allocation. + let base = unsafe { + VirtualAlloc( + std::ptr::null(), + BLOCK_SIZE, + MEM_COMMIT | MEM_RESERVE, + PAGE_READWRITE, + ) + } as *mut u8; + if base.is_null() { + return None; + } + BLOCKS.fetch_add(1, Ordering::Relaxed); + p.base = base; + p.used = 0; + } + let mut code = [0xCC_u8; THUNK_SIZE]; // int3 padding + code[0..2].copy_from_slice(&[0x49, 0xBA]); // mov r10, imm64 + code[2..10].copy_from_slice(&(site as *const Site as u64).to_le_bytes()); + code[10..12].copy_from_slice(&[0x48, 0xB8]); // mov rax, imm64 + code[12..20].copy_from_slice(&(stub as u64).to_le_bytes()); + code[20..22].copy_from_slice(&[0xFF, 0xE0]); // jmp rax + // SAFETY: `used + THUNK_SIZE <= BLOCK_SIZE` and the block is still writable. + let at = unsafe { + let at = p.base.add(p.used); + std::ptr::copy_nonoverlapping(code.as_ptr(), at, THUNK_SIZE); + at + }; + p.used += THUNK_SIZE; + Some(at as usize) +} + +/// Set when a block could not be made executable on the way (a full block is sealed by [`emit_thunk`]). +static SEAL_FAILED: AtomicBool = AtomicBool::new(false); + +fn seal_locked(p: &mut Pending) -> bool { + if p.base.is_null() { + return true; + } + let mut old = 0; + // SAFETY: `base..base+BLOCK_SIZE` is the allocation made in `emit_thunk`; it is leaked on purpose, as title + // code may hold the thunk addresses for the life of the process. + let ok = unsafe { + let ok = VirtualProtect( + p.base as *const c_void, + BLOCK_SIZE, + PAGE_EXECUTE_READ, + &mut old, + ) != 0; + FlushInstructionCache(GetCurrentProcess(), p.base as *const c_void, BLOCK_SIZE); + ok + }; + p.base = std::ptr::null_mut(); + p.used = 0; + ok +} + +/// Makes the thunks emitted since the last call executable. Call it after the wraps of one bind, before the +/// addresses are written into the import tables, and fail the bind on an error: the thunks are in memory that +/// cannot run. It seals whatever is pending even if the size cap has stopped the recording meanwhile (thunks made +/// after the cap record nothing). Nothing to do when no thunk was made, so with the trace off. +pub fn seal() -> Result<()> { + let sealed = seal_locked(&mut PENDING.lock().unwrap_or_else(|e| e.into_inner())); + if !sealed || SEAL_FAILED.swap(false, Ordering::Relaxed) { + bail!( + "VirtualProtect for the call trace thunks failed: {}", + std::io::Error::last_os_error() + ); + } + Ok(()) +} + +// --------------------------------------------------------------------------------------------------------- +// Modules (caller and thread start) + +const MAX_MODULES: usize = 64; +const MODULE_NAME_MAX: usize = 47; + +struct ModuleEntry { + ready: AtomicBool, + base: UnsafeCell, + size: UnsafeCell, + len: UnsafeCell, + name: UnsafeCell<[u8; MODULE_NAME_MAX]>, +} +// SAFETY: the fields are written once before `ready` is set (release) and read only after it is seen (acquire). +unsafe impl Sync for ModuleEntry {} + +impl ModuleEntry { + const fn empty() -> ModuleEntry { + ModuleEntry { + ready: AtomicBool::new(false), + base: UnsafeCell::new(0), + size: UnsafeCell::new(0), + len: UnsafeCell::new(0), + name: UnsafeCell::new([0; MODULE_NAME_MAX]), + } + } +} + +static MODULES: [ModuleEntry; MAX_MODULES] = [const { ModuleEntry::empty() }; MAX_MODULES]; +static NEXT_MODULE: AtomicUsize = AtomicUsize::new(0); + +/// Registers a title module (`"game"` for the main image, the lower-case DLL name for the title's DLLs) so that +/// callers and thread starts inside it are written as `name+0x`. Lock-free; at most 64 modules. +pub fn add_module(name: &str, base: usize, size: usize) { + // Nothing with the trace off: no slot, no allocation. + if COMMON.load(Ordering::Acquire) == 0 { + return; + } + let i = NEXT_MODULE.fetch_add(1, Ordering::Relaxed); + if i >= MAX_MODULES { + return; + } + let lower = name.to_ascii_lowercase(); + let bytes = lower.as_bytes(); + let n = bytes.len().min(MODULE_NAME_MAX); + let e = &MODULES[i]; + // SAFETY: slot `i` was handed out to this call alone and is not readable before `ready` is set. + unsafe { + *e.base.get() = base; + *e.size.get() = size; + *e.len.get() = n as u8; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), e.name.get().cast::(), n); + } + e.ready.store(true, Ordering::Release); +} + +/// The module holding `addr`, and the offset in it. +fn find_module(addr: usize) -> Option<(&'static [u8], usize)> { + let count = NEXT_MODULE.load(Ordering::Relaxed).min(MAX_MODULES); + for e in &MODULES[..count] { + if !e.ready.load(Ordering::Acquire) { + continue; + } + // SAFETY: published by `add_module` before `ready` (acquire above); never written again. + let (base, size, len, name) = + unsafe { (*e.base.get(), *e.size.get(), *e.len.get(), &*e.name.get()) }; + if addr >= base && addr - base < size { + return Some((&name[..len as usize], addr - base)); + } + } + None +} + +// --------------------------------------------------------------------------------------------------------- +// Formatting into a stack buffer + +const LINE_MAX: usize = 320; + +struct Buf { + b: [u8; LINE_MAX], + n: usize, +} + +impl Buf { + const fn new() -> Self { + Buf { + b: [0; LINE_MAX], + n: 0, + } + } + fn bytes(&self) -> &[u8] { + &self.b[..self.n] + } + fn s(&mut self, s: &[u8]) { + let n = s.len().min(LINE_MAX - self.n); + self.b[self.n..self.n + n].copy_from_slice(&s[..n]); + self.n += n; + } + fn c(&mut self, c: u8) { + self.s(&[c]); + } + fn dec(&mut self, mut v: u64) { + let mut t = [0u8; 20]; + let mut i = t.len(); + loop { + i -= 1; + t[i] = b'0' + (v % 10) as u8; + v /= 10; + if v == 0 { + break; + } + } + self.s(&t[i..]); + } + /// Lower-case hex, no leading zeros (`0x0` for zero), prefixed `0x`. + fn hex(&mut self, v: u64) { + self.s(b"0x"); + let digits = (16 - v.leading_zeros() as usize / 4).max(1); + for k in (0..digits).rev() { + self.c(b"0123456789abcdef"[((v >> (k * 4)) & 0xf) as usize]); + } + } + /// `0x` and exactly 8 lower-case hex digits. + fn hex8(&mut self, v: u32) { + self.s(b"0x"); + for k in (0..8).rev() { + self.c(b"0123456789abcdef"[((v >> (k * 4)) & 0xf) as usize]); + } + } + fn hex16(&mut self, v: u64) { + for k in (0..16).rev() { + self.c(b"0123456789abcdef"[((v >> (k * 4)) & 0xf) as usize]); + } + } + /// `+0x` of a title module, else `?`. + fn address(&mut self, addr: usize) { + match find_module(addr) { + Some((name, off)) => { + self.s(name); + self.c(b'+'); + self.hex(off as u64); + } + None => self.c(b'?'), + } + } +} + +// --------------------------------------------------------------------------------------------------------- +// The writer + +const VIEW: u64 = 4 << 20; +/// Room kept below the cap for the `# truncated` line. +const RESERVE: u64 = 64; + +struct Writer { + file: HANDLE, + view: *mut u8, + view_index: u64, + pos: usize, + total: u64, + cap: u64, + seq: u64, + title_bound: Vec, + /// The drop count the last `# dropped` line said. + dropped_written: u64, +} +// SAFETY: the raw view pointer and the file handle are used under the mutex only. +unsafe impl Send for Writer {} + +impl Writer { + fn create(path: &Path, cap: u64, delete_on_close: bool) -> Result { + use std::os::windows::ffi::OsStrExt; + let wide: Vec = path.as_os_str().encode_wide().chain([0]).collect(); + let (access, flags) = if delete_on_close { + ( + GENERIC_READ | GENERIC_WRITE | DELETE, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, + ) + } else { + (GENERIC_READ | GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL) + }; + // SAFETY: NUL-terminated path; no other pointers. + let file = unsafe { + CreateFileW( + wide.as_ptr(), + access, + FILE_SHARE_READ, + std::ptr::null(), + CREATE_NEW, + flags, + std::ptr::null_mut(), + ) + }; + if file == INVALID_HANDLE_VALUE { + bail!( + "cannot create {} (it must not exist yet): {}", + path.display(), + std::io::Error::last_os_error() + ); + } + let mut w = Writer { + file, + view: std::ptr::null_mut(), + view_index: 0, + pos: 0, + total: 0, + cap, + seq: 0, + title_bound: Vec::new(), + dropped_written: 0, + }; + w.view = w.map(0)?; + Ok(w) + } + + /// Maps view `index` (extending the file to its end). + fn map(&self, index: u64) -> Result<*mut u8> { + let end = (index + 1) * VIEW; + let offset = index * VIEW; + // SAFETY: a mapping of our own file handle; the handle is closed once the view holds it. + unsafe { + let mapping = CreateFileMappingW( + self.file, + std::ptr::null(), + PAGE_READWRITE, + (end >> 32) as u32, + end as u32, + std::ptr::null(), + ); + if mapping.is_null() { + bail!("CreateFileMapping: {}", std::io::Error::last_os_error()); + } + let view = MapViewOfFile( + mapping, + FILE_MAP_WRITE, + (offset >> 32) as u32, + offset as u32, + VIEW as usize, + ); + CloseHandle(mapping); + if view.Value.is_null() { + bail!("MapViewOfFile: {}", std::io::Error::last_os_error()); + } + Ok(view.Value as *mut u8) + } + } + + /// Copies into the views, moving on to the next one at a boundary. + fn copy(&mut self, mut bytes: &[u8]) -> bool { + while !bytes.is_empty() { + if self.pos as u64 == VIEW { + let Ok(next) = self.map(self.view_index + 1) else { + return false; + }; + // SAFETY: the previous view is fully written and not used again. + unsafe { + UnmapViewOfFile( + windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { + Value: self.view as *mut c_void, + }, + ) + }; + self.view = next; + self.view_index += 1; + self.pos = 0; + } + let n = bytes.len().min(VIEW as usize - self.pos); + // SAFETY: `pos + n <= VIEW`, the size of the mapped view. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), self.view.add(self.pos), n) }; + self.pos += n; + self.total += n as u64; + bytes = &bytes[n..]; + } + true + } + + /// Appends one line unless the cap is near; at the cap writes `# truncated` and says to stop. + fn line(&mut self, bytes: &[u8]) -> bool { + if self.total + bytes.len() as u64 + RESERVE > self.cap { + self.copy(b"# truncated\n"); + ACTIVE.store(false, Ordering::Release); + return false; + } + if !self.copy(bytes) { + ACTIVE.store(false, Ordering::Release); + return false; + } + true + } +} + +impl Writer { + /// Says how many records were dropped for want of the lock, if that changed since the last time. + fn note_drops(&mut self) { + let dropped = DROPPED.load(Ordering::Relaxed); + if dropped == self.dropped_written { + return; + } + let mut b = Buf::new(); + b.s(b"# dropped "); + b.dec(dropped); + b.c(b'\n'); + if self.line(b.bytes()) { + self.dropped_written = dropped; + } + } +} + +/// Records given up on because the writer lock was not free within [`LOCK_WAIT_MS`] (a thread suspended inside a +/// record function by the title, for instance). +static DROPPED: AtomicU64 = AtomicU64::new(0); +/// How long a record waits for the lock, in milliseconds (a static only so that the tests, whose threads share one +/// busy trace on a loaded machine, can lengthen it). +static LOCK_WAIT_MS: AtomicU64 = AtomicU64::new(10); + +/// The writer, waiting at most [`LOCK_WAIT_MS`] for it: a title may suspend a thread that holds the lock, and +/// suspending (SuspendThread, GetThreadContext) goes through wrapped imports itself. `None` counts a drop. +fn lock_bounded() -> Option>> { + let mut since: Option = None; + loop { + match WRITER.try_lock() { + Ok(guard) => return Some(guard), + Err(TryLockError::Poisoned(e)) => return Some(e.into_inner()), + Err(TryLockError::WouldBlock) => {} + } + let wait = Duration::from_millis(LOCK_WAIT_MS.load(Ordering::Relaxed)); + if since.get_or_insert_with(Instant::now).elapsed() >= wait { + DROPPED.fetch_add(1, Ordering::Relaxed); + return None; + } + std::thread::yield_now(); + } +} + +/// Whether records are still being written (false at the cap or on a write failure). +static ACTIVE: AtomicBool = AtomicBool::new(false); +static WRITER: Mutex> = Mutex::new(None); + +/// Whether a trace is open and recording. +pub fn enabled() -> bool { + ACTIVE.load(Ordering::Acquire) +} + +/// Opens the trace named by `LEONIDA_CALL_TRACE` (`Ok(false)`: switch unset). The file must not exist; an +/// existing file, or one that cannot be created, is an error and the caller must not start the title. +/// `LEONIDA_CALL_TRACE_MAX_MB` sets the size cap (default 4096). +pub fn open_from_env() -> Result { + let Some(path) = std::env::var_os(ENV_PATH).filter(|p| !p.is_empty()) else { + return Ok(false); + }; + let mb = std::env::var(ENV_MAX_MB) + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|&mb| mb > 0) + .unwrap_or(DEFAULT_MAX_MB); + // A value too large for a byte count is clamped: no cap in effect. + open(Path::new(&path), mb.saturating_mul(1 << 20), false)?; + Ok(true) +} + +/// Creates the trace file at `path` (which must not exist), writes its header and starts recording. +pub fn open(path: &Path, cap_bytes: u64, delete_on_close: bool) -> Result<()> { + let mut guard = WRITER.lock().unwrap_or_else(|e| e.into_inner()); + if guard.is_some() { + bail!("the call trace is already open"); + } + // Parsed before the file exists: a broken rules file must not leave a trace behind. + let hash = match rules_result() { + Ok(r) => r.hash, + Err(e) => bail!("the call trace rules (tools/call_trace_rules.def) are unusable: {e}"), + }; + let common = install_common()?; + let mut w = Writer::create(path, cap_bytes, delete_on_close)?; + let mut b = Buf::new(); + b.s(b"# leonida-call-trace 1 stack=leonida-hle rules="); + b.hex16(hash); + b.c(b'\n'); + if !w.copy(b.bytes()) { + bail!("cannot write the call trace header"); + } + COMMON.store(common, Ordering::Release); + *guard = Some(w); + ACTIVE.store(true, Ordering::Release); + Ok(()) +} + +/// Notes that imports of `dll` go to a title module (untraced): one `# title-bound ` line per DLL. +pub fn note_title_bound(dll: &str) { + if !enabled() { + return; + } + let lower = dll.to_ascii_lowercase(); + let Some(mut guard) = lock_bounded() else { + return; + }; + let Some(w) = guard.as_mut() else { return }; + if !enabled() || w.title_bound.contains(&lower) { + return; + } + let mut b = Buf::new(); + b.s(b"# title-bound "); + b.s(&lower.as_bytes()[..lower.len().min(120)]); + b.c(b'\n'); + w.line(b.bytes()); + w.title_bound.push(lower); +} + +// --------------------------------------------------------------------------------------------------------- +// Threads + +thread_local! { + // Plain data on purpose: a destructor would register a thread-exit callback with the shared C runtime. + static RECORDED: Cell = const { Cell::new(false) }; + static MAIN: Cell = const { Cell::new(false) }; +} + +/// Marks the calling thread as the title's main thread: its `T` line says `start=main`. First thing the thread does. +pub fn mark_main_thread() { + MAIN.with(|m| m.set(true)); +} + +/// `start` of the calling thread: `main`, or the module and offset of its Win32 start address, or `?`. +fn thread_start(b: &mut Buf) { + if MAIN.with(Cell::get) { + b.s(b"main"); + return; + } + let mut start: usize = 0; + // SAFETY: class 9 (ThreadQuerySetWin32StartAddress) writes one pointer-sized value. + let status = unsafe { + NtQueryInformationThread( + GetCurrentThread(), + 9, + &mut start as *mut usize as *mut c_void, + std::mem::size_of::() as u32, + std::ptr::null_mut(), + ) + }; + if status == 0 && start != 0 { + b.address(start); + } else { + b.c(b'?'); + } +} + +fn thread_created() -> u64 { + let zero = FILETIME { + dwLowDateTime: 0, + dwHighDateTime: 0, + }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: the current thread's pseudo-handle and four valid out-pointers. + unsafe { + GetThreadTimes( + GetCurrentThread(), + &mut created, + &mut exited, + &mut kernel, + &mut user, + ) + }; + (u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime) +} + +// --------------------------------------------------------------------------------------------------------- +// Records + +fn record_call(site: &Site, ret: usize) -> u64 { + if !enabled() { + return 0; + } + let tid = u64::from(unsafe { GetCurrentThreadId() }); + let mut caller = Buf::new(); + caller.address(ret); + // The thread's first traced call writes its `T` line first (start and creation time found outside the lock). + // The flag is set once the line is written: a record dropped for want of the lock leaves it for the next try. + let first = if RECORDED.with(Cell::get) { + None + } else { + let mut start = Buf::new(); + thread_start(&mut start); + Some((start, thread_created())) + }; + let Some(mut guard) = lock_bounded() else { + return 0; + }; + let Some(w) = guard.as_mut() else { return 0 }; + if !enabled() { + return 0; + } + w.note_drops(); + if let Some((start, created)) = first { + let mut b = Buf::new(); + b.dec(w.seq + 1); + b.c(b'\t'); + b.dec(tid); + b.s(b"\tT\t"); + b.s(start.bytes()); + b.c(b'\t'); + b.dec(created); + b.c(b'\n'); + if !w.line(b.bytes()) { + return 0; + } + w.seq += 1; + RECORDED.with(|r| r.set(true)); + } + let seq = w.seq + 1; + let mut b = Buf::new(); + b.dec(seq); + b.c(b'\t'); + b.dec(tid); + b.s(if site.wrap { b"\tC\t" } else { b"\tE\t" }); + b.s(site.name.as_bytes()); + b.c(b'\t'); + b.s(caller.bytes()); + b.c(b'\t'); + b.s(site.bind.text().as_bytes()); + b.c(b'\n'); + if !w.line(b.bytes()) { + return 0; + } + w.seq = seq; + seq +} + +fn record_return(site: &Site, call_seq: u64, rax: u64) { + let tid = u64::from(unsafe { GetCurrentThreadId() }); + let mut ret = Buf::new(); + match site.class { + Class::Void => ret.c(b'-'), + Class::Bool => ret.s(if rax & 0xff == 0 { b"b:0" } else { b"b:1" }), + Class::U32 => { + ret.s(b"u:"); + ret.hex8(rax as u32); + } + Class::Hr => { + ret.s(b"hr:"); + ret.hex8(rax as u32); + } + Class::Ptr => { + if rax == 0 { + ret.s(b"p:0"); + } else if rax == u64::MAX || rax == 0xFFFF_FFFF { + ret.s(b"p:-1"); + } else { + ret.s(b"p:1"); + } + } + } + let Some(mut guard) = lock_bounded() else { + return; + }; + let Some(w) = guard.as_mut() else { return }; + if !enabled() { + return; + } + w.note_drops(); + let seq = w.seq + 1; + let mut b = Buf::new(); + b.dec(seq); + b.c(b'\t'); + b.dec(tid); + b.s(b"\tR\t"); + b.dec(call_seq); + b.c(b'\t'); + b.s(ret.bytes()); + b.c(b'\n'); + if w.line(b.bytes()) { + w.seq = seq; + } +} + +/// Called by the stubs with the site in `r10` and the title's return address. Keeps the last error. The return +/// value (the sequence number, 0 for not recorded) is what the wrap stub hands to [`leave`]. +extern "system" fn enter(site: &Site, ret: usize) -> u64 { + // SAFETY: plain Win32 calls without preconditions. + let error = unsafe { GetLastError() }; + let seq = record_call(site, ret); + // SAFETY: as above. + unsafe { SetLastError(error) }; + seq +} + +/// Called by the wrap stub after the target returned. +extern "system" fn leave(site: &Site, seq: u64, rax: u64) { + if seq == 0 { + return; + } + // SAFETY: plain Win32 calls without preconditions. + let error = unsafe { GetLastError() }; + record_return(site, seq, rax); + // SAFETY: as above. + unsafe { SetLastError(error) }; +} + +// --------------------------------------------------------------------------------------------------------- +// wrap + +/// Whether `address` is on a committed executable page (not a data import). +fn is_code(address: usize) -> bool { + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a query of our own address space into a valid struct. + let got = unsafe { + VirtualQuery( + address as *const c_void, + &mut info, + std::mem::size_of::(), + ) + }; + got != 0 + && info.State == MEM_COMMIT + && info.Protect + & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY) + != 0 +} + +/// The address to put in the import table for `module!function` bound to `target`: `target` itself with the trace +/// off, for skipped imports and for data imports; otherwise a thunk that records the call. `module` is the +/// import descriptor's DLL name; `function` the import name or `#ordinal`. Imports bound to an `Unimpl` stub are +/// traced at entry only. Call [`seal`] before the returned addresses can be called. +pub fn wrap(target: usize, module: &str, function: &str, bind: Bind) -> usize { + // Installed, not merely recording: after the size cap a thunk is still made (and sealed) so that a bind in + // progress gets addresses it can call; the record functions check `enabled`. + let common = COMMON.load(Ordering::Acquire); + if common == 0 { + return target; + } + let module = module.to_ascii_lowercase(); + let (wrap, class) = if bind == Bind::Unimpl { + // The stub is code, though its block is not sealed yet. + (false, Class::Ptr) + } else { + match classify(&module, function) { + Decision::Skip => return target, + Decision::Entry => (false, Class::Ptr), + Decision::Wrap(class) => (true, class), + } + }; + if bind != Bind::Unimpl && !is_code(target) { + return target; + } + let mut name = format!("{module}!{function}"); + if name.len() > NAME_MAX { + let mut end = NAME_MAX; + while !name.is_char_boundary(end) { + end -= 1; + } + name.truncate(end); + } + let site: &'static Site = Box::leak(Box::new(Site { + target, + wrap, + class, + bind, + name: name.into_boxed_str(), + })); + let stub = if wrap { common + WRAP_AT } else { common }; + emit_thunk(site, stub).unwrap_or(target) +} + +#[cfg(test)] +mod tests; diff --git a/d3d12/crates/leonida-loader/src/call_trace/tests.rs b/d3d12/crates/leonida-loader/src/call_trace/tests.rs new file mode 100644 index 0000000000..bfa05b80fc --- /dev/null +++ b/d3d12/crates/leonida-loader/src/call_trace/tests.rs @@ -0,0 +1,1474 @@ +//! Tests of the import call trace. No game data: every target is a function written here. +//! +//! One process-wide trace in a temporary file serves most tests (each filters the lines by the names of its own +//! sites); the cases that need a process of their own (switch unset, existing file, a killed process, the size cap) +//! run a child of this test binary, as `thunks.rs` does for its trap. + +use std::arch::global_asm; +use std::collections::HashMap; +use std::path::PathBuf; +use std::process::Command; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Once, OnceLock}; + +use super::*; +use windows_sys::Win32::System::Diagnostics::Debug::{ + RtlCaptureStackBackTrace, RtlLookupFunctionEntry, +}; +use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; +use windows_sys::Win32::System::Threading::TerminateProcess; + +/// FNV-1a 64 of `tools/call_trace_rules.def` (205 rules): the C++ side must compute the same. +const RULES_HASH: u64 = 0x873c_d3bb_78a7_0bc5; +const RULES_COUNT: usize = 205; + +// --------------------------------------------------------------------------------------------------------- +// The blob against its assembler source (the `global_asm!` block of the harness that tested the bytes) + +global_asm!( + r#" +.section .rdata,"dr" +.globl ct_blob +.globl ct_blob_end +ct_blob: + sub rsp, 0x98 + mov [rsp+0x20], rcx + mov [rsp+0x28], rdx + mov [rsp+0x30], r8 + mov [rsp+0x38], r9 + movaps [rsp+0x40], xmm0 + movaps [rsp+0x50], xmm1 + movaps [rsp+0x60], xmm2 + movaps [rsp+0x70], xmm3 + mov [rsp+0x80], r10 + mov rcx, r10 + mov rdx, [rsp+0x98] + call qword ptr [rip + ct_ptr_enter] + mov r10, [rsp+0x80] + mov rcx, [rsp+0x20] + mov rdx, [rsp+0x28] + mov r8, [rsp+0x30] + mov r9, [rsp+0x38] + movaps xmm0, [rsp+0x40] + movaps xmm1, [rsp+0x50] + movaps xmm2, [rsp+0x60] + movaps xmm3, [rsp+0x70] + add rsp, 0x98 + jmp qword ptr [r10] +ct_entry_end: + .balign 16, 0xCC +ct_wrap: + sub rsp, 0x138 + mov [rsp+0xA0], rcx + mov [rsp+0xA8], rdx + mov [rsp+0xB0], r8 + mov [rsp+0xB8], r9 + movaps [rsp+0xC0], xmm0 + movaps [rsp+0xD0], xmm1 + movaps [rsp+0xE0], xmm2 + movaps [rsp+0xF0], xmm3 + mov [rsp+0x100], r10 + mov rcx, r10 + mov rdx, [rsp+0x138] + call qword ptr [rip + ct_ptr_enter] + mov [rsp+0x108], rax + xor eax, eax +2: + mov r11, [rsp+rax*8+0x160] + mov [rsp+rax*8+0x20], r11 + inc eax + cmp eax, 16 + jb 2b + mov r10, [rsp+0x100] + mov rcx, [rsp+0xA0] + mov rdx, [rsp+0xA8] + mov r8, [rsp+0xB0] + mov r9, [rsp+0xB8] + movaps xmm0, [rsp+0xC0] + movaps xmm1, [rsp+0xD0] + movaps xmm2, [rsp+0xE0] + movaps xmm3, [rsp+0xF0] + call qword ptr [r10] +ct_wrap_ret: + mov [rsp+0x110], rax + movaps [rsp+0x120], xmm0 + mov rcx, [rsp+0x100] + mov rdx, [rsp+0x108] + mov r8, rax + call qword ptr [rip + ct_ptr_leave] + mov rax, [rsp+0x110] + movaps xmm0, [rsp+0x120] + add rsp, 0x138 + ret +ct_wrap_end: + .balign 8, 0xCC +ct_ptr_enter: .quad 0 +ct_ptr_leave: .quad 0 +ct_unwind_entry: .byte 1, 7, 2, 0, 7, 1, 0x13, 0 +ct_unwind_wrap: .byte 1, 7, 2, 0, 7, 1, 0x27, 0 +ct_rf: + .long 0, ct_entry_end - ct_blob, ct_unwind_entry - ct_blob + .long ct_wrap - ct_blob, ct_wrap_end - ct_blob, ct_unwind_wrap - ct_blob +ct_blob_end: +.text +"# +); + +unsafe extern "C" { + static ct_blob: u8; + static ct_blob_end: u8; +} + +#[test] +fn the_blob_is_its_assembler_source() { + // SAFETY: the two symbols delimit the read-only data the block above assembled. + let assembled = unsafe { + let start = &ct_blob as *const u8; + std::slice::from_raw_parts( + start, + (&ct_blob_end as *const u8).offset_from(start) as usize, + ) + }; + assert_eq!(assembled.len(), BLOB.len()); + // The one byte that differs: the entry function's EndAddress (0x1c4), 0x7F in the blob, 0x82 assembled. + let mut expected = assembled.to_vec(); + assert_eq!(expected[RUNTIME_FUNCTIONS_AT + 4], 0x82); + expected[RUNTIME_FUNCTIONS_AT + 4] = 0x7F; + assert_eq!(expected, &BLOB[..]); + assert_eq!(BLOB.len(), 0x1d8); +} + +#[test] +fn the_blob_has_the_documented_offsets() { + // The jump to the target ends the entry stub, the call to it is the wrap stub's, whose return address is 0x159. + assert_eq!(&BLOB[0x7f..0x82], &[0x41, 0xFF, 0x22]); + assert_eq!(&BLOB[0x156..0x159], &[0x41, 0xFF, 0x12]); + // The two pointer slots are empty in the blob and the function table (relative to the blob) is filled. + assert!(BLOB[ENTER_AT..LEAVE_AT + 8].iter().all(|&b| b == 0)); + let table: Vec = BLOB[RUNTIME_FUNCTIONS_AT..] + .chunks(4) + .map(|c| u32::from_le_bytes(c.try_into().unwrap())) + .collect(); + assert_eq!(table, [0, 0x7f, 0x1b0, 0x90, 0x19a, 0x1b8]); + assert_eq!(WRAP_AT, 0x90); + // The stubs read the site's target at offset 0. + assert_eq!(std::mem::offset_of!(Site, target), 0); +} + +// --------------------------------------------------------------------------------------------------------- +// Rules + +#[test] +fn the_rules_hash_is_the_agreed_constant() { + let rules = parse_rules(RULES).unwrap(); + assert_eq!(rules.len(), RULES_COUNT); + assert_eq!( + hash_rules(&rules), + RULES_HASH, + "got {:016x}", + hash_rules(&rules) + ); + assert_eq!(rules_hash(), RULES_HASH); + // Macro name, NUL, each argument and a NUL (computed outside this crate for the sample). + let sample = parse_rules("// c\n\nCT_SKIP(\"a\")\n CT_HR_MOD( \"m\" , \"p\" )\n").unwrap(); + assert_eq!(sample.len(), 2); + assert_eq!(hash_rules(&sample), 0xa0d0_2896_c340_0acb); +} + +#[test] +fn malformed_rules_are_refused() { + for bad in [ + "CT_SKIP(a)", + "CT_SKIP(\"a\"", + "skip(\"a\")", + "CT_SKIP \"a\"", + "CT_SKIP(\"a\" \"b\")", + "CT_SKIP(\"a\\n\")", + "CT_HR_MOD(\"a\",)", + "CT_()", + // Argument counts are checked per macro, and a macro of another build is refused at open. + "CT_HR_MOD(\"a\")", + "CT_SKIP(\"a\", \"b\")", + "CT_SKIP()", + "CT_UNKNOWN(\"a\")", + ] { + assert!(parse_rules(bad).is_err(), "{bad}"); + } +} + +#[test] +fn the_ten_probes_classify_as_on_the_other_stack() { + use Class::*; + use Decision::*; + // The other stack's test asserts the same table. + let probes: [(&str, &str, Decision); 10] = [ + ("kernel32.dll", "EnterCriticalSection", Skip), + ("api-ms-win-crt-string-l1-1-0.dll", "strcpy", Skip), + ("ucrtbase.dll", "_setjmp", Entry), + ("ucrtbase.dll", "snprintf", Entry), + ("kernel32.dll", "ExitProcess", Entry), + ("kernel32.dll", "WaitForSingleObject", Wrap(Void)), + ("xgameruntime.dll", "XTaskQueueDispatch", Wrap(Bool)), + ("xgameruntime.dll", "XUserAddAsync", Wrap(Hr)), + ("xgameruntime.dll", "XUserCompare", Wrap(Ptr)), + ("d3d12.dll", "D3D12CreateDevice", Wrap(Hr)), + ]; + for (module, function, want) in probes { + assert_eq!(classify(module, function), want, "{module}!{function}"); + } + // Precedence: skip, then entry, then the class; an ordinal has no name to match. + assert_eq!(classify("kernel32.dll", "CreateFileW"), Wrap(Ptr)); + assert_eq!(classify("kernel32.dll", "#12"), Wrap(Ptr)); + assert_eq!( + classify("D3D12.dll", "D3D12CreateDevice"), + Wrap(Ptr), + "modules are matched lower-case" + ); +} + +// --------------------------------------------------------------------------------------------------------- +// The trace file + +#[derive(Debug, Clone)] +struct Rec { + seq: u64, + tid: u64, + kind: char, + /// The fields after the kind. + f: Vec, +} + +fn is_dec(s: &str) -> bool { + !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) +} + +fn is_hex_after(s: &str, prefix: &str, digits: Option) -> bool { + s.strip_prefix(prefix).is_some_and(|h| { + !h.is_empty() + && digits.is_none_or(|n| h.len() == n) + && h.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + }) +} + +/// `main`, `?`, or `+0x`. +fn is_address(s: &str, allow_main: bool) -> bool { + if s == "?" || (allow_main && s == "main") { + return true; + } + s.split_once('+').is_some_and(|(name, off)| { + !name.is_empty() + && !name.bytes().any(|b| b.is_ascii_uppercase() || b == b'\t') + && is_hex_after(off, "0x", None) + }) +} + +fn is_ret(s: &str) -> bool { + matches!(s, "-" | "b:0" | "b:1" | "p:0" | "p:1" | "p:-1") + || is_hex_after(s, "hr:0x", Some(8)) + || is_hex_after(s, "u:0x", Some(8)) +} + +/// The format of one non-comment line, as a regular expression would say it; `None` if it does not match. +fn parse_line(line: &str) -> Option { + let p: Vec<&str> = line.split('\t').collect(); + if p.len() < 5 || !is_dec(p[0]) || !is_dec(p[1]) || p[2].len() != 1 { + return None; + } + let ok = match p[2] { + "T" => p.len() == 5 && is_address(p[3], true) && is_dec(p[4]), + "C" | "E" => { + p.len() == 6 + && p[3] + .split_once('!') + .is_some_and(|(m, f)| !m.is_empty() && !f.is_empty()) + && is_address(p[4], false) + && ["shim", "hle", "host", "unimpl"].contains(&p[5]) + } + "R" => p.len() == 5 && is_dec(p[3]) && is_ret(p[4]), + _ => false, + }; + ok.then(|| Rec { + seq: p[0].parse().unwrap(), + tid: p[1].parse().unwrap(), + kind: p[2].chars().next().unwrap(), + f: p[3..].iter().map(|s| s.to_string()).collect(), + }) +} + +fn is_comment(line: &str) -> bool { + let l = line.strip_prefix("# ").unwrap_or("\0"); + l == "truncated" + || l.strip_prefix("title-bound ") + .is_some_and(|d| !d.is_empty() && !d.contains(' ')) + || l.strip_prefix("dropped ").is_some_and(is_dec) + || l.strip_prefix("leonida-call-trace 1 stack=leonida-hle rules=") + .is_some_and(|h| is_hex_after(h, "", Some(16))) + || l.strip_prefix("leonida-call-trace 1 stack=gta6rt rules=") + .is_some() +} + +/// The complete lines of a trace file: cut at the first NUL (the unwritten end; a read of a file that is being +/// written can also show a gap of NULs mid-file when it copies a page before its last line is written and the next +/// page after, and everything before the first NUL is whole), a partial last line dropped. +fn file_lines(path: &std::path::Path) -> Vec { + let mut bytes = std::fs::read(path).unwrap(); + if let Some(end) = bytes.iter().position(|&b| b == 0) { + bytes.truncate(end); + } + if bytes.last().is_some_and(|&b| b != b'\n') { + let cut = bytes.iter().rposition(|&b| b == b'\n').map_or(0, |i| i + 1); + bytes.truncate(cut); + } + String::from_utf8(bytes) + .unwrap() + .lines() + .map(str::to_owned) + .collect() +} + +fn records_of(lines: &[String]) -> Vec { + lines + .iter() + .filter(|l| !l.starts_with('#')) + .map(|l| { + parse_line(l).unwrap_or_else(|| panic!("a line that does not match the format: {l:?}")) + }) + .collect() +} + +/// A call and, if it returned, its return record. +#[derive(Debug)] +struct Call { + c: Rec, + r: Option, +} + +/// The `C` and `E` records whose name starts with `prefix`, with their `R` records joined by call-seq. +fn calls_in(recs: &[Rec], prefix: &str) -> Vec { + let returns: HashMap = recs + .iter() + .filter(|r| r.kind == 'R') + .map(|r| (r.f[0].parse().unwrap(), r)) + .collect(); + recs.iter() + .filter(|r| (r.kind == 'C' || r.kind == 'E') && r.f[0].starts_with(prefix)) + .map(|c| Call { + c: c.clone(), + r: returns.get(&c.seq).map(|r| (*r).clone()), + }) + .collect() +} + +fn exe_range() -> (usize, usize) { + // SAFETY: the base of our own image: its DOS header points at the NT headers, whose SizeOfImage is at +0x50. + unsafe { + let base = GetModuleHandleW(std::ptr::null()) as usize; + let nt = base + (*((base + 0x3c) as *const u32)) as usize; + (base, *((nt + 0x50) as *const u32) as usize) + } +} + +fn trace_path() -> &'static std::path::Path { + static PATH: OnceLock = OnceLock::new(); + PATH.get_or_init(|| { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + std::env::temp_dir().join(format!("leonida_ct_{}_{nanos}.trace", std::process::id())) + }) +} + +/// Opens the process-wide trace (deleted when the process ends) and makes the test binary the title's `game`. +fn init() { + static ONCE: Once = Once::new(); + ONCE.call_once(|| { + // Not the production 10 ms: these tests share one trace and must not lose a record to a slow machine. + LOCK_WAIT_MS.store(10_000, Ordering::Relaxed); + open(trace_path(), 4096 << 20, true).unwrap(); + let (base, size) = exe_range(); + add_module("game", base, size); + }); +} + +/// The process-wide trace as it is now. Not read with the writer's lock held: a record waits only 10 ms for it. +fn global_lines() -> Vec { + file_lines(trace_path()) +} + +/// The highest seq written so far: a test counts only the lines after the one it saw before its run, because +/// Windows reuses thread ids quickly and an earlier thread may have had the same one. +fn max_seq() -> u64 { + records().last().map_or(0, |r| r.seq) +} + +/// The `T` lines of a thread after `since`, found by what identifies it: id and creation time. +fn t_lines(recs: &[Rec], since: u64, tid: u64, created: u64) -> Vec<&Rec> { + recs.iter() + .filter(|r| r.kind == 'T' && r.seq > since && r.tid == tid && r.f[1] == created.to_string()) + .collect() +} + +fn records() -> Vec { + records_of(&global_lines()) +} + +fn thunk(target: usize, module: &str, function: &str) -> usize { + init(); + let at = wrap(target, module, function, Bind::Hle); + seal().unwrap(); + assert_ne!(at, target, "{module}!{function} was not wrapped"); + at +} + +// --------------------------------------------------------------------------------------------------------- +// Targets + +#[inline(never)] +extern "system" fn ints( + a: u64, + b: u64, + c: u64, + d: u64, + e: u64, + f: u64, + g: u64, + h: u64, + i: u64, + j: u64, + k: u64, + l: u64, + m: u64, + n: u64, + o: u64, + p: u64, + q: u64, + r: u64, + s: u64, + t: u64, +) -> u64 { + unsafe { SetLastError(1234) }; + a + 2 * b + + 3 * c + + 4 * d + + 5 * e + + 6 * f + + 7 * g + + 8 * h + + 9 * i + + 10 * j + + 11 * k + + 12 * l + + 13 * m + + 14 * n + + 15 * o + + 16 * p + + 17 * q + + 18 * r + + 19 * s + + 20 * t +} +type Ints = extern "system" fn( + u64, + u64, + u64, + u64, + u64, + u64, + u64, + u64, + u64, + u64, + u64, + u64, + u64, + u64, + u64, + u64, + u64, + u64, + u64, + u64, +) -> u64; + +#[inline(never)] +extern "system" fn floats(a: f64, b: f32, c: f64, d: f64, e: f64, f: f32) -> f64 { + a + b as f64 * 2.0 + c * 3.0 + d * 4.0 + e * 5.0 + f as f64 * 6.0 +} +type Floats = extern "system" fn(f64, f32, f64, f64, f64, f32) -> f64; + +#[repr(C)] +#[derive(Debug, PartialEq)] +struct Big { + a: u64, + b: u64, + c: u64, +} +#[inline(never)] +extern "system" fn big(x: u64, y: u64) -> Big { + Big { + a: x, + b: y, + c: x ^ y, + } +} +type BigFn = extern "system" fn(u64, u64) -> Big; + +#[inline(never)] +extern "system" fn last_error() -> u64 { + u64::from(unsafe { GetLastError() }) +} + +#[inline(never)] +extern "system-unwind" fn thrower(x: u64) -> u64 { + if x == 7 { + panic!("through the stub") + } + x +} + +/// The return address this function is called from, as the unwinder sees it (the entry stub leaves no frame). +#[inline(never)] +extern "system" fn caller_seen() -> usize { + let mut frames = [std::ptr::null_mut::(); 1]; + // SAFETY: one frame into a one-element array. + unsafe { RtlCaptureStackBackTrace(1, 1, frames.as_mut_ptr(), std::ptr::null_mut()) }; + frames[0] as usize +} + +static RETURNS: AtomicU64 = AtomicU64::new(0); +#[inline(never)] +extern "system" fn returns() -> u64 { + RETURNS.load(Ordering::SeqCst) +} + +/// Not `returns`: the class test sets `RETURNS` while this one runs. +#[inline(never)] +extern "system" fn five() -> u64 { + 5 +} + +static INNER: AtomicUsize = AtomicUsize::new(0); +#[inline(never)] +extern "system" fn outer(x: u64) -> u64 { + // SAFETY: the address of a thunk for `returns`. + let inner: extern "system" fn() -> u64 = + unsafe { std::mem::transmute(INNER.load(Ordering::SeqCst)) }; + inner() + x +} + +#[inline(never)] +extern "system" fn bump(x: u64) -> u64 { + x + 1 +} + +fn addr(f: F) -> usize +where + F: Copy, +{ + assert_eq!(std::mem::size_of::(), std::mem::size_of::()); + // SAFETY: a function pointer, same size as usize. + unsafe { std::mem::transmute_copy(&f) } +} + +fn game(address: usize) -> String { + let mut b = Buf::new(); + b.address(address); + String::from_utf8(b.bytes().to_vec()).unwrap() +} + +// --------------------------------------------------------------------------------------------------------- +// The common stub + +/// Both stubs against 20 integer arguments, float arguments and a struct return; the last error both ways. +#[test] +fn arguments_returns_and_last_error_pass_through_both_stubs() { + init(); + // The wrap stub, and the entry stub (a name the rules mark entry-only). + for (module, function, wrapped) in [ + ("ct_args.dll", "plain", true), + ("ct_args.dll", "setjmp", false), + ] { + let name = format!("{module}!{function}"); + let f: Ints = unsafe { std::mem::transmute(thunk(addr(ints as Ints), module, function)) }; + let want = ints( + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + ); + unsafe { SetLastError(0) }; + let got = f( + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + ); + let after = unsafe { GetLastError() }; + assert_eq!(got, want, "{name}"); + assert_eq!( + after, 1234, + "{name}: the target's last error is the caller's" + ); + + let f: Floats = unsafe { + std::mem::transmute(thunk( + addr(floats as Floats), + module, + &format!("{function}_f"), + )) + }; + assert_eq!( + f(1.5, 2.5, 3.5, 4.5, 5.5, 6.5), + floats(1.5, 2.5, 3.5, 4.5, 5.5, 6.5), + "{name}" + ); + + let f: BigFn = unsafe { + std::mem::transmute(thunk( + addr(big as BigFn), + module, + &format!("{function}_big"), + )) + }; + assert_eq!(f(5, 9), Big { a: 5, b: 9, c: 12 }, "{name}"); + + // The caller's last error reaches the target untouched by the record. + let f: extern "system" fn() -> u64 = unsafe { + std::mem::transmute(thunk( + addr(last_error as extern "system" fn() -> u64), + module, + &format!("{function}_e"), + )) + }; + unsafe { SetLastError(4321) }; + assert_eq!(f(), 4321, "{name}"); + + let recs = records(); + let seen = calls_in(&recs, &format!("{module}!{function}")); + let seen: Vec<&Call> = seen.iter().filter(|c| c.c.f[0] == name).collect(); + assert_eq!(seen.len(), 1, "{name}"); + let call = seen[0]; + assert_eq!(call.c.kind, if wrapped { 'C' } else { 'E' }); + assert_eq!( + call.r.is_some(), + wrapped, + "entry-only calls have no R record" + ); + assert!(call.c.f[1].starts_with("game+0x"), "{:?}", call.c.f); + assert_eq!(call.c.f[2], "hle"); + if let Some(r) = &call.r { + assert_eq!(r.f, [call.c.seq.to_string(), "p:1".to_string()]); + assert_eq!(r.tid, call.c.tid); + assert!(r.seq > call.c.seq); + } + } +} + +/// The entry stub leaves no frame: the callee sees the title's return address, and the line names it. +#[test] +fn the_entry_stub_leaves_the_real_return_address() { + init(); + let f: extern "system" fn() -> usize = unsafe { + std::mem::transmute(thunk( + addr(caller_seen as extern "system" fn() -> usize), + "ct_entry.dll", + "ExitThread", + )) + }; + #[inline(never)] + fn call_site(f: extern "system" fn() -> usize) -> usize { + std::hint::black_box(f()) + } + let seen = call_site(f); + let (base, size) = exe_range(); + assert!( + seen > base && seen - base < size, + "{seen:#x} is in the test binary" + ); + let recs = records(); + let calls = calls_in(&recs, "ct_entry.dll!ExitThread"); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0].c.kind, 'E'); + assert_eq!( + calls[0].c.f[1], + game(seen), + "the line's caller is the callee's return address" + ); + // And it is inside `call_site`, which made the call. + let here = call_site as *const () as usize; + assert!(seen > here && seen - here < 0x200, "{seen:#x} vs {here:#x}"); +} + +#[test] +fn a_wrap_line_names_its_caller() { + init(); + let f: extern "system" fn(u64) -> u64 = unsafe { + std::mem::transmute(thunk( + addr(bump as extern "system" fn(u64) -> u64), + "ct_caller.dll", + "bump", + )) + }; + #[inline(never)] + fn call_site(f: extern "system" fn(u64) -> u64) -> u64 { + std::hint::black_box(f(1)) + } + assert_eq!(call_site(f), 2); + let recs = records(); + let calls = calls_in(&recs, "ct_caller.dll!bump"); + assert_eq!(calls.len(), 1); + let caller = &calls[0].c.f[1]; + let rva = usize::from_str_radix(caller.strip_prefix("game+0x").unwrap(), 16).unwrap(); + let (base, _) = exe_range(); + let here = call_site as *const () as usize - base; + assert!(rva > here && rva - here < 0x200, "{caller} vs {here:#x}"); +} + +/// A panic through both stubs: the wrap stub's call has no R record, later calls are recorded normally. +#[test] +fn a_panic_through_the_stubs_leaves_a_call_without_a_return() { + init(); + for (function, wrapped) in [("unwind", true), ("RaiseException", false)] { + let f: extern "system-unwind" fn(u64) -> u64 = unsafe { + std::mem::transmute(thunk( + addr(thrower as extern "system-unwind" fn(u64) -> u64), + "ct_panic.dll", + function, + )) + }; + let result = std::panic::catch_unwind(|| f(7)); + assert!(result.is_err()); + assert_eq!(f(3), 3); + let recs = records(); + let calls = calls_in(&recs, &format!("ct_panic.dll!{function}")); + assert_eq!(calls.len(), 2, "{function}"); + assert!(calls[0].r.is_none(), "the call that unwound has no R"); + assert_eq!( + calls[1].r.is_some(), + wrapped, + "{function}: the next call is recorded as usual" + ); + } +} + +#[test] +fn nested_calls_nest() { + init(); + let inner = thunk( + addr(five as extern "system" fn() -> u64), + "ct_nest.dll", + "inner", + ); + INNER.store(inner, Ordering::SeqCst); + let outer_f: extern "system" fn(u64) -> u64 = unsafe { + std::mem::transmute(thunk( + addr(outer as extern "system" fn(u64) -> u64), + "ct_nest.dll", + "outer", + )) + }; + assert_eq!(outer_f(2), 7); + let recs = records(); + let tid = u64::from(unsafe { GetCurrentThreadId() }); + let mine: Vec<&Rec> = recs + .iter() + .filter(|r| { + r.tid == tid + && r.f + .first() + .is_some_and(|f| f.starts_with("ct_nest.dll!") || r.kind == 'R') + }) + .collect(); + let order: Vec<(char, String)> = mine.iter().map(|r| (r.kind, r.f[0].clone())).collect(); + let outer_seq = mine + .iter() + .find(|r| r.f[0] == "ct_nest.dll!outer") + .unwrap() + .seq; + let inner_seq = mine + .iter() + .find(|r| r.f[0] == "ct_nest.dll!inner") + .unwrap() + .seq; + assert!(inner_seq > outer_seq); + // C outer, C inner, R inner, R outer: the two R records name their own call. + let mut kinds = Vec::new(); + for r in recs.iter().filter(|r| r.tid == tid && r.seq >= outer_seq) { + match r.kind { + 'C' if r.f[0].starts_with("ct_nest.dll!") => kinds.push(format!("C {}", r.f[0])), + 'R' if r.f[0] == inner_seq.to_string() => kinds.push("R inner".to_string()), + 'R' if r.f[0] == outer_seq.to_string() => { + kinds.push("R outer".to_string()); + break; + } + _ => {} + } + } + assert_eq!( + kinds, + [ + "C ct_nest.dll!outer", + "C ct_nest.dll!inner", + "R inner", + "R outer" + ], + "{order:?}" + ); +} + +// --------------------------------------------------------------------------------------------------------- +// What is wrapped + +#[test] +fn skipped_and_data_imports_are_returned_unchanged() { + init(); + let f = addr(bump as extern "system" fn(u64) -> u64); + assert_eq!( + wrap(f, "kernel32.dll", "EnterCriticalSection", Bind::Host), + f, + "CT_SKIP" + ); + assert_eq!( + wrap(f, "kernel32.dll", "my_chkstk_helper", Bind::Host), + f, + "CT_SKIP_HAS" + ); + assert_eq!( + wrap(f, "API-MS-WIN-CRT-STRING-L1-1-0.DLL", "strcpy", Bind::Host), + f, + "CT_SKIP_MODULE" + ); + static DATA: [u64; 4] = [1, 2, 3, 4]; + let data = DATA.as_ptr() as usize; + assert_eq!( + wrap(data, "ct_data.dll", "SomeDataExport", Bind::Host), + data, + "not on an executable page" + ); + assert_eq!(wrap(0, "ct_data.dll", "Null", Bind::Hle), 0); +} + +#[test] +fn return_values_are_classified_and_never_written_raw() { + init(); + let f = addr(returns as extern "system" fn() -> u64); + let want: [(&str, &str, u64, &str); 17] = [ + ("ct_class.dll", "Ptr", 0, "p:0"), + ("ct_class.dll", "Ptr", 0xdead_beef_0000_1000, "p:1"), + ("ct_class.dll", "Ptr", 1, "p:1"), + ("ct_class.dll", "Ptr", u64::MAX, "p:-1"), + ("ct_class.dll", "Ptr", 0xFFFF_FFFF, "p:-1"), + ("ct_class.dll", "Ptr", 0x1_FFFF_FFFF, "p:1"), + ("ct_class.dll", "Ptr", 0xFFFF_FFFF_0000_0000, "p:1"), + ("ct_class.dll", "Ptr", 0x7ff6_1234_5678_9abc, "p:1"), + ( + "xgameruntime.dll", + "XGameRuntimeInitialize", + 0xdead_beef_8007_000e, + "hr:0x8007000e", + ), + ( + "xgameruntime.dll", + "XUserAddAsync", + 0x1_0000_0000, + "hr:0x00000000", + ), + ( + "xgameruntime.dll", + "XTaskQueueDispatch", + 0xdead_beef_ffff_ff00, + "b:0", + ), + ( + "xgameruntime.dll", + "XTaskQueueDispatch", + 0xdead_beef_ffff_ff01, + "b:1", + ), + ("xgameruntime.dll", "XUserIsStoreUser", 0x100, "b:0"), + ("kernel32.dll", "WaitForSingleObject", 0x102, "-"), + ("kernel32.dll", "WaitForMultipleObjects", u64::MAX, "-"), + ("xgameruntime.dll", "XUserCompare", 0x8000_4005, "p:1"), + ( + "d3d12.dll", + "D3D12CreateDevice", + 0x887a_0005, + "hr:0x887a0005", + ), + ]; + for (module, function, value, _) in want { + let at = thunk(f, module, function); + RETURNS.store(value, Ordering::SeqCst); + let g: extern "system" fn() -> u64 = unsafe { std::mem::transmute(at) }; + assert_eq!(g(), value, "the caller gets the raw value"); + } + // One read of the file: this thread's calls, in order, per site name. + let recs = records(); + let tid = u64::from(unsafe { GetCurrentThreadId() }); + let mut seen: HashMap = HashMap::new(); + for (module, function, value, text) in want { + let name = format!("{module}!{function}"); + let nth = seen.entry(name.clone()).or_insert(0); + let call = recs + .iter() + .filter(|r| r.kind == 'C' && r.tid == tid && r.f[0] == name) + .nth(*nth) + .unwrap(); + *nth += 1; + let ret = recs + .iter() + .find(|r| r.kind == 'R' && r.f[0] == call.seq.to_string()) + .unwrap(); + assert_eq!(ret.f[1], text, "{name} returning {value:#x}"); + } + // A u32 class (no rule uses it yet) writes the low 32 bits and nothing of the high half. + let site: &'static Site = Box::leak(Box::new(Site { + target: f, + wrap: true, + class: Class::U32, + bind: Bind::Host, + name: "ct_class.dll!U32".into(), + })); + let at = emit_thunk(site, COMMON.load(Ordering::SeqCst) + WRAP_AT).unwrap(); + seal().unwrap(); + RETURNS.store(0xabcd_ef01_2345_6789, Ordering::SeqCst); + let g: extern "system" fn() -> u64 = unsafe { std::mem::transmute(at) }; + g(); + let recs = records(); + let calls = calls_in(&recs, "ct_class.dll!U32"); + assert_eq!(calls[0].r.as_ref().unwrap().f[1], "u:0x23456789"); +} + +#[test] +fn an_unimplemented_import_is_traced_at_entry_with_bind_unimpl() { + init(); + // A stub in an unsealed block is code all the same. + let target = addr(bump as extern "system" fn(u64) -> u64); + let at = wrap(target, "ct_unimpl.dll", "Missing", Bind::Unimpl); + seal().unwrap(); + assert_ne!(at, target); + // SAFETY: a thunk to the entry stub, which jumps on to `bump`. + let g: extern "system" fn(u64) -> u64 = unsafe { std::mem::transmute(at) }; + assert_eq!(g(4), 5); + let recs = records(); + let calls = calls_in(&recs, "ct_unimpl.dll!Missing"); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0].c.kind, 'E'); + assert_eq!(calls[0].c.f[2], "unimpl"); + assert!(calls[0].r.is_none()); +} + +// --------------------------------------------------------------------------------------------------------- +// The file + +#[test] +fn the_header_and_title_bound_lines() { + init(); + note_title_bound("CT_Title.DLL"); + note_title_bound("ct_title.dll"); + let lines = global_lines(); + assert_eq!( + lines[0], + format!("# leonida-call-trace 1 stack=leonida-hle rules={RULES_HASH:016x}") + ); + assert_eq!( + lines + .iter() + .filter(|l| *l == "# title-bound ct_title.dll") + .count(), + 1 + ); + assert!( + lines + .iter() + .filter(|l| l.starts_with('#')) + .all(|l| is_comment(l)) + ); +} + +#[test] +fn the_main_thread_and_other_threads_have_a_t_line() { + init(); + let f = thunk( + addr(bump as extern "system" fn(u64) -> u64), + "ct_thread.dll", + "bump", + ); + let run = move |main: bool| { + std::thread::spawn(move || { + if main { + mark_main_thread(); + } + // SAFETY: a thunk of `bump`. + let g: extern "system" fn(u64) -> u64 = unsafe { std::mem::transmute(f) }; + g(1); + g(2); + (u64::from(unsafe { GetCurrentThreadId() }), thread_created()) + }) + .join() + .unwrap() + }; + // One run after the other: the second thread may well have the first one's id. + let before_main = max_seq(); + let main_thread = run(true); + let before_other = max_seq(); + let other_thread = run(false); + let recs = records(); + for ((tid, created), since, start) in [ + (main_thread, before_main, Some("main")), + (other_thread, before_other, None), + ] { + let ts = t_lines(&recs, since, tid, created); + assert_eq!(ts.len(), 1, "one T line for the thread"); + match start { + Some(s) => assert_eq!(ts[0].f[0], s), + // A Rust thread starts in the test binary's image, which is `game` here. + None => assert!(is_address(&ts[0].f[0], false)), + } + let first = recs + .iter() + .find(|r| { + r.seq > since + && r.tid == tid + && r.f.first().is_some_and(|f| f.starts_with("ct_thread.dll")) + }) + .unwrap(); + assert!( + ts[0].seq < first.seq, + "T comes before the thread's first call" + ); + } +} + +/// Four threads cross a view boundary: seq strictly increasing in file order, one T per thread, all lines valid. +#[test] +fn four_threads_across_a_view_boundary() { + init(); + let f = thunk( + addr(bump as extern "system" fn(u64) -> u64), + "ct_mt.dll", + "bump", + ); + const CALLS: u64 = 16_000; + let before = max_seq(); + let threads: Vec<(u64, u64)> = (0..4) + .map(|_| { + std::thread::spawn(move || { + // SAFETY: a thunk of `bump`. + let g: extern "system" fn(u64) -> u64 = unsafe { std::mem::transmute(f) }; + for i in 0..CALLS { + assert_eq!(g(i), i + 1); + } + (u64::from(unsafe { GetCurrentThreadId() }), thread_created()) + }) + }) + .collect::>() + .into_iter() + .map(|h| h.join().unwrap()) + .collect(); + assert!( + WRITER.lock().unwrap().as_ref().unwrap().view_index >= 1, + "the calls above are more than one view of lines" + ); + let lines = global_lines(); + assert!( + lines + .iter() + .filter(|l| l.starts_with('#')) + .all(|l| is_comment(l)) + ); + let recs = records_of(&lines); + assert!( + recs.windows(2).all(|w| w[0].seq < w[1].seq), + "seq strictly increasing in file order" + ); + assert_eq!(recs[0].seq, 1); + for (tid, created) in threads { + assert_eq!(t_lines(&recs, before, tid, created).len(), 1); + } + let calls = calls_in(&recs, "ct_mt.dll!bump"); + assert_eq!(calls.len() as u64, 4 * CALLS); + assert!(calls.iter().all(|c| c.c.seq > before)); + assert!( + calls + .iter() + .all(|c| c.r.as_ref().is_some_and(|r| r.tid == c.c.tid)) + ); +} + +// --------------------------------------------------------------------------------------------------------- +// Children: a process of their own + +fn child( + name: &str, + envs: &[(&str, &std::path::Path)], + max_mb: Option<&str>, +) -> std::process::Output { + let mut cmd = Command::new(std::env::current_exe().unwrap()); + cmd.args([ + "--exact", + &format!("call_trace::tests::child_{name}"), + "--nocapture", + ]) + .env("LEONIDA_CT_CHILD", name) + .env_remove(ENV_PATH) + .env_remove(ENV_MAX_MB); + for (k, v) in envs { + cmd.env(k, v); + } + if let Some(mb) = max_mb { + cmd.env(ENV_MAX_MB, mb); + } + cmd.output().unwrap() +} + +fn in_child(name: &str) -> bool { + std::env::var("LEONIDA_CT_CHILD").is_ok_and(|v| v == name) +} + +fn ran(out: &std::process::Output, name: &str) -> String { + let text = String::from_utf8_lossy(&out.stdout).into_owned(); + assert!( + text.contains(&format!("child_{name}-reached-the-end")), + "child {name}: {text} {}", + String::from_utf8_lossy(&out.stderr) + ); + text +} + +#[test] +fn child_off() { + if !in_child("off") { + return; + } + assert!(!open_from_env().unwrap(), "unset: no trace"); + let f = addr(bump as extern "system" fn(u64) -> u64); + assert_eq!(wrap(f, "kernel32.dll", "CreateFileW", Bind::Hle), f); + assert_eq!(wrap(f, "ct.dll", "Missing", Bind::Unimpl), f); + note_title_bound("ct.dll"); + seal().unwrap(); + assert!(!enabled()); + assert_eq!(thunk_blocks(), 0, "no thunk block with the switch unset"); + assert_eq!(COMMON.load(Ordering::SeqCst), 0, "no stub installed"); + println!("child_off-reached-the-end"); +} + +#[test] +fn child_refuse() { + if !in_child("refuse") { + return; + } + let path = PathBuf::from(std::env::var_os(ENV_PATH).unwrap()); + let error = open_from_env().unwrap_err().to_string(); + assert!(error.contains("cannot create"), "{error}"); + assert!(!error.contains('\n'), "one line"); + assert!(!enabled()); + let f = addr(bump as extern "system" fn(u64) -> u64); + assert_eq!(wrap(f, "kernel32.dll", "CreateFileW", Bind::Hle), f); + assert_eq!(std::fs::read(&path).unwrap(), b"keep me"); + println!("child_refuse-reached-the-end"); +} + +#[test] +fn the_switch_unset_changes_nothing_and_an_existing_file_is_refused() { + let off = child("off", &[], None); + ran(&off, "off"); + assert!(off.status.success()); + + let dir = tempfile::tempdir().unwrap(); + let existing = dir.path().join("existing.trace"); + std::fs::write(&existing, b"keep me").unwrap(); + let refused = child("refuse", &[(ENV_PATH, &existing)], None); + ran(&refused, "refuse"); + assert!(refused.status.success()); + assert_eq!( + std::fs::read(&existing).unwrap(), + b"keep me", + "the existing file is untouched" + ); +} + +#[inline(never)] +extern "system" fn die(_x: u64) -> u64 { + // SAFETY: ends the (child) process. + unsafe { TerminateProcess(GetCurrentProcess(), 77) }; + 0 +} + +#[test] +fn child_kill() { + if !in_child("kill") { + return; + } + assert!(open_from_env().unwrap()); + let (base, size) = exe_range(); + add_module("game", base, size); + let good: extern "system" fn(u64) -> u64 = unsafe { + std::mem::transmute(wrap( + addr(bump as extern "system" fn(u64) -> u64), + "ct_kill.dll", + "good", + Bind::Hle, + )) + }; + let bad: extern "system" fn(u64) -> u64 = unsafe { + std::mem::transmute(wrap( + addr(die as extern "system" fn(u64) -> u64), + "ct_kill.dll", + "die", + Bind::Hle, + )) + }; + seal().unwrap(); + for i in 0..3 { + good(i); + } + bad(1); + unreachable!("the target ended the process"); +} + +/// A process that dies inside a wrapped target leaves every earlier line and the open call. +#[test] +fn a_killed_process_leaves_its_lines_and_the_open_call() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("kill.trace"); + let out = child("kill", &[(ENV_PATH, &path)], None); + assert_eq!( + out.status.code(), + Some(77), + "{}", + String::from_utf8_lossy(&out.stdout) + ); + let lines = file_lines(&path); + assert!(lines[0].starts_with("# leonida-call-trace 1 stack=leonida-hle rules=")); + assert!( + lines + .iter() + .filter(|l| l.starts_with('#')) + .all(|l| is_comment(l)) + ); + let recs = records_of(&lines); + let good = calls_in(&recs, "ct_kill.dll!good"); + assert_eq!(good.len(), 3); + assert!(good.iter().all(|c| c.r.is_some())); + let bad = calls_in(&recs, "ct_kill.dll!die"); + assert_eq!(bad.len(), 1); + assert!( + bad[0].r.is_none(), + "the call that ended the process is open" + ); + assert_eq!(recs.iter().filter(|r| r.kind == 'T').count(), 1); + assert_eq!( + recs.last().unwrap().seq, + bad[0].c.seq, + "nothing after the open call" + ); +} + +/// The cap hits between `wrap` and `seal` (a late bind while title threads run): the thunks must still be sealed +/// and callable, and record nothing. +#[test] +fn child_seal() { + if !in_child("seal") { + return; + } + assert!(open_from_env().unwrap()); + let (base, size) = exe_range(); + add_module("game", base, size); + let bump_fn = addr(bump as extern "system" fn(u64) -> u64); + let call = |at: usize, x: u64| { + // SAFETY: a thunk of `bump`. + let g: extern "system" fn(u64) -> u64 = unsafe { std::mem::transmute(at) }; + g(x) + }; + let driver = wrap(bump_fn, "ct_seal.dll", "driver", Bind::Hle); + seal().unwrap(); + // Made before the cap, not sealed yet. + let early = wrap(bump_fn, "ct_seal.dll", "early", Bind::Hle); + assert_ne!(early, bump_fn); + let mut i = 0; + while enabled() { + assert_eq!(call(driver, i), i + 1); + i += 1; + assert!(i < 200_000, "1 MiB is filled long before"); + } + assert!(!enabled(), "the cap stopped the recording"); + // Made after it. + let late = wrap(bump_fn, "ct_seal.dll", "late", Bind::Hle); + assert_ne!(late, bump_fn, "installed: thunks are still made"); + seal().unwrap(); + assert_eq!(call(early, 10), 11); + assert_eq!(call(late, 20), 21); + let writes = records_of(&file_lines(&PathBuf::from( + std::env::var_os(ENV_PATH).unwrap(), + ))); + assert!(calls_in(&writes, "ct_seal.dll!early").is_empty()); + assert!(calls_in(&writes, "ct_seal.dll!late").is_empty()); + println!("child_seal-reached-the-end"); +} + +#[test] +fn a_cap_between_wrap_and_seal_leaves_callable_thunks() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("seal.trace"); + let out = child("seal", &[(ENV_PATH, &path)], Some("1")); + ran(&out, "seal"); + assert!(out.status.success()); + let lines = file_lines(&path); + assert_eq!(lines.iter().filter(|l| *l == "# truncated").count(), 1); +} + +#[test] +fn an_unusable_rules_text_is_an_error() { + assert!(build_rules("CT_HR_MOD(\"a\")").is_err()); + assert!(build_rules("CT_NOPE(\"a\")").is_err()); + assert!(build_rules(RULES).is_ok()); +} + +/// The unwinder does not take the entry stub's final `jmp [r10]` for an epilogue: the function range ends before +/// it, so a walk of a thread stopped there uses the leaf rule (the return address is at RSP). +#[test] +fn the_entry_stub_s_unwind_range_ends_before_its_jump() { + init(); + let stub = COMMON.load(Ordering::SeqCst); + let lookup = |at: usize| { + let mut image = 0u64; + // SAFETY: a lookup of an address of ours; no history table. + unsafe { RtlLookupFunctionEntry(at as u64, &mut image, std::ptr::null_mut()) } + }; + assert!( + lookup(stub + 0x7F).is_null(), + "the jump is outside the range" + ); + let entry = lookup(stub + 0x7E); + assert!( + !entry.is_null(), + "the instruction before it is the entry function" + ); + // SAFETY: a non-null entry points at the table written by `install_common`. + let (begin, end) = unsafe { ((*entry).BeginAddress, (*entry).EndAddress) }; + assert_eq!((begin, end), (0, 0x7F)); + // The wrap stub is unchanged. + assert!(!lookup(stub + WRAP_AT).is_null()); +} + +/// A thread of the title may be suspended inside a record function with the writer lock held. In a process of its +/// own, the lock is held from the test: the record of another thread is given up within a few milliseconds, and +/// the next record that gets the lock says so. +#[test] +fn child_drop() { + if !in_child("drop") { + return; + } + assert!(open_from_env().unwrap()); + let (base, size) = exe_range(); + add_module("game", base, size); + let f = wrap( + addr(bump as extern "system" fn(u64) -> u64), + "ct_drop.dll", + "bump", + Bind::Hle, + ); + seal().unwrap(); + let call = move |x: u64| { + // SAFETY: a thunk of `bump`. + let g: extern "system" fn(u64) -> u64 = unsafe { std::mem::transmute(f) }; + g(x) + }; + let held = WRITER.lock().unwrap(); + let started = Instant::now(); + let other = std::thread::spawn(move || call(5)).join().unwrap(); + let waited = started.elapsed(); + assert_eq!(other, 6, "the call itself goes on"); + assert!( + waited < Duration::from_millis(500), + "gave up after {waited:?}" + ); + assert!( + waited >= Duration::from_millis(5), + "tried for a while: {waited:?}" + ); + assert_eq!(DROPPED.load(Ordering::SeqCst), 1); + drop(held); + assert_eq!(call(7), 8); + println!("child_drop-reached-the-end"); +} + +#[test] +fn a_held_writer_lock_costs_a_record_not_a_hang() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("drop.trace"); + let out = child("drop", &[(ENV_PATH, &path)], None); + ran(&out, "drop"); + let lines = file_lines(&path); + assert!( + lines + .iter() + .filter(|l| l.starts_with('#')) + .all(|l| is_comment(l)) + ); + let dropped = lines + .iter() + .position(|l| l == "# dropped 1") + .expect("the drop is reported"); + assert_eq!( + lines.iter().filter(|l| l.starts_with("# dropped")).count(), + 1 + ); + let recs = records_of(&lines); + let calls = calls_in(&recs, "ct_drop.dll!bump"); + assert_eq!( + calls.len(), + 1, + "the dropped call has no record, the later one does" + ); + // The report comes before the record that took the lock. + let first_record = lines.iter().position(|l| !l.starts_with('#')).unwrap(); + assert!(dropped < first_record); + assert!(calls[0].r.is_some()); + // That thread had no T line yet (its first record was dropped): the line comes with the next one. + assert_eq!(recs.iter().filter(|r| r.kind == 'T').count(), 1); +} + +#[test] +fn child_cap() { + if !in_child("cap") { + return; + } + assert!(open_from_env().unwrap()); + let (base, size) = exe_range(); + add_module("game", base, size); + let f: extern "system" fn(u64) -> u64 = unsafe { + std::mem::transmute(wrap( + addr(bump as extern "system" fn(u64) -> u64), + "ct_cap.dll", + "bump", + Bind::Hle, + )) + }; + seal().unwrap(); + let mut stopped_at = None; + for i in 0..60_000u64 { + assert_eq!(f(i), i + 1, "calls go on after the cap"); + if stopped_at.is_none() && !enabled() { + stopped_at = Some(i); + } + } + assert!(stopped_at.is_some(), "1 MiB is filled by 60 000 calls"); + println!("child_cap-reached-the-end"); +} + +#[test] +fn the_size_cap_writes_truncated_once_and_stops() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("cap.trace"); + let out = child("cap", &[(ENV_PATH, &path)], Some("1")); + ran(&out, "cap"); + let mut bytes = std::fs::read(&path).unwrap(); + while bytes.last() == Some(&0) { + bytes.pop(); + } + assert!(bytes.len() <= 1 << 20, "{} bytes", bytes.len()); + assert!(bytes.ends_with(b"# truncated\n")); + let lines = file_lines(&path); + assert_eq!(lines.iter().filter(|l| *l == "# truncated").count(), 1); + assert_eq!(lines.last().unwrap(), "# truncated"); + let recs = records_of(&lines); + assert!(recs.len() > 1000 && recs.windows(2).all(|w| w[0].seq < w[1].seq)); +} diff --git a/d3d12/crates/leonida-loader/src/lib.rs b/d3d12/crates/leonida-loader/src/lib.rs index b41ca1945b..c94a37828a 100644 --- a/d3d12/crates/leonida-loader/src/lib.rs +++ b/d3d12/crates/leonida-loader/src/lib.rs @@ -21,6 +21,9 @@ //! point on a thread with the stack size the image asks for; from then //! on, pass every thread start and end on to the attached images. +// The import call trace (`LEONIDA_CALL_TRACE`), the format both runtimes write (tools/call_trace_diff.py). +#[cfg(windows)] +pub mod call_trace; #[cfg(windows)] mod console_insn; mod crash; diff --git a/d3d12/crates/leonida-loader/src/windows.rs b/d3d12/crates/leonida-loader/src/windows.rs index b2334458f1..c07387c9b5 100644 --- a/d3d12/crates/leonida-loader/src/windows.rs +++ b/d3d12/crates/leonida-loader/src/windows.rs @@ -13,6 +13,7 @@ use windows_sys::Win32::Foundation::{FreeLibrary, HMODULE}; use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryExW}; use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; +use crate::call_trace::{self, Bind}; use crate::thunks::{ImportSite, ThunkBlock, UnimplementedPolicy}; use crate::{ DLL_PROCESS_ATTACH, DLL_PROCESS_DETACH, ImportResolver, PreparedImage, Provenance, Resolution, @@ -282,11 +283,31 @@ impl LoadedImage { address, provenance, } => { - match provenance { - Provenance::Hle => report.hle += 1, - Provenance::Host => report.host += 1, - Provenance::Title => report.title += 1, - } + let bind = match provenance { + Provenance::Hle => { + report.hle += 1; + Some(Bind::Hle) + } + Provenance::Host => { + report.host += 1; + Some(Bind::Host) + } + Provenance::Title => { + report.title += 1; + call_trace::note_title_bound(&module.dll); + None + } + }; + // Traced by import identity, whatever it binds to (`LEONIDA_CALL_TRACE`; unset: unchanged). + let address = match bind { + Some(bind) if call_trace::enabled() => call_trace::wrap( + address, + &module.dll, + &entry.symbol.to_string(), + bind, + ), + _ => address, + }; slots.push((entry.iat_slot_rva, address)); } Resolution::Missing => { @@ -305,7 +326,14 @@ impl LoadedImage { policy, calls: AtomicU64::new(0), })); - slots.push((slot, block.emit(site)?)); + let stub = block.emit(site)?; + // Entry-only in the trace, so the stub's return address stays the title's. + let stub = if call_trace::enabled() { + call_trace::wrap(stub, dll, &site.symbol, Bind::Unimpl) + } else { + stub + }; + slots.push((slot, stub)); report.missing.push(MissingImport { dll: site.dll.clone(), symbol: site.symbol.clone(), @@ -314,6 +342,7 @@ impl LoadedImage { block.seal()?; } + call_trace::seal()?; self.write_slots(&slots)?; tracing::info!( hle = report.hle, @@ -442,6 +471,8 @@ impl LoadedImage { .name("title-main".into()) .stack_size(stack) .spawn(move || { + // `start=main` in the call trace. + call_trace::mark_main_thread(); for (name, dll) in &dlls { // SAFETY: forwarded from the caller of `spawn_main`. unsafe { dll.attach() }.with_context(|| format!("attaching {name}"))?; diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 765b2611a6..b132e689d7 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1641,6 +1641,19 @@ if(BUILD_TESTING) add_test(NAME startup_trace COMMAND startup_trace_test) endif() + # LEONIDA_CALL_TRACE (shims/call_trace.h): thunks, the two common stubs, RT_CALLER and the writer, on hand-written + # functions; two cases run in children of this executable (a killed process, a 1 MiB cap). It compiles no shim and + # links no loader. No game files, no GPU. + if(WIN32) + add_executable(call_trace_test test/call_trace_test.cpp) + target_include_directories(call_trace_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_compile_definitions(call_trace_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) + target_compile_options(call_trace_test PRIVATE /W4 /permissive- /utf-8 /EHsc) + target_link_options(call_trace_test PRIVATE /OPT:NOREF /OPT:NOICF) + add_test(NAME call_trace COMMAND call_trace_test) + set_tests_properties(call_trace PROPERTIES TIMEOUT 300) + endif() + if(WIN32) add_executable(present_window_test test/present_window_test.cpp) target_link_libraries(present_window_test PRIVATE user32) diff --git a/runtime/README.md b/runtime/README.md index 62b7db7bcc..06551a8e32 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -363,6 +363,8 @@ document names. | `LEONIDA_TITLE_MEMORY_MB` | unset | Caps the title memory limit (in MiB, clamped to `2048..65536`) reported by both `XSystemGetAppMemoryUsageLimit` (`xgameruntime.cpp`) and `XMemGetWorkingSetStatistics` (`xmem.cpp`). Useful on 16 GB RAM / low-VRAM hosts to prevent oversized title pools; invalid or non-positive values are ignored and fall back to the host memory report. | | `LEONIDA_TRACE_XGAMESAVE` | unset | *Diagnostic.* `1` logs one `[rt] xgamesave:` line to stderr per `XGameSave*` and `XGameSaveFiles*` call (`shims/xgameruntime_gamesave.cpp`): the call, its handles, container and blob names, sizes and HRESULT, after `t=ms tid=`. An async call also logs when its job is scheduled, when its work runs (with how long it waited on the queue), when it completes and when the title collects it with the `...Result` call. Blob contents are never logged. Read once per process; unset, a call costs one load. | | `LEONIDA_STACKS` | unset | Comma-separated whole seconds after the title's entry point is called (e.g. `90,180`). At each time `--run` suspends every other thread in turn just long enough to copy its context and stack, then unwinds the copy (title frames through the unwind tables the loader registers) and prints to stderr `[rt] stacks t= thread ():` and up to 40 `#i module+0xRVA` frames, innermost first; a chain identical to an earlier thread's prints `same as thread `. | +| `LEONIDA_CALL_TRACE` | unset | *Diagnostic.* A path: writes the import call trace of the title there, one tab-separated line per call through the import tables of the main image and its DLLs, with the caller, the thread and a class for the return (never a raw value, a buffer or a string). The file is created new and gta6rt exits with code 2 when it exists or cannot be created. Details in [Import call trace](#import-call-trace-leonida_call_trace). | +| `LEONIDA_CALL_TRACE_MAX_MB` | `4096` | *Diagnostic.* A whole number of MiB, `1` to `1048576`: the size at which `LEONIDA_CALL_TRACE` writes `# truncated` and stops recording. Anything else makes gta6rt exit with code 2. | ### Switches of the D3D12 layer for a retail boot @@ -703,6 +705,17 @@ Each trace line contains a sequence number, a fixed API name and an outcome. `ca whose validation may be deferred. `ok`, `failed` and `unsupported` report known results. `ignored` marks a no-op. Share only the lines prefixed with `[d3d12-trace]`. Other runtime diagnostics are separate. +### Import call trace: `LEONIDA_CALL_TRACE` + +`LEONIDA_CALL_TRACE=` records every call the title makes through its import tables ([shims/call_trace.h](shims/call_trace.h)), +in the format `leonida-hle` writes, so the two runtimes' traces can be compared. Each traced +import gets a small thunk and a common stub that logs the call (`C`, then `R` with the class of the return, or only `E` for +the imports that cannot have a frame in front of them: `setjmp`, the noreturn calls, the variadics); `tools/call_trace_rules.def` +says which imports are skipped and how a return is classified. The file is created new before any module is mapped and gta6rt +refuses an existing path (exit code 2). It is written through mapped views, so it survives a crash and may end in NUL bytes +and a partial line, and `LEONIDA_CALL_TRACE_MAX_MB` (default 4096) ends it with `# truncated`. It holds no game data: import +and DLL names, `game+0xRVA` addresses, thread ids and return classes only. With the variable unset nothing changes. + ### Startup trace: `--trace FILE` `--trace FILE` (with `--dry-run`, `--init` or `--run`, before the `--` separator) writes one JSON object per line diff --git a/runtime/shims/call_trace.h b/runtime/shims/call_trace.h new file mode 100644 index 0000000000..eb050735ca --- /dev/null +++ b/runtime/shims/call_trace.h @@ -0,0 +1,750 @@ +// Import call trace: LEONIDA_CALL_TRACE= writes one line per call the title makes through its import tables. +// The format and the rules are the ones leonida-hle writes, so the two traces can be compared. +// +// What is traced: every import slot of the main image and the title's DLLs, by import identity, whatever it binds to, +// except the CT_SKIP rules (tools/call_trace_rules.def, included below), data imports (a target that is not on a +// committed executable page) and imports bound to a title module (named once as `# title-bound `). +// +// Each traced import gets a 24-byte thunk (`mov r10, site; mov rax, stub; jmp rax`) and a Site. Two common stubs +// share one page (the bytes are in kBlob, with their offsets): the entry stub records the call and jumps to the +// target, so the target sees the real return address (setjmp, noreturn calls, variadics); the wrap stub keeps a frame, +// copies 16 stack-argument qwords, calls the target and records the return. Both are registered with +// RtlAddFunctionTable, so exceptions and stack walks pass through them. There is no shadow stack and no TLS: a +// longjmp or an exception past a wrap frame leaves a C line without its R. +// +// File: UTF-8, LF, TAB-separated, created new (an existing file is refused) and written through 4 MiB mapped views, so +// it survives the process dying, may end in NUL bytes and may end in a partial line. +// # leonida-call-trace 1 stack=gta6rt rules=<16 hex> +// # title-bound +// # truncated +// # dropped records given up on (writer lock held for 10 ms), cumulative +// T a thread's first traced call +// C ! call entered +// R that call returned +// E ! entry-only call, no R follows +// The file never holds a buffer, a string read from the title (apart from the import names of its own tables) or a raw +// return value: is a class (hr, u, b, p:0, p:1, p:-1) or `-`. It names no game data. +// +// With the switch unset nothing here runs: wrap() returns its target and no page, thunk or file is made. +// Everything shared lives in constant-initialised inline variables and plain-data thread_locals (no destructor, no +// block-scope static): this code runs on title threads under the loader, where a thread-exit registration with the +// shared C runtime makes the title abort. +#pragma once + +#include + +#include +#include +#include +#include +#include +#include + +#include "call_trace_caller.h" + +namespace rt::call_trace { + +enum class Bind : uint8_t { Shim, Hle, Host, Unimpl }; +enum class OpenResult { Off, On, Failed }; + +namespace detail { + +// ---- rules ------------------------------------------------------------------------------------------------------- + +enum class Rk : uint8_t { Skip, SkipHas, SkipModule, Entry, EntryHas, Void, Bool, U32, Hr, HrMod, NotHr }; +struct Rule { + Rk kind; + const char* macro; // as written in the file, hashed with its arguments + const char* a; + const char* b; // CT_HR_MOD's prefix, else null +}; + +#define CT_SKIP(n) {Rk::Skip, "CT_SKIP", n, nullptr}, +#define CT_SKIP_HAS(n) {Rk::SkipHas, "CT_SKIP_HAS", n, nullptr}, +#define CT_SKIP_MODULE(n) {Rk::SkipModule, "CT_SKIP_MODULE", n, nullptr}, +#define CT_ENTRY(n) {Rk::Entry, "CT_ENTRY", n, nullptr}, +#define CT_ENTRY_HAS(n) {Rk::EntryHas, "CT_ENTRY_HAS", n, nullptr}, +#define CT_VOID(n) {Rk::Void, "CT_VOID", n, nullptr}, +#define CT_BOOL(n) {Rk::Bool, "CT_BOOL", n, nullptr}, +#define CT_U32(n) {Rk::U32, "CT_U32", n, nullptr}, +#define CT_HR(n) {Rk::Hr, "CT_HR", n, nullptr}, +#define CT_HR_MOD(m, p) {Rk::HrMod, "CT_HR_MOD", m, p}, +#define CT_NOT_HR(n) {Rk::NotHr, "CT_NOT_HR", n, nullptr}, +inline constexpr Rule kRules[] = { +#include "../../tools/call_trace_rules.def" +}; +#undef CT_SKIP +#undef CT_SKIP_HAS +#undef CT_SKIP_MODULE +#undef CT_ENTRY +#undef CT_ENTRY_HAS +#undef CT_VOID +#undef CT_BOOL +#undef CT_U32 +#undef CT_HR +#undef CT_HR_MOD +#undef CT_NOT_HR + +constexpr bool same(const char* a, const char* b) { + while (*a && *a == *b) ++a, ++b; + return *a == *b; +} +constexpr bool starts(const char* s, const char* prefix) { + while (*prefix && *s == *prefix) ++s, ++prefix; + return *prefix == 0; +} +constexpr bool contains(const char* s, const char* part) { + if (!*part) return true; + for (; *s; ++s) + if (starts(s, part)) return true; + return false; +} + +// FNV-1a 64 over each rule in file order: the macro name, a NUL, each argument, a NUL. +constexpr uint64_t rules_hash() { + uint64_t h = 0xcbf29ce484222325ull; + auto feed = [&h](const char* s) { + for (; *s; ++s) h = (h ^ static_cast(*s)) * 0x100000001b3ull; + h = (h ^ 0u) * 0x100000001b3ull; + }; + for (const Rule& r : kRules) { + feed(r.macro); + feed(r.a); + if (r.b) feed(r.b); + } + return h; +} + +enum Cls : uint8_t { kClsP, kClsHr, kClsU32, kClsBool, kClsVoid }; +enum Action : uint8_t { kSkip, kEntry, kWrap }; +struct Decision { + Action action; + Cls cls; +}; + +// Order of precedence: SKIP, then ENTRY, then the class: VOID, BOOL, U32, HR, NOT_HR, HR_MOD, else the default. +// `module` is the lower-case DLL name of the import descriptor. +constexpr Decision decide(const char* module, const char* fn) { + for (const Rule& r : kRules) { + if ((r.kind == Rk::Skip && same(fn, r.a)) || (r.kind == Rk::SkipHas && contains(fn, r.a)) || + (r.kind == Rk::SkipModule && starts(module, r.a))) + return {kSkip, kClsP}; + } + for (const Rule& r : kRules) { + if ((r.kind == Rk::Entry && same(fn, r.a)) || (r.kind == Rk::EntryHas && contains(fn, r.a))) + return {kEntry, kClsP}; + } + auto named = [&](Rk k) { + for (const Rule& r : kRules) + if (r.kind == k && same(fn, r.a)) return true; + return false; + }; + if (named(Rk::Void)) return {kWrap, kClsVoid}; + if (named(Rk::Bool)) return {kWrap, kClsBool}; + if (named(Rk::U32)) return {kWrap, kClsU32}; + if (named(Rk::Hr)) return {kWrap, kClsHr}; + if (named(Rk::NotHr)) return {kWrap, kClsP}; + for (const Rule& r : kRules) + if (r.kind == Rk::HrMod && same(module, r.a) && starts(fn, r.b)) return {kWrap, kClsHr}; + return {kWrap, kClsP}; +} + +// ---- the common stub: the bytes the Rust harness exercised (20 integer arguments, float arguments, a struct return, +// the last error and a panic unwinding through both stubs), copied as they are with one change: the entry stub's +// RUNTIME_FUNCTION (byte 0x1c4) ends at 0x7F, not 0x82. The unwinder does not take `jmp [r10]` (41 FF 22, at 0x7F) for +// an epilogue, so a walk of a thread stopped there would read a frame that is already gone; outside the function it +// is a leaf and the return address is at [rsp], which is where it is after the `add rsp, 0x98` before it. ---------- + +constexpr size_t kBlobSize = 0x1d8; +constexpr size_t kWrapOffset = 0x090; // wrap stub; the entry stub is at 0 +constexpr size_t kWrapRetOffset = 0x159; // return address of the wrap stub's call to the target +constexpr size_t kEnterSlot = 0x1a0; // pointer slots, written before the page becomes executable +constexpr size_t kLeaveSlot = 0x1a8; +constexpr size_t kFunctionTable = 0x1c0; // RUNTIME_FUNCTION[2] relative to the blob start; UNWIND_INFO at 0x1b0 and 0x1b8 +inline constexpr uint8_t kBlob[kBlobSize] = { + /* 000 */ 0x48, 0x81, 0xEC, 0x98, 0x00, 0x00, 0x00, 0x48, 0x89, 0x4C, 0x24, 0x20, 0x48, 0x89, 0x54, 0x24, + /* 010 */ 0x28, 0x4C, 0x89, 0x44, 0x24, 0x30, 0x4C, 0x89, 0x4C, 0x24, 0x38, 0x0F, 0x29, 0x44, 0x24, 0x40, + /* 020 */ 0x0F, 0x29, 0x4C, 0x24, 0x50, 0x0F, 0x29, 0x54, 0x24, 0x60, 0x0F, 0x29, 0x5C, 0x24, 0x70, 0x4C, + /* 030 */ 0x89, 0x94, 0x24, 0x80, 0x00, 0x00, 0x00, 0x4C, 0x89, 0xD1, 0x48, 0x8B, 0x94, 0x24, 0x98, 0x00, + /* 040 */ 0x00, 0x00, 0xFF, 0x15, 0x58, 0x01, 0x00, 0x00, 0x4C, 0x8B, 0x94, 0x24, 0x80, 0x00, 0x00, 0x00, + /* 050 */ 0x48, 0x8B, 0x4C, 0x24, 0x20, 0x48, 0x8B, 0x54, 0x24, 0x28, 0x4C, 0x8B, 0x44, 0x24, 0x30, 0x4C, + /* 060 */ 0x8B, 0x4C, 0x24, 0x38, 0x0F, 0x28, 0x44, 0x24, 0x40, 0x0F, 0x28, 0x4C, 0x24, 0x50, 0x0F, 0x28, + /* 070 */ 0x54, 0x24, 0x60, 0x0F, 0x28, 0x5C, 0x24, 0x70, 0x48, 0x81, 0xC4, 0x98, 0x00, 0x00, 0x00, 0x41, + /* 080 */ 0xFF, 0x22, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, + /* 090 */ 0x48, 0x81, 0xEC, 0x38, 0x01, 0x00, 0x00, 0x48, 0x89, 0x8C, 0x24, 0xA0, 0x00, 0x00, 0x00, 0x48, + /* 0a0 */ 0x89, 0x94, 0x24, 0xA8, 0x00, 0x00, 0x00, 0x4C, 0x89, 0x84, 0x24, 0xB0, 0x00, 0x00, 0x00, 0x4C, + /* 0b0 */ 0x89, 0x8C, 0x24, 0xB8, 0x00, 0x00, 0x00, 0x0F, 0x29, 0x84, 0x24, 0xC0, 0x00, 0x00, 0x00, 0x0F, + /* 0c0 */ 0x29, 0x8C, 0x24, 0xD0, 0x00, 0x00, 0x00, 0x0F, 0x29, 0x94, 0x24, 0xE0, 0x00, 0x00, 0x00, 0x0F, + /* 0d0 */ 0x29, 0x9C, 0x24, 0xF0, 0x00, 0x00, 0x00, 0x4C, 0x89, 0x94, 0x24, 0x00, 0x01, 0x00, 0x00, 0x4C, + /* 0e0 */ 0x89, 0xD1, 0x48, 0x8B, 0x94, 0x24, 0x38, 0x01, 0x00, 0x00, 0xFF, 0x15, 0xB0, 0x00, 0x00, 0x00, + /* 0f0 */ 0x48, 0x89, 0x84, 0x24, 0x08, 0x01, 0x00, 0x00, 0x31, 0xC0, 0x4C, 0x8B, 0x9C, 0xC4, 0x60, 0x01, + /* 100 */ 0x00, 0x00, 0x4C, 0x89, 0x5C, 0xC4, 0x20, 0xFF, 0xC0, 0x83, 0xF8, 0x10, 0x72, 0xEC, 0x4C, 0x8B, + /* 110 */ 0x94, 0x24, 0x00, 0x01, 0x00, 0x00, 0x48, 0x8B, 0x8C, 0x24, 0xA0, 0x00, 0x00, 0x00, 0x48, 0x8B, + /* 120 */ 0x94, 0x24, 0xA8, 0x00, 0x00, 0x00, 0x4C, 0x8B, 0x84, 0x24, 0xB0, 0x00, 0x00, 0x00, 0x4C, 0x8B, + /* 130 */ 0x8C, 0x24, 0xB8, 0x00, 0x00, 0x00, 0x0F, 0x28, 0x84, 0x24, 0xC0, 0x00, 0x00, 0x00, 0x0F, 0x28, + /* 140 */ 0x8C, 0x24, 0xD0, 0x00, 0x00, 0x00, 0x0F, 0x28, 0x94, 0x24, 0xE0, 0x00, 0x00, 0x00, 0x0F, 0x28, + /* 150 */ 0x9C, 0x24, 0xF0, 0x00, 0x00, 0x00, 0x41, 0xFF, 0x12, 0x48, 0x89, 0x84, 0x24, 0x10, 0x01, 0x00, + /* 160 */ 0x00, 0x0F, 0x29, 0x84, 0x24, 0x20, 0x01, 0x00, 0x00, 0x48, 0x8B, 0x8C, 0x24, 0x00, 0x01, 0x00, + /* 170 */ 0x00, 0x48, 0x8B, 0x94, 0x24, 0x08, 0x01, 0x00, 0x00, 0x49, 0x89, 0xC0, 0xFF, 0x15, 0x26, 0x00, + /* 180 */ 0x00, 0x00, 0x48, 0x8B, 0x84, 0x24, 0x10, 0x01, 0x00, 0x00, 0x0F, 0x28, 0x84, 0x24, 0x20, 0x01, + /* 190 */ 0x00, 0x00, 0x48, 0x81, 0xC4, 0x38, 0x01, 0x00, 0x00, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, + /* 1a0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + /* 1b0 */ 0x01, 0x07, 0x02, 0x00, 0x07, 0x01, 0x13, 0x00, 0x01, 0x07, 0x02, 0x00, 0x07, 0x01, 0x27, 0x00, + /* 1c0 */ 0x00, 0x00, 0x00, 0x00, 0x7F, 0x00, 0x00, 0x00, 0xB0, 0x01, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00, + /* 1d0 */ 0x9A, 0x01, 0x00, 0x00, 0xB8, 0x01, 0x00, 0x00, +}; + +// What a thunk's r10 points at; the stubs know only the target at offset 0. +struct Site { + void* target; // 0 + const char* bind; // 8: "shim", "hle", "host" or "unimpl" + uint8_t wrap; // 16: 1 = C/R, 0 = E + uint8_t cls; // 17 + uint8_t name_len; // 18 + uint8_t bind_len; // 19 + char name[172]; // 20: "module!function", printable ASCII only +}; +static_assert(sizeof(Site) == 192); +static_assert(offsetof(Site, target) == 0); + +// ---- state ------------------------------------------------------------------------------------------------------- + +inline constexpr size_t kViewBytes = size_t{4} << 20; +inline constexpr size_t kPoolBytes = size_t{64} << 10; +inline constexpr uint32_t kModules = 64; +inline constexpr uint64_t kDefaultCapMiB = 4096; +inline constexpr size_t kPremapRoom = 352; // a line is at most 320 bytes; the marker 12 + +struct ModEntry { + std::atomic base; // written last, with release: non-zero means the entry is complete + uint32_t size; + uint8_t len; + char name[31]; +}; +struct Pool { + uint8_t* base; + size_t used; +}; + +inline std::atomic g_on{false}; // recording; false once the cap is reached +inline SRWLOCK g_lock = SRWLOCK_INIT; // seq, formatting and the copy into the file +inline SRWLOCK g_wrap_lock = SRWLOCK_INIT; // pools +inline uint64_t g_seq = 0; +inline HANDLE g_file = nullptr; +inline HANDLE g_map = nullptr; +inline uint8_t* g_view = nullptr; +inline uint64_t g_view_off = 0; // file offset of g_view +inline uint64_t g_pos = 0; // file offset of the next byte +inline HANDLE g_next_map = nullptr; // the view after g_view, mapped before it is needed +inline uint8_t* g_next_view = nullptr; +inline std::atomic g_dropped{0}; // records given up on because the writer lock stayed taken +inline uint64_t g_dropped_said = 0; // under g_lock: the count the last `# dropped` line carried +inline uint64_t g_cap = 0; +inline uint8_t* g_stub = nullptr; +inline ModEntry g_mods[kModules] = {}; +inline std::atomic g_nmods{0}; +inline Pool g_thunks = {}; // RWX +inline Pool g_sites = {}; // RW +inline char g_bound[kModules][32] = {}; +inline uint32_t g_nbound = 0; // under g_lock +inline LONG(NTAPI* g_nt_query_thread)(HANDLE, ULONG, PVOID, ULONG, PULONG) = nullptr; +inline thread_local bool t_seen = false; // plain data on purpose: no destructor +inline thread_local bool t_main = false; + +inline char lower_char(char c) { return (c >= 'A' && c <= 'Z') ? static_cast(c + 32) : c; } +inline char printable(char c) { return (static_cast(c) >= 0x21 && static_cast(c) <= 0x7e) ? c : '?'; } + +// A line is built here, then copied under the lock. +struct Line { + char b[320]; + size_t n = 0; + void c(char ch) { + if (n < sizeof b) b[n++] = ch; + } + void s(const char* p, size_t len) { + if (len > sizeof b - n) len = sizeof b - n; + std::memcpy(b + n, p, len); + n += len; + } + void sz(const char* p) { s(p, std::strlen(p)); } + void dec(uint64_t v) { + char t[20]; + size_t k = 0; + do { + t[k++] = static_cast('0' + v % 10); + v /= 10; + } while (v); + while (k && n < sizeof b) b[n++] = t[--k]; + } + void digits(uint64_t v, unsigned count) { + for (unsigned i = count; i-- && n < sizeof b;) b[n++] = "0123456789abcdef"[(v >> (4 * i)) & 15]; + } + void hex(uint64_t v) { + unsigned count = 1; + while (count < 16 && (v >> (4 * count))) ++count; + digits(v, count); + } + // `module+0xRVA` of a title module, else `?`. + void addr(uintptr_t a) { + const uint32_t count = g_nmods.load(std::memory_order_relaxed); + for (uint32_t i = 0; i < count && i < kModules; ++i) { + const ModEntry& m = g_mods[i]; + const uintptr_t base = m.base.load(std::memory_order_acquire); + if (base && a >= base && a - base < m.size) { + s(m.name, m.len); + s("+0x", 3); + hex(a - base); + return; + } + } + c('?'); + } +}; + +// ---- writer (under g_lock) --------------------------------------------------------------------------------------- + +inline bool map_pair(uint64_t off, HANDLE* map, uint8_t** view) { + const uint64_t end = off + kViewBytes; // creating the mapping extends the file + HANDLE m = CreateFileMappingW(g_file, nullptr, PAGE_READWRITE, static_cast(end >> 32), + static_cast(end), nullptr); + if (!m) return false; + auto* v = static_cast( + MapViewOfFile(m, FILE_MAP_WRITE, static_cast(off >> 32), static_cast(off), kViewBytes)); + if (!v) { + CloseHandle(m); + return false; + } + *map = m; + *view = v; + return true; +} + +inline bool map_view(uint64_t off) { + if (g_view) UnmapViewOfFile(g_view); + g_view = nullptr; + if (g_map) CloseHandle(g_map); + g_map = nullptr; + if (!map_pair(off, &g_map, &g_view)) return false; + g_view_off = off; + return true; +} + +// A line that crosses the end of a view is split; the next view is normally mapped long before (see put). +inline void append(const char* p, size_t n) { + while (n) { + size_t room = kViewBytes - static_cast(g_pos - g_view_off); + if (!room) { + if (!g_next_view && !map_pair(g_view_off + kViewBytes, &g_next_map, &g_next_view)) { + g_on.store(false, std::memory_order_release); + return; + } + UnmapViewOfFile(g_view); + CloseHandle(g_map); + g_view = g_next_view; + g_map = g_next_map; + g_next_view = nullptr; + g_next_map = nullptr; + g_view_off += kViewBytes; + room = kViewBytes; + } + const size_t k = n < room ? n : room; + std::memcpy(g_view + (g_pos - g_view_off), p, k); + g_pos += k; + p += k; + n -= k; + } +} + +// True when the line was written. At the cap `# truncated` is written instead and recording stops. The next view is +// mapped while the current one still has room for a line (and the marker), so when that mapping fails the file can +// still end in `# truncated`. +inline bool put(const char* p, size_t n) { + if (!g_on.load(std::memory_order_relaxed)) return false; + if (g_pos + n + 16 > g_cap) { + append("# truncated\n", 12); + g_on.store(false, std::memory_order_release); + return false; + } + const size_t room = kViewBytes - static_cast(g_pos - g_view_off); + if (room < kPremapRoom && !g_next_view && g_view_off + kViewBytes < g_cap && + !map_pair(g_view_off + kViewBytes, &g_next_map, &g_next_view)) { + if (room >= 12) append("# truncated\n", 12); // true here: the previous record saw kPremapRoom and left 32 + g_on.store(false, std::memory_order_release); + return false; + } + append(p, n); + return g_on.load(std::memory_order_relaxed); +} + +// The writer lock, taken with a bound: a title that suspends one of its threads inside enter or leave (SuspendThread, +// GetThreadContext) would otherwise wait for a lock that thread holds. After 10 ms the record is dropped and counted; +// the next record that gets the lock says so (`# dropped `). +inline bool lock_writer() { + if (TryAcquireSRWLockExclusive(&g_lock)) return true; + LARGE_INTEGER freq{}, start{}, now{}; + QueryPerformanceFrequency(&freq); + QueryPerformanceCounter(&start); + const LONGLONG limit = freq.QuadPart / 100; + for (;;) { + SwitchToThread(); + if (TryAcquireSRWLockExclusive(&g_lock)) return true; + QueryPerformanceCounter(&now); + if (now.QuadPart - start.QuadPart >= limit) { + g_dropped.fetch_add(1, std::memory_order_relaxed); + return false; + } + } +} + +inline void unlock_writer() { ReleaseSRWLockExclusive(&g_lock); } + +// Under the lock, before the next record. +inline void say_dropped() { + const uint64_t d = g_dropped.load(std::memory_order_relaxed); + if (d == g_dropped_said) return; + Line l; + l.sz("# dropped "); + l.dec(d); + l.c('\n'); + if (put(l.b, l.n)) g_dropped_said = d; +} + +// ---- the two functions the stubs call: host APIs only, last error saved and restored --------------------------- + +struct ThreadInfo { + char start[56]; + size_t start_len; + uint64_t created; +}; + +inline void thread_info(ThreadInfo& ti) { + Line l; + if (t_main) { + l.sz("main"); + } else { + uintptr_t start = 0; + if (g_nt_query_thread) { + ULONG got = 0; // class 9: ThreadQuerySetWin32StartAddress + if (g_nt_query_thread(GetCurrentThread(), 9, &start, sizeof start, &got) < 0) start = 0; + } + if (start) l.addr(start); + else l.c('?'); + } + ti.start_len = l.n < sizeof ti.start ? l.n : sizeof ti.start; + std::memcpy(ti.start, l.b, ti.start_len); + FILETIME created{}, exit_time{}, kernel{}, user{}; + ti.created = GetThreadTimes(GetCurrentThread(), &created, &exit_time, &kernel, &user) + ? (static_cast(created.dwHighDateTime) << 32) | created.dwLowDateTime + : 0; +} + +// Returns the call's seq, 0 when it was not recorded (also when the writer lock could not be had: see lock_writer). +inline uint64_t __stdcall enter(const Site* s, void* ret) { + if (!g_on.load(std::memory_order_relaxed)) return 0; + const DWORD error = GetLastError(); + const DWORD tid = GetCurrentThreadId(); + ThreadInfo ti{}; + const bool first = !t_seen; + if (first) thread_info(ti); + uint64_t seq = 0; + if (lock_writer()) { + say_dropped(); + if (first && g_on.load(std::memory_order_relaxed)) { + Line l; + l.dec(++g_seq); + l.c('\t'); + l.dec(tid); + l.s("\tT\t", 3); + l.s(ti.start, ti.start_len); + l.c('\t'); + l.dec(ti.created); + l.c('\n'); + if (put(l.b, l.n)) t_seen = true; // a dropped record leaves the T line for the thread's next call + } + if (g_on.load(std::memory_order_relaxed)) { + Line l; + const uint64_t n = ++g_seq; + l.dec(n); + l.c('\t'); + l.dec(tid); + l.s(s->wrap ? "\tC\t" : "\tE\t", 3); + l.s(s->name, s->name_len); + l.c('\t'); + l.addr(reinterpret_cast(ret)); + l.c('\t'); + l.s(s->bind, s->bind_len); + l.c('\n'); + if (put(l.b, l.n)) seq = n; + } + unlock_writer(); + } + SetLastError(error); + return seq; +} + +inline void __stdcall leave(const Site* s, uint64_t seq, uint64_t rax) { + if (!seq) return; + const DWORD error = GetLastError(); + const DWORD tid = GetCurrentThreadId(); + Line r; // the ret field, from the class only: raw rax is never written + switch (s->cls) { + case kClsHr: r.sz("hr:0x"); r.digits(static_cast(rax), 8); break; + case kClsU32: r.sz("u:0x"); r.digits(static_cast(rax), 8); break; + case kClsBool: r.sz((rax & 0xff) ? "b:1" : "b:0"); break; + case kClsVoid: r.c('-'); break; + default: + if (rax == 0) r.sz("p:0"); + else if (rax == ~0ull || rax == 0xffffffffull) r.sz("p:-1"); + else r.sz("p:1"); + } + if (lock_writer()) { + say_dropped(); + if (g_on.load(std::memory_order_relaxed)) { + Line l; + l.dec(++g_seq); + l.c('\t'); + l.dec(tid); + l.s("\tR\t", 3); + l.dec(seq); + l.c('\t'); + l.s(r.b, r.n); + l.c('\n'); + put(l.b, l.n); + } + unlock_writer(); + } + SetLastError(error); +} + +// ---- setup ------------------------------------------------------------------------------------------------------- + +inline uint8_t* pool_take(Pool& pool, size_t size, DWORD protect) { + if (!pool.base || pool.used + size > kPoolBytes) { + pool.base = static_cast(VirtualAlloc(nullptr, kPoolBytes, MEM_RESERVE | MEM_COMMIT, protect)); + pool.used = 0; + if (!pool.base) return nullptr; + } + uint8_t* p = pool.base + pool.used; + pool.used += size; + return p; +} + +inline bool executable(const void* p) { + MEMORY_BASIC_INFORMATION mbi{}; + if (!VirtualQuery(p, &mbi, sizeof mbi) || mbi.State != MEM_COMMIT) return false; + return (mbi.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY)) != 0; +} + +inline uint8_t* make_stub() { + auto* page = static_cast(VirtualAlloc(nullptr, 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!page) return nullptr; + std::memcpy(page, kBlob, kBlobSize); + const uint64_t e = reinterpret_cast(&enter), l = reinterpret_cast(&leave); + std::memcpy(page + kEnterSlot, &e, 8); + std::memcpy(page + kLeaveSlot, &l, 8); + DWORD old = 0; + auto* table = reinterpret_cast(page + kFunctionTable); + if (!RtlAddFunctionTable(table, 2, reinterpret_cast(page))) { + VirtualFree(page, 0, MEM_RELEASE); + return nullptr; + } + if (!VirtualProtect(page, 0x1000, PAGE_EXECUTE_READ, &old)) { + RtlDeleteFunctionTable(table); // before the memory goes: the table must not outlive the page + VirtualFree(page, 0, MEM_RELEASE); + return nullptr; + } + FlushInstructionCache(GetCurrentProcess(), page, 0x1000); + return page; +} + +inline void fail(const char* what, DWORD code = 0) { + if (code) std::fprintf(stderr, "error: LEONIDA_CALL_TRACE: %s (error %lu)\n", what, code); + else std::fprintf(stderr, "error: LEONIDA_CALL_TRACE: %s\n", what); +} + +} // namespace detail + +// The file is created new and the switch refused when it exists or cannot be created: `Failed` (one line on stderr, +// the caller exits). Off when the variable is unset or empty. Call it once, before the first module is mapped. +inline OpenResult open_from_env() { + using namespace detail; + const DWORD chars = GetEnvironmentVariableW(L"LEONIDA_CALL_TRACE", nullptr, 0); + if (chars <= 1) return OpenResult::Off; + std::vector path(chars); + if (GetEnvironmentVariableW(L"LEONIDA_CALL_TRACE", path.data(), chars) + 1 != chars) return OpenResult::Off; + if (g_on.load()) return OpenResult::On; + + uint64_t cap_mib = kDefaultCapMiB; + char text[32] = {}; + const DWORD got = GetEnvironmentVariableA("LEONIDA_CALL_TRACE_MAX_MB", text, sizeof text); + if (got) { + uint64_t v = 0; + bool ok = got < sizeof text; + for (DWORD i = 0; ok && i < got; ++i) { + if (text[i] < '0' || text[i] > '9') ok = false; + else v = v * 10 + static_cast(text[i] - '0'); + } + if (!ok || v < 1 || v > (uint64_t{1} << 20)) { + std::fprintf(stderr, "error: LEONIDA_CALL_TRACE_MAX_MB: expected a whole number of MiB from 1 to 1048576\n"); + return OpenResult::Failed; + } + cap_mib = v; + } + + g_file = CreateFileW(path.data(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (g_file == INVALID_HANDLE_VALUE) { + g_file = nullptr; + const DWORD error = GetLastError(); + if (error == ERROR_FILE_EXISTS || error == ERROR_ALREADY_EXISTS) + fail("the file already exists; the call trace only creates a new file"); + else + fail("cannot create the file", error); + return OpenResult::Failed; + } + auto undo = [&](const char* what, DWORD error) { + fail(what, error); + if (g_view) UnmapViewOfFile(g_view); + if (g_map) CloseHandle(g_map); + CloseHandle(g_file); + DeleteFileW(path.data()); // the file this call created, still empty + g_view = nullptr; + g_map = nullptr; + g_file = nullptr; + g_pos = g_view_off = 0; + return OpenResult::Failed; + }; + g_pos = g_view_off = 0; + if (!map_view(0)) return undo("cannot map the file", GetLastError()); + g_cap = cap_mib << 20; + + char head[96]; + const int hn = std::snprintf(head, sizeof head, "# leonida-call-trace 1 stack=gta6rt rules=%016llx\n", + static_cast(rules_hash())); + append(head, static_cast(hn)); + + g_stub = make_stub(); + if (!g_stub) return undo("cannot build the call stubs", GetLastError()); + if (HMODULE nt = GetModuleHandleW(L"ntdll.dll")) + g_nt_query_thread = reinterpret_cast( + reinterpret_cast(GetProcAddress(nt, "NtQueryInformationThread"))); + g_wrap_ret = g_stub + kWrapRetOffset; + g_on.store(true, std::memory_order_release); + return OpenResult::On; +} + +inline bool enabled() noexcept { return detail::g_on.load(std::memory_order_acquire); } + +// Records a title module (lower-case name) for the caller and start fields. Entries are never removed. +inline void add_module(const char* name, const void* base, uint32_t size) { + using namespace detail; + if (!enabled() || !base) return; + const uint32_t i = g_nmods.fetch_add(1); + if (i >= kModules) return; + ModEntry& m = g_mods[i]; + size_t n = std::strlen(name); + if (n > sizeof m.name) n = sizeof m.name; + for (size_t k = 0; k < n; ++k) m.name[k] = printable(lower_char(name[k])); + m.len = static_cast(n); + m.size = size; + m.base.store(reinterpret_cast(base), std::memory_order_release); +} + +// Renames the entry of the main image `game`. Before any title code runs. +inline void set_main_module(const void* base) { + using namespace detail; + if (!enabled()) return; + const uint32_t count = g_nmods.load(); + for (uint32_t i = 0; i < count && i < kModules; ++i) { + ModEntry& m = g_mods[i]; + if (m.base.load(std::memory_order_acquire) == reinterpret_cast(base)) { + std::memcpy(m.name, "game", 4); + m.len = 4; + return; + } + } +} + +// The calling thread is the title's main thread: its T line says `main` as the start. +inline void mark_main_thread() { + if (detail::g_on.load(std::memory_order_relaxed)) detail::t_main = true; +} + +// Imports of `dll` resolve to a title module and are not traced: said once per DLL. +inline void note_title_bound(const char* dll) { + using namespace detail; + if (!enabled()) return; + char name[32] = {}; + size_t n = std::strlen(dll); + if (n > sizeof name - 1) n = sizeof name - 1; + for (size_t k = 0; k < n; ++k) name[k] = printable(lower_char(dll[k])); + if (!lock_writer()) return; + say_dropped(); + bool seen = false; + for (uint32_t i = 0; i < g_nbound; ++i) + if (std::strcmp(g_bound[i], name) == 0) seen = true; + if (!seen && g_nbound < kModules && g_on.load(std::memory_order_relaxed)) { + std::memcpy(g_bound[g_nbound++], name, n + 1); + Line l; + l.sz("# title-bound "); + l.s(name, n); + l.c('\n'); + put(l.b, l.n); + } + unlock_writer(); +} + +// The address to store in the import slot: `target` itself when the trace is off, the rules skip the import, or the +// target is data; else a thunk. `dll` is the import descriptor's name, `sym` the import name or `#ordinal`. +// Unimplemented thunks are entry-only. +inline void* wrap(void* target, const char* dll, const char* sym, Bind bind) { + using namespace detail; + if (!target || !g_on.load(std::memory_order_acquire)) return target; + char module[260]; + size_t mn = std::strlen(dll); + if (mn > sizeof module - 1) mn = sizeof module - 1; + for (size_t k = 0; k < mn; ++k) module[k] = lower_char(dll[k]); + module[mn] = 0; + const Decision d = decide(module, sym); + if (d.action == kSkip || !executable(target)) return target; + + static constexpr const char* kBindNames[] = {"shim", "hle", "host", "unimpl"}; + const char* bind_name = kBindNames[static_cast(bind)]; + + AcquireSRWLockExclusive(&g_wrap_lock); + auto* site = reinterpret_cast(pool_take(g_sites, sizeof(Site), PAGE_READWRITE)); + uint8_t* thunk = site ? pool_take(g_thunks, 24, PAGE_EXECUTE_READWRITE) : nullptr; + if (thunk) { + const bool entry_only = d.action == kEntry || bind == Bind::Unimpl; + site->target = target; + site->bind = bind_name; + site->bind_len = static_cast(std::strlen(bind_name)); + site->wrap = entry_only ? 0 : 1; + site->cls = d.cls; + size_t n = 0; + auto put_name = [&](const char* s, size_t len) { + for (size_t k = 0; k < len && n < sizeof site->name; ++k) site->name[n++] = printable(s[k]); + }; + put_name(module, mn); + put_name("!", 1); + put_name(sym, std::strlen(sym)); + site->name_len = static_cast(n); + const uint64_t site_address = reinterpret_cast(site); + const uint64_t stub_address = reinterpret_cast(g_stub + (entry_only ? 0 : kWrapOffset)); + uint8_t code[24]; + std::memset(code, 0xCC, sizeof code); + code[0] = 0x49; // mov r10, site + code[1] = 0xBA; + std::memcpy(code + 2, &site_address, 8); + code[10] = 0x48; // mov rax, stub + code[11] = 0xB8; + std::memcpy(code + 12, &stub_address, 8); + code[20] = 0xFF; // jmp rax + code[21] = 0xE0; + std::memcpy(thunk, code, sizeof code); + } + ReleaseSRWLockExclusive(&g_wrap_lock); + return thunk ? thunk : target; +} + +} // namespace rt::call_trace diff --git a/runtime/shims/call_trace_caller.h b/runtime/shims/call_trace_caller.h new file mode 100644 index 0000000000..baac466347 --- /dev/null +++ b/runtime/shims/call_trace_caller.h @@ -0,0 +1,31 @@ +// RT_CALLER(): the address a shim was called from, also when the import call trace (call_trace.h) put its wrap frame +// between the title and the shim. +// +// A shim that classifies its caller (xmem.cpp compares the caller's exact RVA, the file shims and the XApu/XDsp +// shims name it in their notes) must not read _ReturnAddress() directly: with LEONIDA_CALL_TRACE set the shim is +// called by the wrap stub, whose call to the target returns to one fixed address (g_wrap_ret), and the title's own +// return address sits 0x140 bytes above the shim's return-address slot (the stub's 0x138 frame plus the slot). +// tests/test_call_trace_rules.py rejects a raw _ReturnAddress() under runtime/shims and runtime/src outside this file +// and the two D3D12 COM files. +// +// With the trace off g_wrap_ret is null and RT_CALLER() is _ReturnAddress(). Header-only and light so every shim +// source can include it. +#pragma once + +#include + +namespace rt::call_trace { + +// Set once by call_trace.h before any thunk exists, never changed afterwards. A constant-initialised inline variable: +// it exists before any code runs, on every thread. +inline void* g_wrap_ret = nullptr; + +// `ra` is the shim's own return address, `aora` the address of the slot that holds it. +__forceinline void* real_caller(void* ra, void* aora) noexcept { + if (ra != nullptr && ra == g_wrap_ret) return *reinterpret_cast(static_cast(aora) + 0x140); + return ra; +} + +} // namespace rt::call_trace + +#define RT_CALLER() ::rt::call_trace::real_caller(_ReturnAddress(), _AddressOfReturnAddress()) diff --git a/runtime/shims/file_system.cpp b/runtime/shims/file_system.cpp index 6326f3cafe..df2506f10c 100644 --- a/runtime/shims/file_system.cpp +++ b/runtime/shims/file_system.cpp @@ -25,6 +25,7 @@ // host directly. #include #include +#include "call_trace_caller.h" #include #include @@ -874,37 +875,44 @@ bool touch_pages(void* buffer, DWORD size) { return all; } -HANDLE WINAPI create_file_w(LPCWSTR name, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES attributes, - DWORD disposition, DWORD flags, HANDLE template_file) { +// `caller` is the exported shim's RT_CALLER(): read there, in the frame the title called, not in this helper. +HANDLE create_file_w_impl(LPCWSTR name, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES attributes, + DWORD disposition, DWORD flags, HANDLE template_file, const void* caller) { if (!name) { SetLastError(ERROR_INVALID_PARAMETER); return INVALID_HANDLE_VALUE; } const Target t = open_target(name, access, disposition); if (t.error) { - note_open_failure("CreateFileW", name, t.error, _ReturnAddress()); + note_open_failure("CreateFileW", name, t.error, caller); SetLastError(t.error); return INVALID_HANDLE_VALUE; } const HANDLE h = ::CreateFileW(t.path.c_str(), access, share, attributes, disposition, flags, template_file); if (h == INVALID_HANDLE_VALUE) { const DWORD error = GetLastError(); - note_open_failure("CreateFileW", name, error, _ReturnAddress()); + note_open_failure("CreateFileW", name, error, caller); SetLastError(error); } else { - note_open("CreateFileW", name, access, _ReturnAddress()); + note_open("CreateFileW", name, access, caller); } return h; } +HANDLE WINAPI create_file_w(LPCWSTR name, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES attributes, + DWORD disposition, DWORD flags, HANDLE template_file) { + return create_file_w_impl(name, access, share, attributes, disposition, flags, template_file, RT_CALLER()); +} + HANDLE WINAPI create_file_a(LPCSTR name, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES attributes, DWORD disposition, DWORD flags, HANDLE template_file) { + const void* const caller = RT_CALLER(); if (!name) { SetLastError(ERROR_INVALID_PARAMETER); return INVALID_HANDLE_VALUE; } const std::wstring wide = widen_ansi(name); - return create_file_w(wide.c_str(), access, share, attributes, disposition, flags, template_file); + return create_file_w_impl(wide.c_str(), access, share, attributes, disposition, flags, template_file, caller); } HANDLE WINAPI create_file2(LPCWSTR name, DWORD access, DWORD share, DWORD disposition, @@ -915,17 +923,17 @@ HANDLE WINAPI create_file2(LPCWSTR name, DWORD access, DWORD share, DWORD dispos } const Target t = open_target(name, access, disposition); if (t.error) { - note_open_failure("CreateFile2", name, t.error, _ReturnAddress()); + note_open_failure("CreateFile2", name, t.error, RT_CALLER()); SetLastError(t.error); return INVALID_HANDLE_VALUE; } const HANDLE h = ::CreateFile2(t.path.c_str(), access, share, disposition, params); if (h == INVALID_HANDLE_VALUE) { const DWORD error = GetLastError(); - note_open_failure("CreateFile2", name, error, _ReturnAddress()); + note_open_failure("CreateFile2", name, error, RT_CALLER()); SetLastError(error); } else { - note_open("CreateFile2", name, access, _ReturnAddress()); + note_open("CreateFile2", name, access, RT_CALLER()); } return h; } diff --git a/runtime/shims/process.cpp b/runtime/shims/process.cpp index 1705bf5e4f..c5b5e7496f 100644 --- a/runtime/shims/process.cpp +++ b/runtime/shims/process.cpp @@ -44,6 +44,7 @@ #include #include +#include "call_trace.h" #include "process_shim.h" #include "shims.h" @@ -511,6 +512,7 @@ int __cdecl game_wgetmainargs(int* argc, wchar_t*** argv, wchar_t*** env, int ex // `p` is the entry point itself: run_entry can return (another thread ended the run) before this thread first runs, // so nothing of run_entry's frame may be read here. DWORD WINAPI game_thread(void* p) { + rt::call_trace::mark_main_thread(); // LEONIDA_CALL_TRACE: this thread's T line says `main` // An EXE entry point (mainCRTStartup and friends) takes the PEB pointer and returns the process exit code. auto entry = reinterpret_cast(p); const DWORD code = entry(nullptr); diff --git a/runtime/shims/xapu_chad.cpp b/runtime/shims/xapu_chad.cpp index e46a61c977..28c0906474 100644 --- a/runtime/shims/xapu_chad.cpp +++ b/runtime/shims/xapu_chad.cpp @@ -18,6 +18,7 @@ // the title's 0, so the zeroed status reads as "command 0 done, no error" and the title does not wait. #include #include +#include "call_trace_caller.h" #include #include @@ -54,7 +55,7 @@ void note(const char* api, uint64_t value, const void* caller) { HRESULT __stdcall XDspConnectWithMaximumStreamLimit(void* buffer, uint32_t a, uint32_t b, uint32_t max_streams, uint32_t flags, void** handle) { - note("XDspConnectWithMaximumStreamLimit", max_streams, _ReturnAddress()); + note("XDspConnectWithMaximumStreamLimit", max_streams, RT_CALLER()); (void)buffer; (void)a; (void)b; @@ -65,13 +66,13 @@ HRESULT __stdcall XDspConnectWithMaximumStreamLimit(void* buffer, uint32_t a, ui } HRESULT __stdcall XDspDisconnect(void* handle) { - note("XDspDisconnect", 0, _ReturnAddress()); + note("XDspDisconnect", 0, RT_CALLER()); delete static_cast(handle); return S_OK; } HRESULT __stdcall XDspActivate(void* handle, const void* description, void** status, void** stream) { - note("XDspActivate", 0, _ReturnAddress()); + note("XDspActivate", 0, RT_CALLER()); (void)description; auto* c = static_cast(handle); if (!c) return E_INVALIDARG; @@ -81,14 +82,14 @@ HRESULT __stdcall XDspActivate(void* handle, const void* description, void** sta } HRESULT __stdcall XDspDeactivate(void* handle, uint64_t, uint64_t, uint64_t) { - note("XDspDeactivate", 0, _ReturnAddress()); + note("XDspDeactivate", 0, RT_CALLER()); (void)handle; return S_OK; } // *id stays the 0 the title wrote, which the zeroed status block already reports as done. HRESULT __stdcall XDspSubmitCommand(void*, void*, uint32_t*) { - note("XDspSubmitCommand", 0, _ReturnAddress()); + note("XDspSubmitCommand", 0, RT_CALLER()); return S_OK; } diff --git a/runtime/shims/xapu_queue.cpp b/runtime/shims/xapu_queue.cpp index dc75774f9e..7c2c1452d7 100644 --- a/runtime/shims/xapu_queue.cpp +++ b/runtime/shims/xapu_queue.cpp @@ -42,6 +42,7 @@ // the crate, fill() decodes the packet and writes its PCM instead. #include #include +#include "call_trace_caller.h" #include #include @@ -288,7 +289,7 @@ void fill(Connection& connection, Stream& stream, const ProcessCommand& c, Resul } HRESULT __stdcall XApuConnect(const ConnectInput* input, ConnectOutput* output, Connection** out) { - note("XApuConnect", input ? input->processing : ~0ull, _ReturnAddress()); + note("XApuConnect", input ? input->processing : ~0ull, RT_CALLER()); if (!input || !output || !out) return E_INVALIDARG; *out = nullptr; ConnectInput in; @@ -349,7 +350,7 @@ HRESULT __stdcall XApuConnect(const ConnectInput* input, ConnectOutput* output, } HRESULT __stdcall XApuDisconnect(Connection* c, uint32_t /*0x20 at the measured site*/) { - note("XApuDisconnect", 0, _ReturnAddress()); + note("XApuDisconnect", 0, RT_CALLER()); { std::unique_lock lock(g_live_mu); if (!live(c)) return E_INVALIDARG; @@ -369,7 +370,7 @@ HRESULT __stdcall XApuEnqueueCommand(Connection* c, const void* command, uint32_ if (!c || !command) return E_INVALIDARG; CommandId id; std::memcpy(&id, command, sizeof(id)); - note("XApuEnqueueCommand", id.kind, _ReturnAddress()); + note("XApuEnqueueCommand", id.kind, RT_CALLER()); if (id.kind < kActivate || id.kind > kReset) return kInvalidCommand; const std::shared_lock live_lock(g_live_mu); @@ -433,7 +434,7 @@ HRESULT __stdcall XApuEnqueueCommand(Connection* c, const void* command, uint32_ } HRESULT __stdcall XApuDequeueResult(Connection* c, Result* out) { - note("XApuDequeueResult", 0, _ReturnAddress()); + note("XApuDequeueResult", 0, RT_CALLER()); if (!c || !out) return E_INVALIDARG; const std::shared_lock live_lock(g_live_mu); if (!live(c)) return E_INVALIDARG; @@ -448,7 +449,7 @@ HRESULT __stdcall XApuDequeueResult(Connection* c, Result* out) { } uint32_t __stdcall XApuGetResultCount(Connection* c, uint32_t* dequeued_so_far) { - note("XApuGetResultCount", 0, _ReturnAddress()); + note("XApuGetResultCount", 0, RT_CALLER()); const std::shared_lock live_lock(g_live_mu); if (!live(c)) return 0; const std::lock_guard lock(c->mutex); diff --git a/runtime/shims/xg_xs.cpp b/runtime/shims/xg_xs.cpp index 891ba0ec92..1536cc8a39 100644 --- a/runtime/shims/xg_xs.cpp +++ b/runtime/shims/xg_xs.cpp @@ -36,6 +36,7 @@ // and the slots no caller reaches (element coordinate, view descriptor), which log once and return E_NOTIMPL. #include #include +#include "call_trace_caller.h" #include #include @@ -102,14 +103,14 @@ void trace_desc(std::atomic& calls, const char* name, const void* call ULONG __stdcall add_ref(Computer* self) { static std::atomic calls{0}; const ULONG refs = self->texture.layout.planes ? self->refs.fetch_add(1, std::memory_order_relaxed) + 1 : 1; - trace(calls, "slot 0", _ReturnAddress(), "this=%p refs=%lu", self, refs); + trace(calls, "slot 0", RT_CALLER(), "this=%p refs=%lu", self, refs); return refs; } ULONG __stdcall release(Computer* self) { static std::atomic calls{0}; const ULONG refs = self->texture.layout.planes ? self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1 : 1; - trace(calls, "slot 1", _ReturnAddress(), "this=%p refs=%lu", self, refs); + trace(calls, "slot 1", RT_CALLER(), "this=%p refs=%lu", self, refs); if (!refs) delete self; return refs; } @@ -118,7 +119,7 @@ HRESULT __stdcall get_layout(Computer* self, ResourceLayout* out) { static std::atomic calls{0}; const auto& layout = self->texture.layout; const HRESULT hr = !layout.planes ? E_NOTIMPL : !out ? E_POINTER : S_OK; - trace(calls, "slot 2", _ReturnAddress(), "this=%p out=%p hr=0x%08x bytes=%llu align=%llu mips=%u planes=%u", + trace(calls, "slot 2", RT_CALLER(), "this=%p out=%p hr=0x%08x bytes=%llu align=%llu mips=%u planes=%u", self, out, uint32_t(hr), static_cast(layout.size), static_cast(layout.alignment), layout.mips, layout.planes); if (SUCCEEDED(hr)) { @@ -130,14 +131,14 @@ HRESULT __stdcall get_layout(Computer* self, ResourceLayout* out) { uint64_t __stdcall get_size(Computer* self) { static std::atomic calls{0}; const uint64_t bytes = self->texture.layout.size; - trace(calls, "slot 3", _ReturnAddress(), "this=%p bytes=%llu", self, static_cast(bytes)); + trace(calls, "slot 3", RT_CALLER(), "this=%p bytes=%llu", self, static_cast(bytes)); return bytes; } uint64_t __stdcall get_alignment(Computer* self) { static std::atomic calls{0}; const uint64_t bytes = self->texture.layout.alignment; - trace(calls, "slot 4", _ReturnAddress(), "this=%p bytes=%llu", self, static_cast(bytes)); + trace(calls, "slot 4", RT_CALLER(), "this=%p bytes=%llu", self, static_cast(bytes)); return bytes; } @@ -145,7 +146,7 @@ uint64_t __stdcall get_mip_offset(Computer* self, uint32_t plane, uint32_t level static std::atomic calls{0}; const auto& layout = self->texture.layout; const uint64_t offset = plane < layout.planes && level < layout.mips ? layout.plane[plane].mips[level].offset : 0; - trace(calls, "slot 5", _ReturnAddress(), "this=%p plane=%u mip=%u offset=%llu", + trace(calls, "slot 5", RT_CALLER(), "this=%p plane=%u mip=%u offset=%llu", self, plane, level, static_cast(offset)); return offset; } @@ -163,7 +164,7 @@ uint64_t __stdcall get_element_offset(Computer* self, uint32_t plane, uint32_t l offset = address.offset(mip, address.tail_origin(mip), uint32_t(x), y, z); } } - trace(calls, "slot 6", _ReturnAddress(), "this=%p plane=%u mip=%u x=%llu y=%u z=%u sample=%u bit=%p offset=%llu", + trace(calls, "slot 6", RT_CALLER(), "this=%p plane=%u mip=%u x=%llu y=%u z=%u sample=%u bit=%p offset=%llu", self, plane, level, static_cast(x), y, z, sample, bit, static_cast(offset)); return offset; @@ -200,7 +201,7 @@ HRESULT __stdcall copy_into(Computer* self, void* dst, uint32_t plane, uint32_t const HRESULT hr = copy_subresource(self->texture, plane, sub, 0, src, dst, row, slice); // The texture's image on the PC GPU is filled from this memory: tell the D3D12 layer it changed. if (SUCCEEDED(hr)) leonida::title_texel_writes::note(dst, size_t(self->texture.layout.size)); - trace(calls, "slot 8", _ReturnAddress(), "this=%p dst=%p plane=%u sub=%u src=%p row=%u slice=%u hr=0x%08x", + trace(calls, "slot 8", RT_CALLER(), "this=%p dst=%p plane=%u sub=%u src=%p row=%u slice=%u hr=0x%08x", self, dst, plane, sub, src, row, slice, uint32_t(hr)); return hr; } @@ -209,7 +210,7 @@ HRESULT __stdcall copy_from(Computer* self, void* dst, uint32_t plane, uint32_t const void* src, uint32_t row, uint32_t slice) { static std::atomic calls{0}; const HRESULT hr = copy_subresource(self->texture, plane, sub, sample, src, dst, row, slice); - trace(calls, "slot 9", _ReturnAddress(), "this=%p dst=%p plane=%u sub=%u sample=%u src=%p row=%u slice=%u hr=0x%08x", + trace(calls, "slot 9", RT_CALLER(), "this=%p dst=%p plane=%u sub=%u sample=%u src=%p row=%u slice=%u hr=0x%08x", self, dst, plane, sub, sample, src, row, slice, uint32_t(hr)); return hr; } @@ -255,7 +256,7 @@ HRESULT __stdcall get_tiling(Computer* self, uint32_t* total_tiles, PackedMips* } if (count) *count = written; } - trace(calls, "slot 10", _ReturnAddress(), + trace(calls, "slot 10", RT_CALLER(), "this=%p total=%p packed=%p shape=%p count=%p first=%u out=%p requested=%u written=%u " "hr=0x%08x tiles=%u standard=%u tail=%u tile=%ux%u", self, total_tiles, packed, shape, count, first, tilings, requested, written, uint32_t(hr), @@ -266,7 +267,7 @@ HRESULT __stdcall get_tiling(Computer* self, uint32_t* total_tiles, PackedMips* template HRESULT __stdcall unimplemented_slot(Computer* self) { static std::atomic calls{0}; - trace(calls, "unknown slot", _ReturnAddress(), "this=%p slot=%zu hr=0x80004001", self, Slot); + trace(calls, "unknown slot", RT_CALLER(), "this=%p slot=%zu hr=0x80004001", self, Slot); return E_NOTIMPL; } @@ -673,7 +674,7 @@ uint64_t __stdcall mip_offset(Computer* c, uint32_t plane, uint32_t mip) { template HRESULT __stdcall unused_slot(Computer*) { static std::atomic warned{false}; - warn_once(warned, "texture computer slot ", static_cast(Slot), _ReturnAddress(), + warn_once(warned, "texture computer slot ", static_cast(Slot), RT_CALLER(), "method not implemented; E_NOTIMPL"); return kNotImpl; } @@ -743,10 +744,10 @@ HRESULT __stdcall XGCreateTextureComputer(const void* desc, void** out) { // What xg_xs_layout.h cannot lay out, the second model may: targets, depth with stencil, other modes. port::ResourceDesc p; std::memcpy(&p, desc, sizeof(p)); - hr = port::create(p, out, _ReturnAddress()); + hr = port::create(p, out, RT_CALLER()); } } - trace_desc(calls, "create", _ReturnAddress(), desc ? &d : nullptr, out, 0, hr, t.mode, t.layout.size); + trace_desc(calls, "create", RT_CALLER(), desc ? &d : nullptr, out, 0, hr, t.mode, t.layout.size); // A refused computer is not harmless: the title's texture lock reads the layout it would have written // without checking, so say which descriptions are refused (at most 32 lines). static std::atomic refused{0}; @@ -756,7 +757,7 @@ HRESULT __stdcall XGCreateTextureComputer(const void* desc, void** out) { "layout=%#x flags=%#x (hr 0x%08x), caller %s\n", d.dimension, static_cast(d.width), d.height, unsigned(d.depth_or_array), unsigned(d.mips), d.format, d.samples, d.layout, d.flags, uint32_t(hr), - rt::shims::module_offset(reinterpret_cast(_ReturnAddress())).c_str()); + rt::shims::module_offset(reinterpret_cast(RT_CALLER())).c_str()); // LOCAL DIAGNOSTIC: LEONIDA_XG_TRACE_FORMAT= logs the first 256 computers of that format whatever // LEONIDA_XG_TRACE's cap, with the layout the title asked for (which tiling its CPU writes use). static const uint32_t only = [] { @@ -771,7 +772,7 @@ HRESULT __stdcall XGCreateTextureComputer(const void* desc, void** out) { d.format, d.dimension, static_cast(d.width), d.height, unsigned(d.depth_or_array), unsigned(d.mips), d.layout, d.flags, t.mode, static_cast(t.layout.size), uint32_t(hr), - rt::shims::module_offset(reinterpret_cast(_ReturnAddress())).c_str()); + rt::shims::module_offset(reinterpret_cast(RT_CALLER())).c_str()); return hr; } @@ -789,7 +790,7 @@ HRESULT __stdcall XGSuggestSwizzleMode(const void* desc, uint32_t options, uint3 hr = S_OK; } } - trace_desc(calls, "suggest", _ReturnAddress(), desc ? &d : nullptr, out, options, hr, mode, 0); + trace_desc(calls, "suggest", RT_CALLER(), desc ? &d : nullptr, out, options, hr, mode, 0); return hr; } diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 0d32d27a92..9bb88d5b42 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -17,6 +17,7 @@ #include #include #include +#include "call_trace_caller.h" #include #include @@ -237,12 +238,12 @@ void free_title_block(void* p) { } void* __stdcall XMemAlloc(size_t size, uint64_t attributes) { - note_attributes("XMemAlloc", attributes, size, _ReturnAddress()); + note_attributes("XMemAlloc", attributes, size, RT_CALLER()); return title_block(size); } void __stdcall XMemFree(void* p, uint64_t attributes) { - note_attributes("XMemFree", attributes, kNoSize, _ReturnAddress()); + note_attributes("XMemFree", attributes, kNoSize, RT_CALLER()); free_title_block(p); } @@ -251,12 +252,12 @@ void __stdcall XMemFree(void* p, uint64_t attributes) { // so they take exactly XMemAlloc's and XMemFree's arguments. They share the heap: a block from either allocator may be // released by either free. void* __stdcall XMemAllocDefault(size_t size, uint64_t attributes) { - note_attributes("XMemAllocDefault", attributes, size, _ReturnAddress()); + note_attributes("XMemAllocDefault", attributes, size, RT_CALLER()); return title_block(size); } void __stdcall XMemFreeDefault(void* p, uint64_t attributes) { - note_attributes("XMemFreeDefault", attributes, kNoSize, _ReturnAddress()); + note_attributes("XMemFreeDefault", attributes, kNoSize, RT_CALLER()); free_title_block(p); } @@ -1037,8 +1038,8 @@ void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULON void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) { drain_fault_notes(); - note_attributes("XMemVirtualAlloc", attributes, size, _ReturnAddress()); - void* result = xmem_virtual_alloc(address, size, allocation_type, attributes, protect, _ReturnAddress()); + note_attributes("XMemVirtualAlloc", attributes, size, RT_CALLER()); + void* result = xmem_virtual_alloc(address, size, allocation_type, attributes, protect, RT_CALLER()); // Diagnostic: the title's large regions (windows and placeholders log their own), so a fault left to the title can // be matched to the region it is in. static std::atomic shown{0}; @@ -1061,7 +1062,7 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, } if (result && allocation_type == 0x20402000) rt::xmem::note_stream_reservation(reinterpret_cast(result), size, - reinterpret_cast(_ReturnAddress()) - kTitleImage); + reinterpret_cast(RT_CALLER()) - kTitleImage); // A reservation: a GPU-only one (no CPU access, PAGE_GRAPHICS_* bits) is paired with the CPU-mappable one of the // same size made just before it (src/title_page_watch.h, title_gpu_views). const DWORD host_type = allocation_type & kXmemHostAllocationTypeMask; @@ -1069,7 +1070,7 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, const bool gpu_only = (protect & kPageGraphicsMask) && host_protect(protect) == PAGE_NOACCESS; const auto base = reinterpret_cast(result); const bool stream_queue_view = allocation_type == 0x20402000 && gpu_only && - reinterpret_cast(_ReturnAddress()) - kTitleImage == 0x1e1d03e && + reinterpret_cast(RT_CALLER()) - kTitleImage == 0x1e1d03e && rt::xmem::slot31_runs() && rt::xmem::queue_page_mappings_enabled(); if (leonida::title_gpu_views::note_reservation(base, size, gpu_only, stream_queue_view)) std::fprintf(stderr, "[rt] xmem: GPU-only view %p (%llu MiB, protect 0x%lx) paired with CPU view %p (%s)\n", @@ -2034,7 +2035,7 @@ void note_physical_attributes(uint64_t attributes, uint64_t count, const void* c // every page is 64 KiB, which all four callers' arithmetic agrees with. BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count, uint64_t* page_array) { drain_fault_notes(); - note_physical_attributes(attributes, page_count ? *page_count : 0, _ReturnAddress()); + note_physical_attributes(attributes, page_count ? *page_count : 0, RT_CALLER()); if (!page_count || (*page_count && !page_array)) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; @@ -2605,7 +2606,7 @@ BOOL WINAPI XMemTransferMemory(uint32_t type, SIZE_T size) { "\"api\":\"XMemTransferMemory\",\"type\":" + std::to_string(type) + ",\"size\":" + std::to_string(static_cast(size)) + ",\"caller\":" + rt::startup_trace::quote( - rt::startup_trace::where(reinterpret_cast(_ReturnAddress())))); + rt::startup_trace::where(reinterpret_cast(RT_CALLER())))); } } return TRUE; @@ -2727,7 +2728,7 @@ BOOL title_release(void* address, SIZE_T size, DWORD free_type, const void* call // The pages are freed with the GPU label regions locked (src/gpu_label_memory.h), so a completed label is never // stored into pages that are going away. -BOOL title_free_impl(LPVOID address, SIZE_T size, DWORD free_type) { +BOOL title_free_impl(LPVOID address, SIZE_T size, DWORD free_type, const void* caller) { drain_fault_notes(); const bool releases = (free_type & MEM_RELEASE) && !(free_type & (MEM_PRESERVE_PLACEHOLDER | MEM_COALESCE_PLACEHOLDERS)); const uintptr_t start = reinterpret_cast(address); @@ -2740,7 +2741,7 @@ BOOL title_free_impl(LPVOID address, SIZE_T size, DWORD free_type) { } BOOL result; if (releases) { - result = title_release(address, size, free_type, _ReturnAddress()); + result = title_release(address, size, free_type, caller); } else if (free_type & (MEM_PRESERVE_PLACEHOLDER | MEM_COALESCE_PLACEHOLDERS)) { // A split or a merge of placeholders, which may be the title's windows: the pages it touches are part way // through changing until it returns, so the fault handler waits for it as it waits for a remap of xmem's. @@ -2769,10 +2770,11 @@ BOOL title_free_impl(LPVOID address, SIZE_T size, DWORD free_type) { } BOOL WINAPI TitleVirtualFree(LPVOID address, SIZE_T size, DWORD free_type) { + const void* const caller = RT_CALLER(); // the shim's own frame: read before the lambda below DWORD saved = ERROR_SUCCESS; const bool ok = leonida::label::memory().release_pages( reinterpret_cast(address), size, (free_type & MEM_RELEASE) != 0, [&] { - const BOOL result = title_free_impl(address, size, free_type); + const BOOL result = title_free_impl(address, size, free_type, caller); saved = GetLastError(); return !!result; }); @@ -2780,11 +2782,12 @@ BOOL WINAPI TitleVirtualFree(LPVOID address, SIZE_T size, DWORD free_type) { return ok ? TRUE : FALSE; } BOOL WINAPI TitleVirtualFreeEx(HANDLE process,LPVOID address,SIZE_T size,DWORD flags) { + const void* const caller = RT_CALLER(); if(GetProcessId(process)!=GetCurrentProcessId())return ::VirtualFreeEx(process,address,size,flags); DWORD saved = ERROR_SUCCESS; const bool ok = leonida::label::memory().release_pages( reinterpret_cast(address), size, (flags & MEM_RELEASE) != 0, [&] { - const BOOL result = title_free_impl(address, size, flags); + const BOOL result = title_free_impl(address, size, flags, caller); saved = GetLastError(); return !!result; }); diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index ad17dd3b0d..bd5e3cf4da 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -191,6 +191,7 @@ void start_title_peek(std::uint8_t* base) { #include "thread_sampler.h" #include "title_page_watch.h" #include "title_geometry_watch.h" +#include "../shims/call_trace.h" #include "../shims/d3d12_trace.h" #include "../shims/d3d12_xs_device.h" #include "../shims/file_system.h" @@ -590,8 +591,12 @@ int wmain(int argc, wchar_t** argv) { } try { + // LEONIDA_CALL_TRACE= (shims/call_trace.h): created new before any module is mapped, so every import slot + // can get its thunk. Unset, nothing changes. + if (rt::call_trace::open_from_env() == rt::call_trace::OpenResult::Failed) return 2; rt::Loader loader(game_dir); rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code + rt::call_trace::set_main_module(main_module.base); // its caller field reads `game` // An executable with TLS that did not get index 0: its /GA code would read and write the TLS in slot 0, which // is gta6rt's own (or another executable's), so no code of it may run. const auto* main_nt = reinterpret_cast( diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 49588b4245..a391baa16f 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -17,6 +17,7 @@ #include #include +#include "../shims/call_trace.h" #include "../shims/shims.h" #include "../shims/startup_trace.h" #include "base_reservation.h" @@ -1774,6 +1775,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& std::unique_lock lock(ranges_mutex_); ranges_.push_back({reinterpret_cast(m->base), m->size, m->name}); } + if (call_trace::enabled()) call_trace::add_module(lower(m->name).c_str(), m->base, m->size); std::memcpy(m->base, file.data(), oh.SizeOfHeaders); auto* sec = IMAGE_FIRST_SECTION(nt); @@ -2281,8 +2283,21 @@ void Loader::bind_imports(Module& m) { } if (iat_rva < headers_end) throw std::runtime_error(m.name + ": an import address table lands in the headers"); - at(m.base, static_cast(iat_rva))->u1.Function = - reinterpret_cast(resolve(m, dll, name, ord, by_ord)); + void* bound = resolve(m, dll, name, ord, by_ord); + // LEONIDA_CALL_TRACE (shims/call_trace.h): the slot gets a thunk that records the call. An import bound to + // another title module is not traced and is named once; with the switch unset `bound` is stored as it is. + if (call_trace::enabled()) { + const ImportRecord& r = m.imports.back(); + if (r.binding == Binding::Module) { + call_trace::note_title_bound(dll.c_str()); + } else { + bound = call_trace::wrap(bound, dll.c_str(), r.name.c_str(), + r.binding == Binding::Shim ? call_trace::Bind::Shim + : r.binding == Binding::Host ? call_trace::Bind::Host + : call_trace::Bind::Unimpl); + } + } + at(m.base, static_cast(iat_rva))->u1.Function = reinterpret_cast(bound); if (delayed && startup_trace::enabled() && m.imports.back().binding == Binding::Unimplemented) startup_trace::event("delay_import_unimplemented", "\"module\":" + startup_trace::quote(m.name) + ",\"import\":" + diff --git a/runtime/test/call_trace_test.cpp b/runtime/test/call_trace_test.cpp new file mode 100644 index 0000000000..1e0de23f60 --- /dev/null +++ b/runtime/test/call_trace_test.cpp @@ -0,0 +1,795 @@ +// LEONIDA_CALL_TRACE (shims/call_trace.h): the thunks, the two common stubs, RT_CALLER and the writer, exercised with +// hand-written functions only. No game files, no GPU, no mapped image. +// +// One process-wide trace is opened in main(); each case calls its own sites ("ctt.dll!") and reads the file +// back, filtering by that name. The cases that end the process (TerminateProcess) or need another cap run in a child +// of this executable. Exits 0 when everything passed. +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "../shims/call_trace.h" + +namespace ct = rt::call_trace; + +namespace { + +int g_failures = 0; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + ++g_failures; \ + } \ + } while (0) + +// The same rules hash as leonida-hle asserts; tests/test_call_trace_rules.py recomputes it from the rules file and +// fails when the two differ, so a rule change shows up in both stacks. +constexpr const char kExpectedRulesHash[] = "873cd3bb78a70bc5"; + +std::wstring widen(const std::string& s) { return std::wstring(s.begin(), s.end()); } + +std::string slurp(const std::wstring& path) { + HANDLE h = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) return {}; + std::string out; + char buf[1 << 16]; + DWORD got = 0; + while (ReadFile(h, buf, sizeof buf, &got, nullptr) && got) out.append(buf, got); + CloseHandle(h); + return out; +} + +uint64_t file_size(const std::wstring& path) { + WIN32_FILE_ATTRIBUTE_DATA d{}; + if (!GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &d)) return 0; + return (static_cast(d.nFileSizeHigh) << 32) | d.nFileSizeLow; +} + +struct Rec { + uint64_t seq = 0; + uint32_t tid = 0; + char kind = 0; // T, C, R, E + std::vector f; +}; + +std::vector split(const std::string& s, char sep) { + std::vector out; + size_t at = 0; + for (;;) { + const size_t next = s.find(sep, at); + out.push_back(s.substr(at, next == std::string::npos ? std::string::npos : next - at)); + if (next == std::string::npos) break; + at = next + 1; + } + return out; +} + +struct Parsed { + std::vector comments; + std::vector bad; // lines that match no format + std::vector recs; + std::vector lines; + bool partial_tail = false; +}; + +// The trailing NULs of the last view and a partial last line are dropped, as call_trace_diff.py does. +Parsed parse(const std::wstring& path) { + Parsed p; + std::string text = slurp(path); + while (!text.empty() && text.back() == '\0') text.pop_back(); + if (!text.empty() && text.back() != '\n') { + p.partial_tail = true; + const size_t nl = text.rfind('\n'); + text.resize(nl == std::string::npos ? 0 : nl + 1); + } + static const std::regex header(R"(# leonida-call-trace 1 stack=gta6rt rules=[0-9a-f]{16})"); + static const std::regex bound(R"(# (title-bound [!-~]+|dropped [1-9]\d*))"); + static const std::regex where(R"((\?|[!-~]+\+0x[0-9a-f]+))"); + static const std::regex t_line(R"(\d+\t\d+\tT\t(main|\?|[a-z0-9_.\-]+\+0x[0-9a-f]+)\t\d+)"); + static const std::regex c_line( + R"(\d+\t\d+\t[CE]\t[a-z0-9_.\-]+![!-~]+\t(\?|[a-z0-9_.\-]+\+0x[0-9a-f]+)\t(shim|hle|host|unimpl))"); + static const std::regex r_line(R"(\d+\t\d+\tR\t\d+\t(hr:0x[0-9a-f]{8}|u:0x[0-9a-f]{8}|b:[01]|p:(0|1|-1)|-))"); + (void)where; + size_t at = 0; + while (at < text.size()) { + const size_t nl = text.find('\n', at); + const std::string line = text.substr(at, nl - at); + at = nl + 1; + p.lines.push_back(line); + if (line[0] == '#') { + p.comments.push_back(line); + if (!std::regex_match(line, header) && !std::regex_match(line, bound) && line != "# truncated") + p.bad.push_back(line); + continue; + } + Rec r; + r.f = split(line, '\t'); + const bool ok = r.f.size() >= 4 && ((r.f[2] == "T" && std::regex_match(line, t_line)) || + ((r.f[2] == "C" || r.f[2] == "E") && std::regex_match(line, c_line)) || + (r.f[2] == "R" && std::regex_match(line, r_line))); + if (!ok) { + p.bad.push_back(line); + continue; + } + r.seq = std::strtoull(r.f[0].c_str(), nullptr, 10); + r.tid = static_cast(std::strtoul(r.f[1].c_str(), nullptr, 10)); + r.kind = r.f[2][0]; + p.recs.push_back(std::move(r)); + } + return p; +} + +// The C and E records of one site, in file order. +std::vector calls_of(const Parsed& p, const std::string& site) { + std::vector out; + for (const Rec& r : p.recs) + if ((r.kind == 'C' || r.kind == 'E') && r.f[3] == site) out.push_back(r); + return out; +} +const Rec* ret_of(const Parsed& p, const Rec& call) { + for (const Rec& r : p.recs) + if (r.kind == 'R' && r.f[3] == std::to_string(call.seq)) return &r; + return nullptr; +} + +std::wstring g_trace; // the process-wide trace +uint64_t g_exe_base = 0; + +std::string game_caller(const void* ra) { + char b[48]; + std::snprintf(b, sizeof b, "game+0x%llx", static_cast(reinterpret_cast(ra) - g_exe_base)); + return b; +} + +template +F* traced(F* f, const char* sym, ct::Bind bind = ct::Bind::Shim) { + return reinterpret_cast(ct::wrap(reinterpret_cast(f), "ctt.dll", sym, bind)); +} +template +bool same_fn(F* a, F* b) { + return reinterpret_cast(a) == reinterpret_cast(b); +} + +// ---- the targets: plain functions, each its own site ------------------------------------------------------------ + +uint64_t __stdcall ints20(uint64_t a, uint64_t b, uint64_t c, uint64_t d, uint64_t e, uint64_t f, uint64_t g, uint64_t h, + uint64_t i, uint64_t j, uint64_t k, uint64_t l, uint64_t m, uint64_t n, uint64_t o, uint64_t p, + uint64_t q, uint64_t r, uint64_t s, uint64_t t) { + return a + 2 * b + 3 * c + 4 * d + 5 * e + 6 * f + 7 * g + 8 * h + 9 * i + 10 * j + 11 * k + 12 * l + 13 * m + + 14 * n + 15 * o + 16 * p + 17 * q + 18 * r + 19 * s + 20 * t; +} + +double __stdcall floats(double a, float b, double c, double d, double e, float f) { + return a + b * 2.0 + c * 3.0 + d * 4.0 + e * 5.0 + f * 6.0; +} +float __stdcall float_out(float a, float b) { return a * b + 0.25f; } + +struct Big { + uint64_t a, b, c; +}; +// A console method returning a struct by value: the hidden return pointer is in RCX and `this` in RDX, so `self` +// stands for `this` here and `x` is the first real argument. +Big __stdcall get_desc(void* self, uint64_t x) { + const uint64_t s = reinterpret_cast(self); + return Big{x, s, x ^ s}; +} + +DWORD g_error_seen = 0; +uint64_t __stdcall error_probe() { + g_error_seen = GetLastError(); + SetLastError(1234); + return 0; +} + +using ProbeFn = void(__stdcall*)(void**, void**); +void __stdcall caller_probe(void** raw, void** caller) { + *raw = _ReturnAddress(); + *caller = RT_CALLER(); +} +// One call instruction for every call through a pointer, so a direct call and a call through a thunk return to the +// same address. +__declspec(noinline) void invoke(ProbeFn f, void** raw, void** caller) { + f(raw, caller); + volatile int keep_the_return_here = 1; + (void)keep_the_return_here; +} + +void* __stdcall entry_probe() { return _ReturnAddress(); } +using EntryFn = void*(__stdcall*)(); +__declspec(noinline) void* invoke_entry(EntryFn f) { + void* r = f(); + volatile int keep_the_return_here = 1; + (void)keep_the_return_here; + return r; +} + +std::jmp_buf g_jump; +void __stdcall long_jumper() { std::longjmp(g_jump, 1); } +void __stdcall thrower() { throw 5; } +void __stdcall quiet() {} + +using VoidFn = void(__stdcall*)(); +VoidFn g_inner = nullptr; +void __stdcall outer() { g_inner(); } +void __stdcall inner() {} + +uint64_t __stdcall ret_all_ones() { return ~0ull; } +uint64_t __stdcall ret_low_ones() { return 0xffffffffull; } +uint64_t __stdcall ret_high_ones() { return 0xffffffff00000000ull; } +uint64_t __stdcall ret_zero() { return 0; } +uint64_t __stdcall ret_one() { return 77; } +uint64_t __stdcall ret_hr() { return 0xdeadbeef80004005ull; } // garbage above the HRESULT +uint64_t __stdcall ret_bool_true() { return 0xdeadbeef00000001ull; } +uint64_t __stdcall ret_bool_false() { return 0xdeadbeef12345600ull; } +uint64_t __stdcall ret_void() { return 0x1122334455667788ull; } +uint64_t __stdcall stress(uint64_t x) { return x + 1; } +uint64_t __stdcall kill_me() { TerminateProcess(GetCurrentProcess(), 7); return 0; } +uint64_t __stdcall before_kill(uint64_t x) { return x; } +int g_data = 5; + +// ---- cases ------------------------------------------------------------------------------------------------------- + +void case_rules() { + using namespace ct::detail; + CHECK(decide("kernel32.dll", "malloc").action == kSkip); + CHECK(decide("kernel32.dll", "__chkstk").action == kSkip); + CHECK(decide("api-ms-win-crt-string-l1-1-0.dll", "anything").action == kSkip); + CHECK(decide("kernel32.dll", "_setjmpex").action == kEntry); + CHECK(decide("api-ms-win-crt-stdio-l1-1-0.dll", "__stdio_common_vfprintf").action == kEntry); + CHECK(decide("kernel32.dll", "ExitProcess").action == kEntry); + CHECK(decide("kernel32.dll", "OutputDebugStringA").cls == kClsVoid); + CHECK(decide("xgameruntime.dll", "XUserIsStoreUser").cls == kClsBool); + CHECK(decide("xgameruntime.dll", "XGameRuntimeInitialize").cls == kClsHr); + CHECK(decide("xgameruntime.dll", "XUserAddAsync").cls == kClsHr); + CHECK(decide("xgameruntime.dll", "XUserCompare").cls == kClsP); // CT_NOT_HR beats CT_HR_MOD + CHECK(decide("d3d12.dll", "D3D12CreateDevice").cls == kClsHr); + CHECK(decide("other.dll", "D3D12CreateDevice").cls == kClsP); // CT_HR_MOD is per module + CHECK(decide("kernel32.dll", "CreateFileW").action == kWrap && decide("kernel32.dll", "CreateFileW").cls == kClsP); + CHECK(decide("kernel32.dll", "#12").action == kWrap); + // The ten probes both stacks classify the same way (agreed with the leonida-hle tests). + struct Probe { + const char* module; + const char* fn; + Action action; + Cls cls; + }; + const Probe probes[] = { + {"kernel32.dll", "EnterCriticalSection", kSkip, kClsP}, + {"api-ms-win-crt-string-l1-1-0.dll", "strcpy", kSkip, kClsP}, + {"ucrtbase.dll", "_setjmp", kEntry, kClsP}, + {"ucrtbase.dll", "snprintf", kEntry, kClsP}, + {"kernel32.dll", "ExitProcess", kEntry, kClsP}, + {"kernel32.dll", "WaitForSingleObject", kWrap, kClsVoid}, + {"xgameruntime.dll", "XTaskQueueDispatch", kWrap, kClsBool}, + {"xgameruntime.dll", "XUserAddAsync", kWrap, kClsHr}, + {"d3d12.dll", "D3D12CreateDevice", kWrap, kClsHr}, + {"xgameruntime.dll", "XUserCompare", kWrap, kClsP}, + }; + for (const Probe& pr : probes) { + const Decision d = decide(pr.module, pr.fn); + CHECK(d.action == pr.action && (pr.action != kWrap || d.cls == pr.cls)); + } + // Stack walks cannot have a wrap frame in front of them; SVML passes YMM arguments the stubs do not carry. + CHECK(decide("kernel32.dll", "RtlCaptureStackBackTrace").action == kEntry); + CHECK(decide("kernel32.dll", "RtlCaptureContext2").action == kEntry); + CHECK(decide("vcruntime140.dll", "__vdecl_sin2").action == kSkip); + CHECK(sizeof kRules / sizeof kRules[0] == 205); + char hash[24]; + std::snprintf(hash, sizeof hash, "%016llx", static_cast(rules_hash())); + CHECK(std::string(kExpectedRulesHash) == hash); +} + +void case_off() { + // Before open_from_env: the target comes back unchanged and RT_CALLER() is _ReturnAddress(). + CHECK(!ct::enabled()); + CHECK(ct::wrap(reinterpret_cast(&ints20), "ctt.dll", "ints20", ct::Bind::Shim) == + reinterpret_cast(&ints20)); + CHECK(ct::g_wrap_ret == nullptr); + void *raw = nullptr, *caller = nullptr; + invoke(&caller_probe, &raw, &caller); + CHECK(raw && raw == caller); + CHECK(ct::open_from_env() == ct::OpenResult::Off); // unset + SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE", L""); + CHECK(ct::open_from_env() == ct::OpenResult::Off); // empty + CHECK(!ct::enabled()); +} + +void case_refusals() { + // An existing file is refused and left as it was. + const std::wstring existing = g_trace + L".exists"; + HANDLE h = CreateFileW(existing.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + DWORD wrote = 0; + WriteFile(h, "keep", 4, &wrote, nullptr); + CloseHandle(h); + SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE", existing.c_str()); + CHECK(ct::open_from_env() == ct::OpenResult::Failed); + CHECK(slurp(existing) == "keep"); + CHECK(!ct::enabled()); + CHECK(ct::wrap(reinterpret_cast(&ints20), "ctt.dll", "ints20", ct::Bind::Shim) == + reinterpret_cast(&ints20)); + DeleteFileW(existing.c_str()); + // A cap that is not a whole number of MiB refuses before the file is created. + SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE", g_trace.c_str()); + SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE_MAX_MB", L"12x"); + CHECK(ct::open_from_env() == ct::OpenResult::Failed); + CHECK(GetFileAttributesW(g_trace.c_str()) == INVALID_FILE_ATTRIBUTES); + SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE_MAX_MB", nullptr); + // An unwritable place is refused too. + SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE", (g_trace + L"_no_dir\\x.txt").c_str()); + CHECK(ct::open_from_env() == ct::OpenResult::Failed); + SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE", g_trace.c_str()); +} + +void case_header_and_modules() { + const Parsed p = parse(g_trace); + CHECK(!p.comments.empty()); + if (!p.comments.empty()) { + CHECK(p.comments[0].rfind("# leonida-call-trace 1 stack=gta6rt rules=", 0) == 0); + CHECK(p.comments[0].substr(p.comments[0].size() - 16) == kExpectedRulesHash); + } + int bound = 0; + for (const std::string& c : p.comments) bound += c == "# title-bound foo.dll"; + CHECK(bound == 1); // named once, lower-cased + CHECK(ct::detail::g_stub && ct::g_wrap_ret == ct::detail::g_stub + 0x159); + // `jmp [r10]` (41 FF 22 at 0x7F) is not an epilogue the unwinder knows: the entry stub's function ends before it, + // so a stack walk there treats it as a leaf and finds the return address at [rsp]. + if (ct::detail::g_stub) { + DWORD64 base = 0; + PRUNTIME_FUNCTION f = RtlLookupFunctionEntry(reinterpret_cast(ct::detail::g_stub + 0x7E), &base, nullptr); + CHECK(f != nullptr && f->BeginAddress == 0 && f->EndAddress == 0x7F); + CHECK(RtlLookupFunctionEntry(reinterpret_cast(ct::detail::g_stub + 0x7F), &base, nullptr) == nullptr); + CHECK(RtlLookupFunctionEntry(reinterpret_cast(ct::detail::g_stub + 0x81), &base, nullptr) == nullptr); + CHECK(ct::detail::g_stub[0x7F] == 0x41 && ct::detail::g_stub[0x80] == 0xFF && ct::detail::g_stub[0x81] == 0x22); + PRUNTIME_FUNCTION w = RtlLookupFunctionEntry(reinterpret_cast(ct::g_wrap_ret), &base, nullptr); + CHECK(w != nullptr && w->BeginAddress == 0x90 && w->EndAddress == 0x19A); + } +} + +void case_ints() { + auto f = traced(&ints20, "ints20"); + CHECK(!same_fn(f, &ints20)); + const uint64_t want = ints20(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20); + const uint64_t got = f(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20); + CHECK(got == want); + const Parsed p = parse(g_trace); + const auto calls = calls_of(p, "ctt.dll!ints20"); + CHECK(calls.size() == 1 && calls[0].kind == 'C' && calls[0].f[5] == "shim"); + if (!calls.empty()) { + const Rec* r = ret_of(p, calls[0]); + CHECK(r && r->f[4] == "p:1" && r->seq > calls[0].seq); + CHECK(calls[0].f[4].rfind("game+0x", 0) == 0); + } +} + +void case_floats() { + auto f = traced(&floats, "floats"); + CHECK(f(1.5, 2.5f, 3.5, 4.5, 5.5, 6.5f) == floats(1.5, 2.5f, 3.5, 4.5, 5.5, 6.5f)); + auto g = traced(&float_out, "float_out"); + CHECK(g(3.0f, 4.0f) == float_out(3.0f, 4.0f)); +} + +void case_struct_return() { + auto f = traced(&get_desc, "get_desc"); + int self = 0; + const Big got = f(&self, 0x1234); + const Big want = get_desc(&self, 0x1234); + CHECK(got.a == want.a && got.b == want.b && got.c == want.c); + CHECK(got.a == 0x1234); +} + +void case_last_error() { + for (const char* sym : {"error_wrap", "exit"}) { // `exit` is an entry-only rule + auto f = traced(&error_probe, sym); + SetLastError(55); + g_error_seen = 0; + f(); + CHECK(GetLastError() == 1234); // the target's value survives the trace + CHECK(g_error_seen == 55); // and the target saw the caller's + } +} + +void case_caller() { + void *raw0 = nullptr, *caller0 = nullptr, *raw1 = nullptr, *caller1 = nullptr; + invoke(&caller_probe, &raw0, &caller0); + auto f = traced(&caller_probe, "caller_probe"); + invoke(f, &raw1, &caller1); + CHECK(raw0 == caller0); + CHECK(raw1 == ct::g_wrap_ret); // the shim is called by the wrap stub + CHECK(caller1 == raw0); // RT_CALLER() sees through it + const Parsed p = parse(g_trace); + const auto calls = calls_of(p, "ctt.dll!caller_probe"); + CHECK(calls.size() == 1 && calls[0].f[4] == game_caller(raw0)); +} + +void case_entry_only() { + void* direct = invoke_entry(&entry_probe); + auto f = traced(&entry_probe, "terminate"); // CT_ENTRY + void* through = invoke_entry(f); + CHECK(direct == through); // no frame between the title and the target + auto g = traced(&entry_probe, "unimpl_probe", ct::Bind::Unimpl); + CHECK(invoke_entry(g) == direct); + const Parsed p = parse(g_trace); + const auto e = calls_of(p, "ctt.dll!terminate"); + CHECK(e.size() == 1 && e[0].kind == 'E' && e[0].f[5] == "shim" && e[0].f[4] == game_caller(direct)); + CHECK(e.empty() || ret_of(p, e[0]) == nullptr); + const auto u = calls_of(p, "ctt.dll!unimpl_probe"); + CHECK(u.size() == 1 && u[0].kind == 'E' && u[0].f[5] == "unimpl"); +} + +// Kept apart from anything with a destructor or a handler: setjmp and C++ unwinding do not mix in one frame. +#pragma warning(push) +#pragma warning(disable : 4611) // setjmp under /EHsc: nothing here has a destructor +__declspec(noinline) int jump_past(VoidFn f) { + volatile int jumped = 0; + if (setjmp(g_jump) == 0) { + f(); + jumped = 2; + } else { + jumped = 1; + } + return jumped; +} +#pragma warning(pop) +__declspec(noinline) int throw_through(VoidFn f) { + try { + f(); + } catch (int v) { + return v; + } + return 0; +} + +void case_jump_and_throw() { + auto ok = traced(&quiet, "after_jump"); + CHECK(jump_past(traced(&long_jumper, "long_jumper")) == 1); + ok(); + CHECK(throw_through(traced(&thrower, "thrower")) == 5); + ok(); + const Parsed p = parse(g_trace); + for (const char* name : {"ctt.dll!long_jumper", "ctt.dll!thrower"}) { + const auto c = calls_of(p, name); + CHECK(c.size() == 1 && c[0].kind == 'C' && ret_of(p, c[0]) == nullptr); // a C without an R + } + const auto a = calls_of(p, "ctt.dll!after_jump"); + CHECK(a.size() == 2); + for (const Rec& c : a) CHECK(ret_of(p, c) != nullptr); +} + +void case_nested() { + g_inner = traced(&inner, "nested_inner"); + auto o = traced(&outer, "nested_outer"); + o(); + const Parsed p = parse(g_trace); + const auto co = calls_of(p, "ctt.dll!nested_outer"); + const auto ci = calls_of(p, "ctt.dll!nested_inner"); + CHECK(co.size() == 1 && ci.size() == 1); + if (co.size() != 1 || ci.size() != 1) return; + const Rec* ro = ret_of(p, co[0]); + const Rec* ri = ret_of(p, ci[0]); + CHECK(ro && ri); + if (!ro || !ri) return; + CHECK(co[0].seq < ci[0].seq && ci[0].seq < ri->seq && ri->seq < ro->seq); // C C R R + CHECK(ri->f[3] == std::to_string(ci[0].seq) && ro->f[3] == std::to_string(co[0].seq)); +} + +void case_unchanged_returns() { + void* f = reinterpret_cast(&quiet); + CHECK(ct::wrap(f, "ctt.dll", "malloc", ct::Bind::Host) == f); // CT_SKIP + CHECK(ct::wrap(f, "ctt.dll", "my_chkstk_thing", ct::Bind::Host) == f); // CT_SKIP_HAS + CHECK(ct::wrap(f, "API-MS-WIN-CRT-STRING-L1-1-0.dll", "whatever", ct::Bind::Host) == f); // CT_SKIP_MODULE + CHECK(ct::wrap(&g_data, "ctt.dll", "data_import", ct::Bind::Host) == static_cast(&g_data)); // data + CHECK(ct::wrap(nullptr, "ctt.dll", "null_import", ct::Bind::Host) == nullptr); + const Parsed p = parse(g_trace); + CHECK(calls_of(p, "ctt.dll!malloc").empty() && calls_of(p, "ctt.dll!data_import").empty()); +} + +void case_classes() { + struct Row { + uint64_t (__stdcall* fn)(); + const char* sym; + const char* want; + }; + const Row rows[] = { + {&ret_all_ones, "cls_all_ones", "p:-1"}, {&ret_low_ones, "cls_low_ones", "p:-1"}, + {&ret_high_ones, "cls_high_ones", "p:1"}, {&ret_zero, "cls_zero", "p:0"}, + {&ret_one, "cls_one", "p:1"}, {&ret_hr, "XGameRuntimeInitialize", "hr:0x80004005"}, + {&ret_bool_true, "XUserIsStoreUser", "b:1"}, {&ret_bool_false, "XStoreIsLicenseValid", "b:0"}, + {&ret_void, "OutputDebugStringA", "-"}, + }; + for (const Row& row : rows) traced(row.fn, row.sym)(); + const Parsed p = parse(g_trace); + for (const Row& row : rows) { + const auto c = calls_of(p, std::string("ctt.dll!") + row.sym); + CHECK(c.size() == 1); + if (c.size() != 1) continue; + const Rec* r = ret_of(p, c[0]); + CHECK(r && r->f[4] == row.want); + if (r && r->f[4] != row.want) std::printf(" %s: %s, wanted %s\n", row.sym, r->f[4].c_str(), row.want); + } +} + +HANDLE g_start = nullptr; // workers wait for it, so they are all running before any records +HANDLE g_release = nullptr; // and for this one after they have recorded, so no thread id is reused +volatile LONG g_recorded = 0; + +DWORD WINAPI worker(void* p) { + auto f = reinterpret_cast(p); + WaitForSingleObject(g_start, INFINITE); + uint64_t sum = 0; + for (uint64_t i = 0; i < 20000; ++i) sum += f(i); + InterlockedIncrement(&g_recorded); + WaitForSingleObject(g_release, INFINITE); + return sum == 20000ull * 20001 / 2 ? 0 : 1; +} + +uint64_t __stdcall bulk_target(uint64_t x) { return x * 3; } + +// 400 distinct sites need more than one 64 KiB pool of Sites (341 each). +void case_many_sites() { + constexpr int kSites = 400; + std::vector fns; + for (int i = 0; i < kSites; ++i) fns.push_back(traced(&bulk_target, ("bulk" + std::to_string(i)).c_str())); + for (int i = 0; i < kSites; ++i) CHECK(fns[static_cast(i)](static_cast(i)) == 3ull * static_cast(i)); + const Parsed p = parse(g_trace); + CHECK(p.bad.empty()); + int found = 0; + for (const Rec& r : p.recs) + if (r.kind == 'C' && r.f[3].rfind("ctt.dll!bulk", 0) == 0) ++found; + CHECK(found == kSites); + for (int i : {0, 340, 341, 399}) { + const auto c = calls_of(p, "ctt.dll!bulk" + std::to_string(i)); + CHECK(c.size() == 1 && ret_of(p, c[0]) != nullptr); + } +} + +// The writer lock is taken with a bound: a record that cannot get it is dropped after about 10 ms, and the next one +// that does says so. +struct LockHolder { + HANDLE locked; + HANDLE release; +}; +DWORD WINAPI hold_writer_lock(void* p) { + auto* h = static_cast(p); + AcquireSRWLockExclusive(&ct::detail::g_lock); + SetEvent(h->locked); + WaitForSingleObject(h->release, INFINITE); + ReleaseSRWLockExclusive(&ct::detail::g_lock); + return 0; +} + +void case_dropped_record() { + LockHolder h{CreateEventW(nullptr, TRUE, FALSE, nullptr), CreateEventW(nullptr, TRUE, FALSE, nullptr)}; + HANDLE t = CreateThread(nullptr, 0, hold_writer_lock, &h, 0, nullptr); + WaitForSingleObject(h.locked, INFINITE); + auto f = traced(&stress, "dropped_probe"); + LARGE_INTEGER freq, a, b; + QueryPerformanceFrequency(&freq); + QueryPerformanceCounter(&a); + const uint64_t got = f(41); + QueryPerformanceCounter(&b); + CHECK(got == 42); // the call itself went through + const double ms = 1000.0 * static_cast(b.QuadPart - a.QuadPart) / static_cast(freq.QuadPart); + CHECK(ms < 100.0); + if (ms >= 100.0) std::printf(" the dropped call took %.1f ms\n", ms); + SetEvent(h.release); + WaitForSingleObject(t, INFINITE); + CloseHandle(t); + CloseHandle(h.locked); + CloseHandle(h.release); + CHECK(ct::detail::g_dropped.load() == 1); + CHECK(f(1) == 2); + const Parsed p = parse(g_trace); + CHECK(p.bad.empty()); + int dropped_line = -1, call_line = -1, calls = 0; + for (size_t i = 0; i < p.lines.size(); ++i) { + if (p.lines[i] == "# dropped 1") dropped_line = static_cast(i); + if (p.lines[i].find("ctt.dll!dropped_probe") != std::string::npos) { + call_line = static_cast(i); + ++calls; + } + } + CHECK(calls == 1); // the first call left no C and no R + CHECK(dropped_line >= 0 && call_line > dropped_line); + const auto c = calls_of(p, "ctt.dll!dropped_probe"); + CHECK(c.size() == 1 && ret_of(p, c[0]) != nullptr); +} + +void case_threads() { + constexpr int kThreads = 4; + auto f = traced(&stress, "stress"); + HANDLE h[kThreads]; + g_start = CreateEventW(nullptr, TRUE, FALSE, nullptr); + g_release = CreateEventW(nullptr, TRUE, FALSE, nullptr); + g_recorded = 0; + for (HANDLE& t : h) t = CreateThread(nullptr, 0, worker, reinterpret_cast(f), 0, nullptr); + SetEvent(g_start); + for (int waited = 0; g_recorded < kThreads && waited < 120000; waited += 5) Sleep(5); + CHECK(g_recorded == kThreads); + SetEvent(g_release); + for (HANDLE t : h) { + WaitForSingleObject(t, INFINITE); + DWORD code = 99; + GetExitCodeThread(t, &code); + CHECK(code == 0); + CloseHandle(t); + } + CloseHandle(g_start); + CloseHandle(g_release); + CHECK(file_size(g_trace) >= 2 * ct::detail::kViewBytes); // the lines crossed a view boundary + const Parsed p = parse(g_trace); + CHECK(p.bad.empty()); + if (!p.bad.empty()) std::printf(" first bad line: %s\n", p.bad[0].c_str()); + uint64_t last = 0; + bool increasing = true; + for (const Rec& r : p.recs) { + if (r.seq <= last) increasing = false; + last = r.seq; + } + CHECK(increasing); + const auto c = calls_of(p, "ctt.dll!stress"); + CHECK(c.size() == static_cast(kThreads) * 20000); + std::vector tids; + for (const Rec& r : c) + if (std::find(tids.begin(), tids.end(), r.tid) == tids.end()) tids.push_back(r.tid); + CHECK(tids.size() == kThreads); + for (uint32_t tid : tids) { + int t_lines = 0; + for (const Rec& r : p.recs) t_lines += r.kind == 'T' && r.tid == tid; + CHECK(t_lines == 1); + } + size_t returns = 0; + for (const Rec& r : p.recs) returns += r.kind == 'R'; + CHECK(returns >= c.size()); +} + +void case_main_thread() { + const Parsed p = parse(g_trace); + const DWORD tid = GetCurrentThreadId(); + int t_lines = 0; + for (const Rec& r : p.recs) + if (r.kind == 'T' && r.tid == tid) { + ++t_lines; + CHECK(r.f[3] == "main"); + } + CHECK(t_lines == 1); +} + +// ---- children ---------------------------------------------------------------------------------------------------- + +DWORD run_child(const std::wstring& mode, const std::wstring& path, bool* started) { + wchar_t exe[MAX_PATH]; + GetModuleFileNameW(nullptr, exe, MAX_PATH); + std::wstring cmd = L"\"" + std::wstring(exe) + L"\" " + mode + L" \"" + path + L"\""; + STARTUPINFOW si{}; + si.cb = sizeof si; + PROCESS_INFORMATION pi{}; + *started = CreateProcessW(exe, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi) != 0; + if (!*started) return 99; + WaitForSingleObject(pi.hProcess, 120000); + DWORD code = 98; + GetExitCodeProcess(pi.hProcess, &code); + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + return code; +} + +void case_killed_child() { + const std::wstring path = g_trace + L".kill"; + DeleteFileW(path.c_str()); + bool started = false; + const DWORD code = run_child(L"--child-kill", path, &started); + CHECK(started && code == 7); + const Parsed p = parse(path); + CHECK(p.bad.empty()); + const auto before = calls_of(p, "ctt.dll!before_kill"); + CHECK(before.size() == 3); + for (const Rec& c : before) CHECK(ret_of(p, c) != nullptr); + const auto kill = calls_of(p, "ctt.dll!kill_me"); + CHECK(kill.size() == 1 && ret_of(p, kill[0]) == nullptr); + CHECK(!p.recs.empty() && p.recs.back().kind == 'C' && p.recs.back().f[3] == "ctt.dll!kill_me"); // the open C is last + DeleteFileW(path.c_str()); +} + +void case_capped_child() { + const std::wstring path = g_trace + L".cap"; + DeleteFileW(path.c_str()); + bool started = false; + const DWORD code = run_child(L"--child-cap", path, &started); + CHECK(started && code == 0); + const Parsed p = parse(path); + CHECK(p.bad.empty()); + CHECK(!p.lines.empty() && p.lines.back() == "# truncated"); + size_t truncated = 0; + for (const std::string& l : p.lines) truncated += l == "# truncated"; + CHECK(truncated == 1); + size_t bytes = 0; + for (const std::string& l : p.lines) bytes += l.size() + 1; + CHECK(bytes <= (size_t{1} << 20)); + DeleteFileW(path.c_str()); +} + +int child_main(const std::wstring& mode, const std::wstring& path) { + SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE", path.c_str()); + const bool cap = mode == L"--child-cap"; + if (cap) SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE_MAX_MB", L"1"); + if (ct::open_from_env() != ct::OpenResult::On) return 3; + if (cap) { // far more than 1 MiB of lines: the file ends in `# truncated` and the calls keep working + auto f = traced(&stress, "stress"); + for (uint64_t i = 0; i < 40000; ++i) + if (f(i) != i + 1) return 4; + if (ct::enabled()) return 5; // the cap was reached + void* late = ct::wrap(reinterpret_cast(&stress), "ctt.dll", "after_cap", ct::Bind::Shim); + if (late != reinterpret_cast(&stress)) return 6; // no new thunk once recording has stopped + if (f(5) != 6) return 7; // an old one still forwards + return 0; + } + auto b = traced(&before_kill, "before_kill"); + for (uint64_t i = 0; i < 3; ++i) b(i); + traced(&kill_me, "kill_me")(); + return 5; // not reached +} + +} // namespace + +int wmain(int argc, wchar_t** argv) { + if (argc == 3 && (std::wstring(argv[1]) == L"--child-kill" || std::wstring(argv[1]) == L"--child-cap")) + return child_main(argv[1], argv[2]); + + wchar_t temp[MAX_PATH]; + GetTempPathW(MAX_PATH, temp); + g_trace = std::wstring(temp) + L"leonida_call_trace_test_" + std::to_wstring(GetCurrentProcessId()) + L".txt"; + DeleteFileW(g_trace.c_str()); + SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE", nullptr); + SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE_MAX_MB", nullptr); + + auto* dos = reinterpret_cast(GetModuleHandleW(nullptr)); + auto* nt = reinterpret_cast(reinterpret_cast(dos) + dos->e_lfanew); + g_exe_base = reinterpret_cast(dos); + + case_rules(); + case_off(); + case_refusals(); + + CHECK(ct::open_from_env() == ct::OpenResult::On); + if (!ct::enabled()) { + std::printf("FAIL: the trace did not open; stopping\n"); + return 1; + } + ct::add_module("CTT.EXE", dos, nt->OptionalHeader.SizeOfImage); + ct::set_main_module(dos); + ct::note_title_bound("Foo.DLL"); + ct::note_title_bound("foo.dll"); + ct::mark_main_thread(); + + case_header_and_modules(); + case_ints(); + case_floats(); + case_struct_return(); + case_last_error(); + case_caller(); + case_entry_only(); + case_jump_and_throw(); + case_nested(); + case_unchanged_returns(); + case_classes(); + case_many_sites(); + case_dropped_record(); + case_threads(); + case_main_thread(); + case_killed_child(); + case_capped_child(); + + if (g_failures == 0) DeleteFileW(g_trace.c_str()); + else std::printf("trace kept at %ls\n", g_trace.c_str()); + std::printf(g_failures ? "call_trace_test: %d failure(s)\n" : "call_trace_test: ok\n", g_failures); + return g_failures ? 1 : 0; +} diff --git a/tests/test_call_trace_diff.py b/tests/test_call_trace_diff.py new file mode 100644 index 0000000000..a2a1101d50 --- /dev/null +++ b/tests/test_call_trace_diff.py @@ -0,0 +1,986 @@ +"""Tests for tools/call_trace_diff.py. + + python -I tests/test_call_trace_diff.py + +Every trace here is written by the test; no game data and no fixture file is used. +""" +import json +import os +import subprocess +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOL = os.path.join(ROOT, "tools", "call_trace_diff.py") +sys.path.insert(0, os.path.join(ROOT, "tools")) + +import call_trace_diff # noqa: E402 + +RULES = "0123456789abcdef" +CALLER = "game+0x10" + + +class Tr: + """Builds a version 1 trace; every record takes the next seq, as the writer does.""" + + def __init__(self, stack=None, rules=RULES, header=True, extra_lines=()): + self.seq = 0 + self.lines = [] + self.threads = set() + if header: + self.lines.append("# leonida-call-trace 1" + (" stack=%s" % stack if stack else "") + + (" rules=%s" % rules if rules else "")) + self.lines.extend(extra_lines) + + def raw(self, line): + self.lines.append(line) + return self + + def _emit(self, *fields): + self.seq += 1 + self.lines.append("\t".join([str(self.seq)] + [str(f) for f in fields])) + return self.seq + + def thread(self, tid, start="main", created=None): + self.threads.add(tid) + return self._emit(tid, "T", start, 1000 + tid if created is None else created) + + def _ensure(self, tid): + if tid not in self.threads: + self.thread(tid, "main" if tid == 1 else "game+0x%x" % (0x1000 * tid)) + + def enter(self, tid, call, caller=CALLER, bind="shim"): + self._ensure(tid) + return self._emit(tid, "C", call, caller, bind) + + def leave(self, tid, call_seq, ret="-"): + return self._emit(tid, "R", call_seq, ret) + + def call(self, tid, call, ret="-", caller=CALLER, bind="shim"): + seq = self.enter(tid, call, caller, bind) + self.leave(tid, seq, ret) + return seq + + def entry(self, tid, call, caller=CALLER, bind="shim"): + self._ensure(tid) + return self._emit(tid, "E", call, caller, bind) + + def text(self, trailer=""): + return "\n".join(self.lines) + "\n" + trailer + + +def mk(*specs, tid=1, **kwargs): + """A trace of calls on one thread; a spec is a call name or (call, ret[, caller]). The n-th call has seq 2n+2.""" + tr = Tr(**kwargs) + for spec in specs: + if isinstance(spec, str): + spec = (spec,) + tr.call(tid, *spec) + return tr.text() + + +def seq_of(index): + return 2 * index + 2 + + +class TraceDiffCase(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.dir = self._tmp.name + + def write(self, name, text): + path = os.path.join(self.dir, name) + with open(path, "w", encoding="utf-8", newline="\n") as handle: + handle.write(text) + return path + + def run_tool(self, left, right, *args): + a = self.write("left.trace", left) + b = self.write("right.trace", right) + proc = subprocess.run([sys.executable, "-I", TOOL, a, b, *args], capture_output=True, text=True, + encoding="utf-8") + return proc + + def run_json(self, left, right, *args): + proc = self.run_tool(left, right, "--json", *args) + self.assertIn(proc.returncode, (0, 1), proc.stderr) + return proc.returncode, json.loads(proc.stdout) + + def kinds(self, data): + return [(d["kind"], d["left_seq"], d["right_seq"]) for d in data["divergences"]["shown"]] + + +BASE = [("kernel32!CreateFileW", "p:1"), + ("d3d12!D3D12CreateDevice", "hr:0x00000000"), + ("kernel32!CloseHandle", "u:0x1")] + + +class DiffTests(TraceDiffCase): + def test_identical_traces(self): + proc = self.run_tool(mk(*BASE, stack="gta6rt"), mk(*BASE, stack="leonida-hle")) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn("left: gta6rt", proc.stdout) + self.assertIn("right: leonida-hle", proc.stdout) + self.assertIn("records=3 threads=1", proc.stdout) + self.assertIn("divergences: 0", proc.stdout) + self.assertIn("Open calls at end of trace: 0", proc.stdout) + self.assertNotIn("kind=", proc.stdout) + self.assertNotIn("WARNING", proc.stdout) + + def test_label_falls_back_to_file_name(self): + proc = self.run_tool(mk(*BASE), mk(*BASE)) + self.assertIn("left: left.trace", proc.stdout) + + def test_missing_header_is_accepted(self): + proc = self.run_tool(mk(*BASE, header=False), mk(*BASE)) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn("rules=-", proc.stdout) + self.assertIn("WARNING: left.trace: no leonida-call-trace header", proc.stdout) + self.assertNotIn("right.trace: no leonida-call-trace header", proc.stdout) + rc, data = self.run_json(mk(*BASE, header=False), mk(*BASE)) + self.assertEqual((data["left"]["header"], data["right"]["header"]), (False, True)) + self.assertNotIn("no leonida-call-trace header", self.run_tool(mk(*BASE), mk(*BASE)).stdout) + + def test_extra_call_on_left(self): + left = mk(BASE[0], BASE[1], "kernel32!Sleep", BASE[2]) + rc, data = self.run_json(left, mk(*BASE)) + self.assertEqual(rc, 1) + self.assertEqual(self.kinds(data), [("only-left", seq_of(2), None)]) + self.assertEqual(data["divergences"]["shown"][0]["call"], "kernel32!Sleep") + proc = self.run_tool(left, mk(*BASE)) + self.assertIn("kind=only-left left_seq=%d right_seq=- call=kernel32!Sleep caller=game+0x10 bind=shim" + % seq_of(2), proc.stdout) + + def test_extra_calls_on_right_run(self): + right = mk(BASE[0], "kernel32!Sleep", "kernel32!Sleep", *BASE[1:]) + rc, data = self.run_json(mk(*BASE), right) + self.assertEqual(rc, 1) + self.assertEqual(self.kinds(data), [("only-right", None, seq_of(1))]) + shown = data["divergences"]["shown"][0] + self.assertEqual((shown["calls"], shown["last_seq"]), (2, seq_of(2))) + + def test_different_hresult(self): + right = mk(BASE[0], ("d3d12!D3D12CreateDevice", "hr:0x80004005"), BASE[2]) + rc, data = self.run_json(mk(*BASE), right) + self.assertEqual(rc, 1) + shown = data["divergences"]["shown"] + self.assertEqual([(d["kind"], d["left"], d["right"]) for d in shown], + [("ret", "hr:0x00000000", "hr:0x80004005")]) + proc = self.run_tool(mk(*BASE), right) + self.assertIn("left=hr:0x00000000 right=hr:0x80004005", proc.stdout) + + def test_pointer_null_vs_non_null(self): + left = mk(("kernel32!GetModuleHandleW", "p:1"), ("kernel32!LoadLibraryW", "p:1")) + right = mk(("kernel32!GetModuleHandleW", "p:0"), ("kernel32!LoadLibraryW", "p:1")) + rc, data = self.run_json(left, right) + self.assertEqual(rc, 1) + self.assertEqual([(d["kind"], d["call"]) for d in data["divergences"]["shown"]], + [("ret", "kernel32!GetModuleHandleW")]) + + def test_pointer_values_are_only_null_or_not(self): + self.assertEqual(self.run_tool(mk(("kernel32!HeapAlloc", "p:1")), mk(("kernel32!HeapAlloc", "p:1"))).returncode, 0) + + def test_all_ones_pointer_differs_from_non_null(self): + left = mk(("kernel32!CreateFileW", "p:-1")) + right = mk(("kernel32!CreateFileW", "p:1")) + rc, data = self.run_json(left, right) + self.assertEqual(rc, 1) + shown = data["divergences"]["shown"] + self.assertEqual([(d["kind"], d["left"], d["right"]) for d in shown], [("ret", "p:-1", "p:1")]) + self.assertEqual(self.run_tool(left, mk(("kernel32!CreateFileW", "p:-1"))).returncode, 0) + + def test_bool_zero_vs_one(self): + left = mk(("kernel32!CloseHandle", "b:0"), ("kernel32!SetEvent", "b:1")) + right = mk(("kernel32!CloseHandle", "b:1"), ("kernel32!SetEvent", "b:1")) + rc, data = self.run_json(left, right) + self.assertEqual(rc, 1) + shown = data["divergences"]["shown"] + self.assertEqual([(d["kind"], d["call"], d["left"], d["right"]) for d in shown], + [("ret", "kernel32!CloseHandle", "b:0", "b:1")]) + + def test_dash_is_never_compared(self): + left = mk(("kernel32!Sleep", "-"), ("kernel32!A", "hr:0x00000000")) + right = mk(("kernel32!Sleep", "hr:0x80004005"), ("kernel32!A", "-")) + self.assertEqual(self.run_tool(left, right).returncode, 0) + + def test_different_kinds_that_are_both_comparable_differ(self): + rc, data = self.run_json(mk(("kernel32!X", "hr:0x00000000")), mk(("kernel32!X", "u:0x0"))) + self.assertEqual((rc, self.kinds(data)), (1, [("ret", 2, 2)])) + rc, data = self.run_json(mk(("kernel32!X", "b:0")), mk(("kernel32!X", "p:0"))) + self.assertEqual((rc, self.kinds(data)), (1, [("ret", 2, 2)])) + + def test_ignore_ret(self): + left = mk(*BASE) + right = mk(BASE[0], ("d3d12!D3D12CreateDevice", "hr:0x80004005"), BASE[2]) + self.assertEqual(self.run_tool(left, right).returncode, 1) + proc = self.run_tool(left, right, "--ignore-ret", "D3D12!D3D12CreateDevice") + self.assertEqual(proc.returncode, 0, proc.stdout) + proc = self.run_tool(left, right, "--ignore-ret", "d3d12!Other", "--ignore-ret", "d3d12!D3D12CreateDevice") + self.assertEqual(proc.returncode, 0, proc.stdout) + proc = self.run_tool(left, right, "--ignore-ret", "d3d12!d3d12createdevice") + self.assertEqual(proc.returncode, 1) # the function name is case-sensitive + + def test_ignore_ret_needs_module_and_function(self): + self.assertEqual(self.run_tool(mk(*BASE), mk(*BASE), "--ignore-ret", "Sleep").returncode, 2) + + def test_bind_is_shown_but_not_part_of_identity(self): + left, right = Tr(), Tr() + left.call(1, "kernel32!A", "u:0x1", bind="shim") + left.call(1, "kernel32!B", "-", bind="shim") + right.call(1, "kernel32!A", "u:0x2", bind="hle") + right.call(1, "kernel32!B", "-", bind="host") + rc, data = self.run_json(left.text(), right.text()) + self.assertEqual((rc, self.kinds(data)), (1, [("ret", 2, 2)])) + shown = data["divergences"]["shown"][0] + self.assertEqual((shown["left_bind"], shown["right_bind"]), ("shim", "hle")) + proc = self.run_tool(left.text(), right.text()) + self.assertIn("left=u:0x1 right=u:0x2 left_bind=shim right_bind=hle", proc.stdout) + + def test_count_summary(self): + left = mk(*["kernel32!Sleep"] * 5, "kernel32!Other") + right = mk(*["kernel32!Sleep"] * 2, "kernel32!Other") + rc, data = self.run_json(left, right) + self.assertEqual(rc, 1) + self.assertEqual(data["counts"]["shown"], + [{"thread": "main", "call": "kernel32!Sleep", "left": 5, "right": 2, "delta": -3}]) + self.assertEqual([d["kind"] for d in data["divergences"]["shown"]], ["only-left"]) + self.assertEqual(data["divergences"]["shown"][0]["calls"], 3) + + def test_thread_interleaving_is_not_a_divergence(self): + left, right = Tr(), Tr() + left.thread(1, "main") + left.thread(2, "game+0x2000") + for name, tid in (("A", 1), ("B", 2), ("C", 1), ("D", 2)): + left.call(tid, "kernel32!" + name) + right.thread(7, "game+0x2000") + right.thread(8, "main") + right.call(7, "kernel32!B") + right.call(7, "kernel32!D") + right.call(8, "kernel32!A") + right.call(8, "kernel32!C") + proc = self.run_tool(left.text(), right.text()) + self.assertEqual(proc.returncode, 0, proc.stdout) + self.assertIn("threads=2", proc.stdout) + + def test_order_inside_a_thread_still_matters(self): + self.assertEqual(self.run_tool(mk("kernel32!A", "kernel32!B"), mk("kernel32!B", "kernel32!A")).returncode, 1) + + def test_thread_on_one_side_only(self): + left, right = Tr(), Tr() + left.call(1, "kernel32!A") + left.thread(9, "game+0x900") + left.call(9, "kernel32!B") + left.call(9, "kernel32!C") + right.call(1, "kernel32!A") + right.thread(7, "game+0x700") + right.call(7, "kernel32!B") + rc, data = self.run_json(left.text(), right.text()) + self.assertEqual(rc, 1) + self.assertEqual(data["threads_only"], [{"thread": "game+0x700#1", "side": "right", "calls": 1}, + {"thread": "game+0x900#1", "side": "left", "calls": 2}]) + self.assertEqual(data["divergences"]["total"], 0) + proc = self.run_tool(left.text(), right.text()) + self.assertIn("thread=game+0x900#1 only-left calls=2", proc.stdout) + self.assertIn("thread=game+0x700#1 only-right calls=1", proc.stdout) + + def test_extra_worker_with_the_same_start_is_thread_only(self): + left, right = Tr(), Tr() + for tid in (2, 3): + left.thread(tid, "game+0x500", created=100 * tid) + left.call(tid, "kernel32!W") + right.thread(9, "game+0x500", created=5) + right.call(9, "kernel32!W") + rc, data = self.run_json(left.text(), right.text()) + self.assertEqual(rc, 1) + self.assertEqual(data["threads_only"], [{"thread": "game+0x500#2", "side": "left", "calls": 1}]) + self.assertEqual(data["divergences"]["total"], 0) + + def test_thread_option_limits_comparison(self): + left, right = Tr(), Tr() + for tr, name in ((left, "B"), (right, "Z")): + tr.call(1, "kernel32!A") + tr.thread(2, "game+0x100") + tr.call(2, "kernel32!" + name) + self.assertEqual(self.run_tool(left.text(), right.text()).returncode, 1) + self.assertEqual(self.run_tool(left.text(), right.text(), "--thread", "main").returncode, 0) + self.assertEqual(self.run_tool(left.text(), right.text(), "--thread", "game+0x100").returncode, 1) + self.assertEqual(self.run_tool(left.text(), right.text(), "--thread", "game+0x100#1").returncode, 1) + self.assertEqual(self.run_tool(left.text(), right.text(), "--thread", "game+0x100#2").returncode, 2) + self.assertEqual(self.run_tool(left.text(), right.text(), "--thread", "nope").returncode, 2) + + def test_thread_selector_is_normalised_like_the_starts(self): + left, right = Tr(), Tr() + for tr, name in ((left, "B"), (right, "Z")): + tr.thread(2, "Game+0x1A") + tr.call(2, "kernel32!" + name) + for selector in ("game+0x01A", "GAME+0x1a#1", "game+0x1a"): + with self.subTest(selector): + self.assertEqual(self.run_tool(left.text(), right.text(), "--thread", selector).returncode, 1) + self.assertEqual(self.run_tool(left.text(), right.text(), "--thread", "game+0x1b").returncode, 2) + + def test_module_and_caller_module_are_case_insensitive(self): + left = mk(("KERNEL32.dll!Sleep", "-", "Game+0x1A")) + right = mk(("kernel32.DLL!Sleep", "-", "GAME+0x1a")) + self.assertEqual(self.run_tool(left, right).returncode, 0) + + def test_function_is_case_sensitive(self): + self.assertEqual(self.run_tool(mk("kernel32!Sleep"), mk("kernel32!sleep")).returncode, 1) + + def test_ordinal_function_name(self): + self.assertEqual(self.run_tool(mk("ws2_32.dll!#115"), mk("ws2_32.dll!#115")).returncode, 0) + + def test_caller_offset_differs(self): + left = mk(("kernel32!Sleep", "-", "game+0x10")) + right = mk(("kernel32!Sleep", "-", "game+0x20")) + rc, data = self.run_json(left, right) + self.assertEqual((rc, [d["kind"] for d in data["divergences"]["shown"]]), (1, ["only-left", "only-right"])) + + def test_unknown_caller_falls_back_to_module_and_function(self): + left = mk(("kernel32!Sleep", "-", "game+0x10"), ("kernel32!Other", "-", "?")) + right = mk(("kernel32!Sleep", "-", "?"), ("kernel32!Other", "-", "game+0x99")) + proc = self.run_tool(left, right) + self.assertEqual(proc.returncode, 0, proc.stdout) + + def test_unknown_caller_ret_is_still_compared(self): + left = mk(("kernel32!Sleep", "u:0x1", "?")) + right = mk(("kernel32!Sleep", "u:0x2", "game+0x4")) + rc, data = self.run_json(left, right) + shown = data["divergences"]["shown"] + self.assertEqual((rc, [d["kind"] for d in shown], shown[0]["caller"]), (1, ["ret"], "game+0x4")) + + def test_comments_and_blank_lines(self): + left = Tr(stack="gta6rt", extra_lines=["# a comment", ""]) + left.call(1, "kernel32!A", "p:1", "game+0x1") + left.raw("") + left.raw(" ") + left.call(1, "kernel32!B") + right = Tr(stack="leonida-hle") + right.call(1, "kernel32!A", "p:1", "game+0x1") + right.call(1, "kernel32!B") + proc = self.run_tool(left.text(), right.text()) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + self.assertIn("records=2 threads=1", proc.stdout) + + def test_crlf_input(self): + text = mk(*BASE).replace("\n", "\r\n") + path = os.path.join(self.dir, "crlf.trace") + with open(path, "w", encoding="utf-8", newline="") as handle: + handle.write(text) + trace = call_trace_diff.parse_trace(path) + self.assertEqual((trace.label, trace.ncalls, trace.rules), ("crlf.trace", 3, RULES)) + + +class JoinTests(TraceDiffCase): + def nested(self, outer_ret="u:0x1", inner_ret="hr:0x00000000"): + tr = Tr() + outer = tr.enter(1, "kernel32!Outer") + inner = tr.enter(1, "kernel32!Inner", "game+0x20") + tr.leave(1, inner, inner_ret) + tr.leave(1, outer, outer_ret) + return tr.text(), outer, inner + + def test_nested_calls_are_joined_by_call_seq(self): + left, outer, inner = self.nested() + self.assertEqual(self.run_tool(left, self.nested()[0]).returncode, 0) + right, _, _ = self.nested(outer_ret="u:0x2") + rc, data = self.run_json(left, right) + self.assertEqual(rc, 1) + shown = data["divergences"]["shown"] + self.assertEqual([(d["kind"], d["call"], d["left_seq"], d["left"], d["right"]) for d in shown], + [("ret", "kernel32!Outer", outer, "u:0x1", "u:0x2")]) + right, _, _ = self.nested(inner_ret="hr:0x80004005") + rc, data = self.run_json(left, right) + self.assertEqual([(d["call"], d["left_seq"]) for d in data["divergences"]["shown"]], + [("kernel32!Inner", inner)]) + + def test_open_call_section_and_open_kind(self): + left, right = Tr(), Tr() + left.call(1, "kernel32!A", "u:0x1") + crash = left.enter(1, "kernel32!B", "game+0x30", "hle") + right.call(1, "kernel32!A", "u:0x1") + returned = right.call(1, "kernel32!B", "hr:0x00000000", "game+0x30", "shim") + rc, data = self.run_json(left.text(), right.text()) + self.assertEqual((rc, self.kinds(data)), (1, [("open", crash, returned)])) + shown = data["divergences"]["shown"][0] + self.assertEqual((shown["left"], shown["right"]), ("open", "hr:0x00000000")) + self.assertEqual(data["open_calls"], {"total": 1, "shown": [ + {"side": "left", "thread": "main", "seq": crash, "call": "kernel32!B", "caller": "game+0x30", + "bind": "hle"}]}) + proc = self.run_tool(left.text(), right.text()) + self.assertIn("kind=open left_seq=%d right_seq=%d call=kernel32!B caller=game+0x30 left=open " + "right=hr:0x00000000 left_bind=hle right_bind=shim" % (crash, returned), proc.stdout) + self.assertIn("Open calls at end of trace: 1", proc.stdout) + self.assertIn("side=left thread=main seq=%d call=kernel32!B caller=game+0x30 bind=hle" % crash, proc.stdout) + + def test_open_on_right_side(self): + left, right = Tr(), Tr() + left.call(1, "kernel32!A", "u:0x1") + right.enter(1, "kernel32!A") + rc, data = self.run_json(left.text(), right.text()) + self.assertEqual((rc, [d["kind"] for d in data["divergences"]["shown"]]), (1, ["open"])) + self.assertEqual([o["side"] for o in data["open_calls"]["shown"]], ["right"]) + + def test_open_on_both_sides_is_listed_but_not_a_divergence(self): + left, right = Tr(), Tr() + for tr in (left, right): + tr.call(1, "kernel32!A") + tr.enter(1, "kernel32!Wait") + tr.thread(2, "game+0x200") + tr.enter(2, "kernel32!Wait2") + proc = self.run_tool(left.text(), right.text()) + self.assertEqual(proc.returncode, 0, proc.stdout) + self.assertIn("Open calls at end of trace: 4", proc.stdout) + self.assertIn("side=left thread=main", proc.stdout) + self.assertIn("side=right thread=game+0x200#1", proc.stdout) + + def test_open_nested_stack_lists_every_open_call(self): + tr = Tr() + tr.enter(1, "kernel32!Outer") + tr.enter(1, "kernel32!Inner") + rc, data = self.run_json(tr.text(), tr.text()) + self.assertEqual(rc, 0) + self.assertEqual([o["call"] for o in data["open_calls"]["shown"] if o["side"] == "left"], + ["kernel32!Outer", "kernel32!Inner"]) + + def test_open_against_an_entry_only_call_is_not_reported(self): + left, right = Tr(), Tr() + left.enter(1, "kernel32!A") + right.entry(1, "kernel32!A") + proc = self.run_tool(left.text(), right.text()) + self.assertEqual(proc.returncode, 0, proc.stdout) + + def test_open_against_a_void_return_is_reported(self): + left, right = Tr(), Tr() + left.enter(1, "kernel32!ExitThing") + right.call(1, "kernel32!ExitThing", "-") + rc, data = self.run_json(left.text(), right.text()) + self.assertEqual((rc, [d["kind"] for d in data["divergences"]["shown"]]), (1, ["open"])) + + def test_entry_records_are_never_compared(self): + left, right = Tr(), Tr() + left.entry(1, "kernel32!A", bind="unimpl") + left.entry(1, "kernel32!B") + left.call(1, "kernel32!C", "u:0x1") + right.call(1, "kernel32!A", "hr:0x80004005") + right.entry(1, "kernel32!B") + right.entry(1, "kernel32!C") + proc = self.run_tool(left.text(), right.text()) + self.assertEqual(proc.returncode, 0, proc.stdout) + self.assertIn("records=3", proc.stdout) + + def test_unimpl_calls_are_counted_per_side(self): + left, right = Tr(), Tr() + left.entry(1, "kernel32!A", bind="unimpl") + left.call(1, "kernel32!B", bind="unimpl") + left.call(1, "kernel32!C") + right.call(1, "kernel32!A") + rc, data = self.run_json(left.text(), right.text()) + self.assertEqual((data["left"]["unimpl"], data["right"]["unimpl"]), (2, 0)) + proc = self.run_tool(left.text(), right.text()) + self.assertIn("unimpl=2", proc.stdout.splitlines()[0]) + self.assertIn("unimpl=0", proc.stdout.splitlines()[1]) + + +class FileShapeTests(TraceDiffCase): + def test_trailing_nuls_and_partial_last_line_are_accepted(self): + full = mk(*BASE) + partial = "99\t1\tC\tkernel32!Cut\tgame+0x" + for name, trailer in (("nuls", "\0" * 64), ("partial", partial), ("partial+nuls", partial + "\0" * 64), + ("partial mid-character", "99\t1\tC\tkernel32!é"[:-1] + "\0" * 5)): + with self.subTest(name): + proc = self.run_tool(full + trailer, full) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + self.assertIn("records=3 threads=1", proc.stdout) + + def test_partial_last_line_cut_inside_a_utf8_character(self): + data = mk(*BASE).encode("utf-8") + "99\txé".encode("utf-8")[:-1] + b"\0\0" + path = os.path.join(self.dir, "cut.trace") + with open(path, "wb") as handle: + handle.write(data) + self.assertEqual(call_trace_diff.parse_trace(path).ncalls, 3) + + def test_a_half_written_r_does_not_close_its_call(self): + tr = Tr() + crash = tr.enter(1, "kernel32!A") + rc, data = self.run_json(tr.text("%d\t1\tR\t%d\thr:0x0000" % (tr.seq + 1, crash)), tr.text()) + self.assertEqual((rc, data["open_calls"]["total"]), (0, 2)) + + def test_malformed_full_line_before_nuls_is_still_an_error(self): + proc = self.run_tool(mk(*BASE) + "9\t1\tQ\n" + "\0" * 8, mk(*BASE)) + self.assertEqual(proc.returncode, 2, proc.stdout) + self.assertIn("left.trace:9:", proc.stderr) + + def test_malformed_lines_exit_2_with_line_number(self): + tr = Tr() + tr.call(1, "kernel32!A") # header line 1, T line 2, C line 3, R line 4 + good = tr.text() + done = tr.seq + bad_cases = { + "too few fields": "100\t1", + "bad seq": "x\t1\tC\tkernel32!A\tgame+0x1\tshim", + "bad tid": "100\tmain\tC\tkernel32!A\tgame+0x1\tshim", + "empty tid": "100\t\tC\tkernel32!A\tgame+0x1\tshim", + "unknown kind": "100\t1\tX\tkernel32!A\tgame+0x1\tshim", + "C too few fields": "100\t1\tC\tkernel32!A\tgame+0x1", + "C too many fields": "100\t1\tC\tkernel32!A\tgame+0x1\tshim\textra", + "no bang": "100\t1\tC\tkernel32\tgame+0x1\tshim", + "bad caller": "100\t1\tC\tkernel32!A\tgame\tshim", + "bad bind": "100\t1\tC\tkernel32!A\tgame+0x1\tpointer", + "duplicate seq": "%d\t1\tC\tkernel32!A\tgame+0x1\tshim" % (done - 1), + "no T before a call": "100\t77\tC\tkernel32!A\tgame+0x1\tshim", + "T too few fields": "100\t5\tT\tmain", + "bad start": "100\t5\tT\tgame\t1", + "bad created": "100\t5\tT\tmain\tlater", + "R unknown call-seq": "100\t1\tR\t999\tu:0x1", + "R call-seq not a number": "100\t1\tR\tx\tu:0x1", + "R twice": "100\t1\tR\t%d\tu:0x1" % (done - 1), + "bad ret": "100\t1\tR\t%d\thr:0x1" % (done - 1), + "R too few fields": "100\t1\tR\t%d" % (done - 1), + "bad pointer": "100\t1\tR\t%d\tp:2" % (done - 1), + "bad bool": "100\t1\tR\t%d\tb:2" % (done - 1), + "raw rax": "100\t1\tR\t%d\t0x1234" % (done - 1), + "bad rules": None, + } + for name, bad in bad_cases.items(): + with self.subTest(name): + if bad is None: + left = good.replace("rules=" + RULES, "rules=xyz") + line = 1 + else: + left = good + "\n" + bad + "\n" # a blank line 5, the bad record line 6 + line = 6 + proc = self.run_tool(left, good) + self.assertEqual(proc.returncode, 2, proc.stdout) + self.assertIn("left.trace:%d:" % line, proc.stderr) + proc = self.run_tool(good, left) + self.assertEqual(proc.returncode, 2, proc.stdout) + self.assertIn("right.trace:%d:" % line, proc.stderr) + + def test_seq_must_start_at_one_and_increase(self): + head = "# leonida-call-trace 1 stack=x rules=%s\n" % RULES + cases = { + "zero": head + "0\t1\tT\tmain\t1\n", + "repeated": head + "1\t1\tT\tmain\t1\n1\t1\tC\tk!A\tgame+0x1\tshim\n", + "backwards": head + "5\t1\tT\tmain\t1\n3\t1\tC\tk!A\tgame+0x1\tshim\n", + } + for name, text in cases.items(): + with self.subTest(name): + proc = self.run_tool(text, mk(*BASE)) + self.assertEqual(proc.returncode, 2, proc.stdout) + self.assertIn("left.trace:%d:" % (3 if name != "zero" else 2), proc.stderr) + self.assertIn("seq", proc.stderr) + + def test_r_for_another_thread_or_an_entry_record_is_an_error(self): + tr = Tr() + seq = tr.enter(1, "kernel32!A") + tr.thread(2, "game+0x200") + tr.raw("%d\t2\tR\t%d\tu:0x1" % (tr.seq + 1, seq)) + proc = self.run_tool(tr.text(), mk(*BASE)) + self.assertEqual(proc.returncode, 2) + self.assertIn("left.trace:5:", proc.stderr) + tr = Tr() + seq = tr.entry(1, "kernel32!A") + tr.raw("%d\t1\tR\t%d\tu:0x1" % (tr.seq + 1, seq)) + proc = self.run_tool(tr.text(), mk(*BASE)) + self.assertEqual(proc.returncode, 2) + self.assertIn("left.trace:4:", proc.stderr) + + def test_unsupported_version_is_a_parse_error(self): + proc = self.run_tool("# leonida-call-trace 2 stack=x\n", mk("kernel32!A")) + self.assertEqual(proc.returncode, 2) + self.assertIn("left.trace:1:", proc.stderr) + + def test_provisional_record_shape_is_rejected(self): + old = "# leonida-call-trace 1\n1\tmain\tkernel32!A\tp:1\tgame+0x10\n" + proc = self.run_tool(old, mk("kernel32!A")) + self.assertEqual(proc.returncode, 2) + self.assertIn("left.trace:2:", proc.stderr) + + def test_a_reused_thread_id_starts_a_new_thread(self): + tr = Tr() + tr.thread(5, "game+0x100") + tr.call(5, "kernel32!A") + tr.thread(5, "game+0x200") + tr.call(5, "kernel32!B") + path = self.write("reuse.trace", tr.text()) + trace = call_trace_diff.parse_trace(path) + self.assertEqual([(t.start, [c.func for c in t.calls]) for t in trace.threads], + [("game+0x100", ["A"]), ("game+0x200", ["B"])]) + + def test_missing_input_exits_2(self): + proc = subprocess.run([sys.executable, "-I", TOOL, os.path.join(self.dir, "none.a"), + os.path.join(self.dir, "none.b")], capture_output=True, text=True) + self.assertEqual(proc.returncode, 2) + + +class HeaderTests(TraceDiffCase): + def test_title_bound_module_is_dropped_from_both_sides(self): + left = Tr(stack="gta6rt", extra_lines=["# title-bound VCRuntime140.dll"]) + right = Tr(stack="leonida-hle") + left.call(1, "kernel32!A", "u:0x1") + left.call(1, "vcruntime140.dll!memcpy", "p:1") + left.call(1, "kernel32!B") + right.call(1, "kernel32!A", "u:0x1") + right.call(1, "VCRUNTIME140.dll!memset", "p:1") # bound to the title on the left only, dropped anyway + right.call(1, "vcruntime140.dll!memcpy", "p:0") + right.call(1, "kernel32!B") + proc = self.run_tool(left.text(), right.text()) + self.assertEqual(proc.returncode, 0, proc.stdout) + self.assertIn("title-bound modules dropped from both sides: vcruntime140.dll (calls dropped: left=1 right=2)", + proc.stdout) + self.assertIn("records=2 threads=1", proc.stdout) + rc, data = self.run_json(left.text(), right.text()) + self.assertEqual((rc, data["title_bound"]), (0, ["vcruntime140.dll"])) + + def test_thread_with_only_title_bound_calls_disappears(self): + left = Tr(extra_lines=["# title-bound t.dll"]) + right = Tr() + left.call(1, "kernel32!A") + left.thread(2, "game+0x200") + left.call(2, "t.dll!X") + right.call(1, "kernel32!A") + self.assertEqual(self.run_tool(left.text(), right.text()).returncode, 0) + + def test_differing_rules_print_a_warning(self): + left = mk(*BASE, rules="aaaaaaaaaaaaaaaa") + right = mk(*BASE, rules="bbbbbbbbbbbbbbbb") + proc = self.run_tool(left, right) + self.assertEqual(proc.returncode, 0, proc.stdout) + self.assertIn("WARNING: rules differ (left=aaaaaaaaaaaaaaaa right=bbbbbbbbbbbbbbbb)", proc.stdout) + self.assertIn("rules=aaaaaaaaaaaaaaaa", proc.stdout.splitlines()[0]) + rc, data = self.run_json(left, right) + self.assertTrue(data["rules_differ"]) + proc = self.run_tool(left, mk(*BASE, rules="AAAAAAAAAAAAAAAA")) + self.assertNotIn("WARNING", proc.stdout) + + def test_dropped_last_value_wins_and_warns(self): + left = Tr(extra_lines=["# dropped 3"]) + left.call(1, "kernel32!A") + left.raw("# dropped 12") + left.call(1, "kernel32!B") + right = mk("kernel32!A", "kernel32!B") + proc = self.run_tool(left.text(), right) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + lines = proc.stdout.splitlines() + self.assertIn("dropped=12", lines[0]) + self.assertIn("dropped=0", lines[1]) + self.assertIn("WARNING: left: the writer dropped 12 records", proc.stdout) + self.assertIn("may be drops, not behaviour", proc.stdout) + self.assertNotIn("WARNING: right", proc.stdout) + rc, data = self.run_json(left.text(), right) + self.assertEqual((data["left"]["dropped"], data["right"]["dropped"]), (12, 0)) + self.assertEqual(data["left"]["title_bound_calls"], 0) + + def test_dropped_zero_has_no_warning(self): + proc = self.run_tool(mk("kernel32!A", extra_lines=["# dropped 0"]), mk("kernel32!A")) + self.assertNotIn("WARNING", proc.stdout) + + def test_malformed_dropped_exit_2_with_line_number(self): + for bad in ("# dropped", "# dropped many", "# dropped -1", "# dropped 1 2", "# dropped 0x10"): + with self.subTest(bad): + tr = Tr() + tr.call(1, "kernel32!A") + tr.raw(bad) # header 1, T 2, C 3, R 4, bad 5 + proc = self.run_tool(tr.text(), mk("kernel32!A")) + self.assertEqual(proc.returncode, 2, proc.stdout) + self.assertIn("left.trace:5:", proc.stderr) + + def test_truncated_is_shown_per_side(self): + left = Tr(extra_lines=["# truncated"]) + left.call(1, "kernel32!A") + proc = self.run_tool(left.text(), mk("kernel32!A")) + lines = proc.stdout.splitlines() + self.assertIn("truncated=yes", lines[0]) + self.assertIn("truncated=no", lines[1]) + rc, data = self.run_json(left.text(), mk("kernel32!A")) + self.assertEqual((data["left"]["truncated"], data["right"]["truncated"]), (True, False)) + + +class PairingTests(TraceDiffCase): + WORKER = "game+0xa000" + + def traces(self): + """Two workers with one start; the sides create them in the opposite order.""" + left, right = Tr(), Tr() + left.call(1, "kernel32!Main") + right.call(1, "kernel32!Main") + left.thread(10, self.WORKER, created=100) + left.thread(11, self.WORKER, created=200) + right.thread(20, self.WORKER, created=100) + right.thread(21, self.WORKER, created=200) + # left: 10 runs X, Y and 11 runs P, Q. right: 20 (created first) runs P, Q and 21 runs X, Y. + for tr, first, second in ((left, 10, 11), (right, 21, 20)): + tr.call(first, "kernel32!X", "u:0x1", "game+0x100") + tr.call(first, "kernel32!Y", "u:0x2", "game+0x110") + tr.call(second, "kernel32!P", "u:0x3", "game+0x200") + tr.call(second, "kernel32!Q", "u:0x4", "game+0x210") + return left, right + + def test_threads_with_one_start_pair_by_call_sequence_not_by_created(self): + left, right = self.traces() + proc = self.run_tool(left.text(), right.text()) + self.assertEqual(proc.returncode, 0, proc.stdout) + self.assertIn("threads on one side only: 0", proc.stdout) + + def test_pair_keys_follow_the_left_creation_order(self): + left, right = self.traces() + # make the right's P/Q thread return something else: it pairs with the left's second thread + right.lines = [line.replace("u:0x4", "u:0x9") for line in right.lines] + rc, data = self.run_json(left.text(), right.text()) + self.assertEqual(rc, 1) + self.assertEqual([(d["thread"], d["call"]) for d in data["divergences"]["shown"]], + [("%s#2" % self.WORKER, "kernel32!Q")]) + self.assertEqual(self.run_tool(left.text(), right.text(), "--thread", self.WORKER + "#1").returncode, 0) + self.assertEqual(self.run_tool(left.text(), right.text(), "--thread", self.WORKER + "#2").returncode, 1) + self.assertEqual(self.run_tool(left.text(), right.text(), "--thread", self.WORKER).returncode, 1) + self.assertEqual(self.run_tool(left.text(), right.text(), "--thread", "main").returncode, 0) + + def test_the_best_prefix_pairs_first(self): + left, right = Tr(), Tr() + left.thread(10, self.WORKER, created=1) + left.thread(11, self.WORKER, created=2) + right.thread(20, self.WORKER, created=1) + right.thread(21, self.WORKER, created=2) + for name in ("A", "B", "C"): + left.call(10, "kernel32!" + name) + for name in ("A", "B", "D"): + left.call(11, "kernel32!" + name) + for name in ("A", "B", "D"): + right.call(20, "kernel32!" + name) # the first created on the right matches left 11, not left 10 + for name in ("A", "X", "Y"): + right.call(21, "kernel32!" + name) + rc, data = self.run_json(left.text(), right.text()) + # pairs: (left 11, right 20) with a 3-call prefix, then (left 10, right 21) with 1 + self.assertEqual({d["thread"] for d in data["divergences"]["shown"]}, {"%s#1" % self.WORKER}) + self.assertEqual(data["threads_only"], []) + self.assertEqual({c["thread"] for c in data["counts"]["shown"]}, {"%s#1" % self.WORKER}) + self.assertEqual(data["counts"]["total"], 4) # B, C, X, Y: only the poorly matched pair differs + + def test_equal_prefixes_pair_by_created_order(self): + left, right = Tr(), Tr() + for tr, order in ((left, (10, 11)), (right, (21, 20))): + tr.thread(order[0], self.WORKER, created=1) + tr.thread(order[1], self.WORKER, created=2) + tr.call(order[0], "kernel32!A", "u:0x1") + tr.call(order[1], "kernel32!A", "u:0x2") + rc, data = self.run_json(left.text(), right.text()) + self.assertEqual(rc, 0, data) + + def test_main_is_keyed_main_and_starts_compare_case_insensitively(self): + left, right = Tr(), Tr() + left.thread(1, "main") + left.thread(2, "Game+0xA000") + left.call(2, "kernel32!W", "u:0x1") + right.thread(1, "main") + right.thread(2, "game+0xa000") + right.call(2, "kernel32!W", "u:0x2") + rc, data = self.run_json(left.text(), right.text()) + self.assertEqual([d["thread"] for d in data["divergences"]["shown"]], ["game+0xa000#1"]) + + +class OutputTests(TraceDiffCase): + def test_out_same_as_input_is_refused(self): + a = self.write("left.trace", mk(*BASE)) + b = self.write("right.trace", mk(*BASE)) + for out in (a, b): + proc = subprocess.run([sys.executable, "-I", TOOL, a, b, "--out", out], capture_output=True, text=True) + self.assertEqual(proc.returncode, 2) + with open(out, encoding="utf-8", newline="") as handle: + self.assertEqual(handle.read(), mk(*BASE)) + + def test_unwritable_out_exits_2_with_a_message(self): + out = os.path.join(self.dir, "no-such-dir", "report.txt") + proc = self.run_tool(mk(*BASE), mk(BASE[0], BASE[2]), "--out", out) + self.assertEqual(proc.returncode, 2, proc.stdout) + self.assertIn("error: cannot write", proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + proc = self.run_tool(mk(*BASE), mk(*BASE), "--out", self.dir) # a directory + self.assertEqual(proc.returncode, 2) + self.assertNotIn("Traceback", proc.stderr) + + def test_out_writes_lf_file(self): + out = os.path.join(self.dir, "report.txt") + proc = self.run_tool(mk(*BASE), mk(BASE[0], BASE[2]), "--out", out) + self.assertEqual(proc.returncode, 1) + self.assertEqual(proc.stdout, "") + with open(out, "rb") as handle: + data = handle.read() + self.assertNotIn(b"\r", data) + self.assertTrue(data.endswith(b"\n")) + self.assertIn(b"kind=only-left", data) + + def test_json_matches_text(self): + left, right = Tr(), Tr() + left.call(1, *BASE[0]) + left.call(1, BASE[1][0], "hr:0x00000000") + left.call(1, *BASE[2]) + left.thread(3, "game+0x300") + left.call(3, "kernel32!Sleep") + left.call(1, "kernel32!Extra") + right.call(1, *BASE[0]) + right.call(1, BASE[1][0], "hr:0x80004005") + right.call(1, *BASE[2]) + text = self.run_tool(left.text(), right.text()).stdout + proc = self.run_tool(left.text(), right.text(), "--json") + self.assertTrue(proc.stdout.endswith("}\n")) + data = json.loads(proc.stdout) + self.assertEqual(proc.stdout, json.dumps(data, sort_keys=True, indent=2) + "\n") + self.assertEqual(proc.returncode, 1) + self.assertTrue(data["diverged"]) + self.assertEqual(data["left"]["records"], 5) + self.assertEqual(data["right"]["threads"], 1) + self.assertEqual(data["divergences"]["total"], 2) + for d in data["divergences"]["shown"]: + self.assertIn("kind=%s" % d["kind"], text) + self.assertIn("call=%s" % d["call"], text) + self.assertEqual([d["kind"] for d in data["divergences"]["shown"]], ["ret", "only-left"]) + self.assertIn("thread=game+0x300#1 only-left calls=1", text) + self.assertEqual(data["threads_only"], [{"thread": "game+0x300#1", "side": "left", "calls": 1}]) + self.assertEqual(data["counts"]["total"], 1) + self.assertIn("call=kernel32!Extra left=1 right=0 delta=-1", text) + + def test_json_identical(self): + rc, data = self.run_json(mk(*BASE), mk(*BASE)) + self.assertEqual(rc, 0) + self.assertFalse(data["diverged"]) + self.assertEqual(data["divergences"], {"shown": [], "total": 0}) + self.assertEqual(data["open_calls"], {"shown": [], "total": 0}) + + def test_max_limits_listing_not_total(self): + left = mk(*[("kernel32!F%d" % i, "u:0x1") for i in range(1, 8)]) + right = mk(*[("kernel32!F%d" % i, "u:0x2") for i in range(1, 8)]) + rc, data = self.run_json(left, right, "--max", "3") + self.assertEqual((data["divergences"]["total"], len(data["divergences"]["shown"])), (7, 3)) + self.assertEqual([d["left_seq"] for d in data["divergences"]["shown"]], [seq_of(0), seq_of(1), seq_of(2)]) + self.assertEqual(data["counts"]["total"], 0) + + def test_ordering_by_left_seq_and_right_seq_for_only_right(self): + left = mk(("kernel32!A", "u:0x1"), "kernel32!B", "kernel32!B2", "kernel32!B3", ("kernel32!C", "u:0x1")) + right = mk(("kernel32!A", "u:0x2"), "kernel32!B", "kernel32!New", "kernel32!B2", "kernel32!B3", + ("kernel32!C", "u:0x2")) + rc, data = self.run_json(left, right) + self.assertEqual(self.kinds(data), [("ret", seq_of(0), seq_of(0)), ("only-right", None, seq_of(2)), + ("ret", seq_of(4), seq_of(5))]) + + +class OrderTests(TraceDiffCase): + def test_divergences_are_positional_across_threads(self): + # the right side makes many calls on another thread before the divergences: its seqs are far above the left's + left, right = Tr(), Tr() + right.thread(9, "game+0x900") + for i in range(50): + right.call(9, "kernel32!Spin%d" % i) + left.call(1, "kernel32!A") + left.call(1, "kernel32!B") + left.call(1, "kernel32!C", "u:0x1") + right.call(1, "kernel32!A") + extra = right.call(1, "kernel32!Extra") + right.call(1, "kernel32!B") + right.call(1, "kernel32!C", "u:0x2") + self.assertGreater(extra, 100) + rc, data = self.run_json(left.text(), right.text()) + self.assertEqual([(d["kind"], d["call"]) for d in data["divergences"]["shown"]], + [("only-right", "kernel32!Extra"), ("ret", "kernel32!C")]) + self.assertEqual([d["anchor"] for d in data["divergences"]["shown"]], [seq_of(0), seq_of(2)]) + self.assertTrue(all("_pos" not in d and "_order" not in d for d in data["divergences"]["shown"])) + + def test_only_right_before_the_first_left_call_has_anchor_zero(self): + left, right = Tr(), Tr() + left.call(1, "kernel32!A", "u:0x1") + right.call(1, "kernel32!New") + right.call(1, "kernel32!A", "u:0x2") + rc, data = self.run_json(left.text(), right.text()) + self.assertEqual([(d["kind"], d["anchor"]) for d in data["divergences"]["shown"]], + [("only-right", 0), ("ret", seq_of(0))]) + + def test_same_anchor_orders_by_thread_pairing_then_place(self): + left, right = Tr(), Tr() + for tr in (left, right): + tr.thread(1, "main") + tr.thread(2, "game+0x200") + left.call(1, "kernel32!A") + left.call(2, "kernel32!B") + right.call(1, "kernel32!New1") # both extra calls sit before the first left call of their thread: anchor 0 + right.call(1, "kernel32!A") + right.call(2, "kernel32!New2") + right.call(2, "kernel32!B") + rc, data = self.run_json(left.text(), right.text()) + shown = data["divergences"]["shown"] + self.assertEqual([(d["anchor"], d["thread"]) for d in shown], [(0, "game+0x200#1"), (0, "main")]) + + +class MemoryTests(TraceDiffCase): + CALLS = 200000 + PEAK_LIMIT = 60 * 1024 * 1024 # measured peak 28.6 MB (150 bytes per call) + + def test_parsing_a_large_trace_keeps_few_bytes_per_call(self): + import tracemalloc + path = os.path.join(self.dir, "big.trace") + with open(path, "w", encoding="utf-8", newline="\n") as handle: + handle.write("# leonida-call-trace 1 stack=x rules=%s\n1\t7\tT\tmain\t1\n" % RULES) + seq = 2 + for i in range(self.CALLS): + handle.write("%d\t7\tC\tkernel32!Func%d\tgame+0x%x\tshim\n" % (seq, i % 400, 0x1000 + (i % 700) * 8)) + handle.write("%d\t7\tR\t%d\tu:0x%08x\n" % (seq + 1, seq, i % 5)) + seq += 2 + tracemalloc.start() + try: + trace = call_trace_diff.parse_trace(path) + peak = tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + self.assertEqual(trace.ncalls, self.CALLS) + self.assertLess(peak, self.PEAK_LIMIT, "peak %.1f MB, %.0f bytes per call" % (peak / 2**20, peak / self.CALLS)) + + +class WindowTests(TraceDiffCase): + def test_window_smaller_than_trace_still_finds_divergence(self): + names = ["kernel32!F%d" % (i % 37) for i in range(1000)] + right_names = names[:700] + ["kernel32!Injected"] + names[700:] + for window in ("50", "7", "2000"): + with self.subTest(window=window): + rc, data = self.run_json(mk(*names), mk(*right_names), "--window", window) + self.assertEqual(rc, 1) + self.assertEqual(self.kinds(data), [("only-right", None, seq_of(700))]) + self.assertEqual(data["divergences"]["shown"][0]["call"], "kernel32!Injected") + + def test_window_bridges_insertion_longer_than_window(self): + names = ["kernel32!F%d" % i for i in range(300)] + extra = ["kernel32!X%d" % i for i in range(200)] + rc, data = self.run_json(mk(*names), mk(*(names[:100] + extra + names[100:])), "--window", "20") + self.assertEqual(self.kinds(data), [("only-right", None, seq_of(100))]) + self.assertEqual(data["divergences"]["shown"][0]["calls"], 200) + + def test_window_must_be_positive(self): + self.assertEqual(self.run_tool(mk(*BASE), mk(*BASE), "--window", "0").returncode, 2) + + def test_long_trace_terminates(self): + calls = [("kernel32!F%d" % (i % 500), "u:0x%x" % (i % 3)) for i in range(150000)] + right_calls = list(calls) + right_calls[100000] = ("kernel32!Changed", "u:0x1") + rc, data = self.run_json(mk(*calls), mk(*right_calls)) + self.assertEqual(rc, 1) + self.assertEqual([d["kind"] for d in data["divergences"]["shown"]], ["only-left", "only-right"]) + self.assertEqual(data["divergences"]["shown"][0]["left_seq"], seq_of(100000)) + + def test_help(self): + proc = subprocess.run([sys.executable, "-I", TOOL, "--help"], capture_output=True, text=True) + self.assertEqual(proc.returncode, 0) + self.assertIn("--window", proc.stdout) + self.assertIn("START[#N]", proc.stdout) + + +class AlignTests(unittest.TestCase): + def test_align_covers_both_sequences(self): + a = list("abcdefgh") + b = list("abxdefyyh") + ops = call_trace_diff.align(a, b, 3) + self.assertEqual(sum(i2 - i1 for tag, i1, i2, j1, j2 in ops), len(a)) + self.assertEqual(sum(j2 - j1 for tag, i1, i2, j1, j2 in ops), len(b)) + self.assertEqual([(i1, j1) for tag, i1, i2, j1, j2 in ops][0], (0, 0)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_call_trace_rules.py b/tests/test_call_trace_rules.py new file mode 100644 index 0000000000..5cbb3639ae --- /dev/null +++ b/tests/test_call_trace_rules.py @@ -0,0 +1,203 @@ +"""The import call trace's rules file and the one rule that keeps gta6rt's shims honest about their caller. + + python -I tests/test_call_trace_rules.py + +`tools/call_trace_rules.def` is read by both runtimes (runtime/shims/call_trace.h includes it, leonida-hle parses the +same text), so its grammar is checked here: one rule per line, string literals only, a known macro with the right +number of arguments. Its FNV-1a 64 hash (the macro name, a NUL, each argument, a NUL, in file order: the `rules=` of +the trace header) is recomputed and compared with the constant runtime/test/call_trace_test.cpp asserts, so a rule +change fails here until that constant is updated, and the same constant has to be updated in the leonida-hle tests. + +With the trace on, a shim is called by the trace's wrap stub, not by the title: a raw `_ReturnAddress()` there names +the stub. Every shim reads its caller through `RT_CALLER()` (runtime/shims/call_trace_caller.h); the only raw uses +left are that header and the two D3D12 COM files, whose methods are not reached through an import table. + +Standard library only; sources only: no build, no GPU, no game files. +""" +import os +import re +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +RULES = os.path.join(ROOT, "tools", "call_trace_rules.def") +CPP_TEST = os.path.join(ROOT, "runtime", "test", "call_trace_test.cpp") + +# macro -> number of string arguments +MACROS = { + "CT_SKIP": 1, + "CT_SKIP_HAS": 1, + "CT_SKIP_MODULE": 1, + "CT_ENTRY": 1, + "CT_ENTRY_HAS": 1, + "CT_VOID": 1, + "CT_BOOL": 1, + "CT_U32": 1, + "CT_HR": 1, + "CT_HR_MOD": 2, + "CT_NOT_HR": 1, +} +LITERAL = r'"[^"\\]*"' +RULE = re.compile(r"(CT_[A-Z0-9_]+)\((%s(?:, %s)*)\)" % (LITERAL, LITERAL)) + +# Raw _ReturnAddress() is allowed here only. +RAW_ALLOWED = { + "runtime/shims/call_trace_caller.h", + "runtime/shims/d3d12_xs_device.cpp", + "runtime/shims/d3d12_vulkan_device.cpp", +} +SCANNED_DIRS = ("runtime/shims", "runtime/src") +SOURCE_SUFFIXES = (".cpp", ".h", ".hpp", ".cc", ".cxx", ".inl") + + +def read(path): + with open(path, encoding="utf-8", errors="replace", newline="") as f: + return f.read() + + +def parse_rules(text): + """[(macro, [argument, ...])] in file order; raises ValueError naming the line that breaks the grammar.""" + rules = [] + for number, raw in enumerate(text.splitlines(), 1): + line = raw.strip() + if not line or line.startswith("//"): + continue + m = RULE.fullmatch(line) + if not m: + raise ValueError("line %d is not one rule of string literals: %r" % (number, raw)) + macro = m.group(1) + args = [a[1:-1] for a in re.findall(LITERAL, m.group(2))] + if macro not in MACROS: + raise ValueError("line %d: unknown macro %s" % (number, macro)) + if len(args) != MACROS[macro]: + raise ValueError("line %d: %s takes %d argument(s), has %d" % (number, macro, MACROS[macro], len(args))) + if any(not a for a in args): + raise ValueError("line %d: an empty argument" % number) + rules.append((macro, args)) + return rules + + +def rules_hash(rules): + h = 0xCBF29CE484222325 + for macro, args in rules: + for part in [macro] + args: + for byte in part.encode("utf-8") + b"\0": + h = ((h ^ byte) * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF + return "%016x" % h + + +def strip_comments(text): + """The text without // and /* */ comments and with string and character literals blanked, lines kept.""" + out = [] + i, n = 0, len(text) + while i < n: + c = text[i] + two = text[i:i + 2] + if two == "//": + while i < n and text[i] != "\n": + i += 1 + elif two == "/*": + end = text.find("*/", i + 2) + end = n if end < 0 else end + 2 + out.append("\n" * text.count("\n", i, end)) + i = end + elif c in "\"'": + j = i + 1 + while j < n and text[j] != c and text[j] != "\n": + j += 2 if text[j] == "\\" else 1 + out.append(c + c) + i = j + 1 + else: + out.append(c) + i += 1 + return "".join(out) + + +def raw_return_address_uses(root=ROOT): + """["path:line"] of every `_ReturnAddress(` in code under runtime/shims and runtime/src outside RAW_ALLOWED.""" + found = [] + for directory in SCANNED_DIRS: + for base, dirs, files in os.walk(os.path.join(root, *directory.split("/"))): + dirs[:] = [d for d in dirs if d not in ("build", "__pycache__")] + for name in sorted(files): + if not name.endswith(SOURCE_SUFFIXES): + continue + path = os.path.join(base, name) + rel = os.path.relpath(path, root).replace(os.sep, "/") + if rel in RAW_ALLOWED: + continue + for number, line in enumerate(strip_comments(read(path)).splitlines(), 1): + if re.search(r"(? rules=<16 hex> + # title-bound imports of this DLL go to a title module and are untraced (any position) + # truncated the size cap was reached and tracing stopped + # dropped records dropped so far (writer lock not taken in time); repeated, the last one wins + T a thread's first traced call + C ! call entered + R the call with that seq returned + E ! entry-only call, no R follows + +`module` is compared case-insensitively, `function` (an import name or `#`) case-sensitively; `caller` and +`start` are `game+0x`, `+0x`, `?` (and `main` for `start`); `bind` is shim, hle, host or unimpl and is +shown in the report but is not part of a call's identity. The file is memory-mapped, so it may end in NUL bytes and in +a partial last line: trailing NULs are stripped and a last line without a trailing LF is ignored. Any other malformed +line is an error with file and line number, and so is a seq that does not exceed the previous one. Blank lines are +ignored; other `#` lines are comments; a file without the header is accepted with a WARNING. The file is read line by +line, so its size is not limited by memory, only the calls kept (about 150 bytes each) are. + +A dropped C is a call missing entirely and a dropped R leaves its C open, so the report warns when a side has +dropped records. + +A call is a C record joined with its R record by call-seq (nested calls appear as C C R R), or an E record. A C with no +R is `open` (it never returned: a crash, a longjmp or a call still running at the end). Return classes: `hr:0x<8 hex>` +and `u:0x` (compared exactly), `b:0` / `b:1`, `p:0` / `p:1` / `p:-1` (null / other / all ones), `-` (void or +unknown) and `open`. Two returns are compared when both are one of the first four kinds; `-` (and an E record) is never +compared. + +Divergences are listed in positional order: by the seq of the nearest left call at or before the place in the +alignment (`anchor`; the left seq is one order shared by all threads), then by thread pairing order, then by place. +Divergence kinds: `only-left` / `only-right` (a run of calls one side makes in a thread and the other does not), +`ret` (a matched call with a different comparable return), `open` (a matched call that returned on one side and never +returned on the other; a matched E record is never an `open`), `count` (per thread and module!function the call counts +differ) and `thread` (a thread present on one side only). The section "Open calls at end of trace" lists, per thread +and side, the calls that never returned (the crash site); it is shown even without other divergences and does not by +itself change the exit code. Exit code 0: no divergence, 1: divergences, 2: usage or parse error. + + python -I tools/call_trace_diff.py gta6rt.trace leonida-hle.trace --max 20 --out diff.txt + +Threads: the T record gives `start` and `created`. A thread with start `main` is keyed `main` (`main#n` when a side has +several). Other threads are grouped by `start` on each side and paired inside a group by the longest common prefix of +their call identity sequences (greedy, best pair first, ties by creation order); a pair is keyed `#`, n +counting the group's pairs in the left trace's creation order, then the unpaired threads. A thread left unpaired +because the other side has fewer threads in the group is reported as a thread on one side only. + +Modules named by a `# title-bound` line on either side are dropped from both sides before alignment. Differing +`rules=` hashes print a WARNING: the two traces were not made with the same rules and are not comparable. + +Alignment: per thread, a call's identity is (module, function, caller offset); a (module, function) that has an +unknown caller (`?`) on either side in that thread is compared by (module, function) only. The two identity +sequences are aligned with difflib.SequenceMatcher (autojunk=False) in chunks of `--window` calls: the chunk is +aligned, everything up to the end of its last matching block is committed and the next chunk starts there. A chunk +without any match is doubled until it matches, so a long insertion is still bridged. A divergence that is longer +than the window can in rare cases be reported as a wider only-left/only-right pair than the shortest edit script. +Standard library only; no game data. +""" +import argparse +import array +import collections +import difflib +import json +import os +import re +import sys + +ROOT = os.path.dirname(os.path.abspath(__file__)) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) +from report_paths import same_report_path # noqa: E402 + +DEFAULT_WINDOW = 2000 +DEFAULT_MAX = 20 +BINDS = ("shim", "hle", "host", "unimpl") + +_HR = re.compile(r"hr:0x([0-9a-fA-F]{8})\Z") +_UINT = re.compile(r"u:0x([0-9a-fA-F]+)\Z") +_BOOL = re.compile(r"b:([01])\Z") +_PTR = re.compile(r"p:(0|1|-1)\Z") +_CALLER = re.compile(r"(.+)\+0x([0-9a-fA-F]+)\Z") +_HEADER = re.compile(r"#\s*leonida-call-trace\s+(\S+)(.*)\Z") +_STACK = re.compile(r"(?:^|\s)stack=(\S+)") +_RULES = re.compile(r"(?:^|\s)rules=(\S+)") +_RULES_VALUE = re.compile(r"[0-9a-fA-F]{16}\Z") +_TITLE_BOUND = re.compile(r"#\s*title-bound\s+(\S+)\s*\Z") +_TRUNCATED = re.compile(r"#\s*truncated\s*\Z") +_DROPPED = re.compile(r"#\s*dropped(?:\s+(.*?))?\s*\Z") + + +class TraceError(Exception): + pass + + +class Call: + """One call: a C record joined with its R (or an E record). ret is None (never compared) or (kind, value).""" + __slots__ = ("seq", "module", "func", "caller_text", "caller", "bind", "entry", "open", "ret_text", "ret") + + def __init__(self, seq, module, func, caller_text, caller, bind, entry): + self.seq = seq + self.module = module + self.func = func + self.caller_text = caller_text + self.caller = caller + self.bind = bind + self.entry = entry + self.open = not entry + self.ret_text = "-" if entry else "open" + self.ret = None + + +class Thread: + __slots__ = ("tid", "start", "created", "calls", "opens") + + def __init__(self, tid, start, created): + self.tid = tid + self.start = start + self.created = created + self.calls = [] + self.opens = {} # seq -> Call entered on this thread and not yet returned (parse time only) + + +class Trace: + def __init__(self, path): + self.path = path + self.label = None + self.stack = None + self.rules = None + self.has_header = False + self.truncated = False + self.dropped = 0 # records the writer dropped (lock not taken in time): the last `# dropped` value + self.title_bound = set() + self.threads = [] + self.ncalls = 0 + + +def _decimal(text): + return text.isascii() and text.isdigit() + + +_CACHE_LIMIT = 100000 +_BIND = {b: b for b in BINDS} + + +def parse_trace(path): + """Read one trace file into a Trace, line by line. Raises TraceError(":: ...") on a malformed record.""" + name = os.path.basename(path) + trace = Trace(path) + current = {} # tid -> its newest Thread (an OS thread id can be reused after a thread exits) + call_cache, caller_cache, ret_cache = {}, {}, {} + intern = sys.intern + last_seq = 0 + lineno = 0 + + def fail(message): + raise TraceError("%s:%d: %s" % (name, lineno, message)) + + try: + handle = open(path, "rb") + except OSError as exc: + raise TraceError("%s: cannot read: %s" % (name, exc)) + with handle: + try: + for lineno, raw in enumerate(handle, 1): + if not raw.endswith(b"\n"): + break # a last chunk without its LF: a partial write and/or the NUL padding of the mapped file + try: + line = raw[:-1].decode("utf-8") + except UnicodeDecodeError as exc: + fail("not valid UTF-8: %s" % exc) + line = line.rstrip("\r") + if not line.strip(): + continue + if line.startswith("#"): + header = _HEADER.match(line) + if header: + if header.group(1) != "1": + fail("unsupported trace version %r" % header.group(1)) + if not trace.has_header: + trace.has_header = True + stack = _STACK.search(header.group(2)) + trace.stack = stack.group(1) if stack else None + rules = _RULES.search(header.group(2)) + if rules: + if not _RULES_VALUE.match(rules.group(1)): + fail("bad rules hash %r (16 hex digits)" % rules.group(1)) + trace.rules = rules.group(1).lower() + continue + bound = _TITLE_BOUND.match(line) + if bound: + trace.title_bound.add(bound.group(1).lower()) + elif _TRUNCATED.match(line): + trace.truncated = True + else: + lost = _DROPPED.match(line) + if lost: + if lost.group(1) is None or not _decimal(lost.group(1)): + fail("bad dropped count %r (a decimal integer)" % (lost.group(1) or "")) + trace.dropped = int(lost.group(1)) + continue + fields = line.split("\t") + if len(fields) < 3: + fail("expected TAB TAB ..., got %d TAB-separated fields" % len(fields)) + seq_text, tid_text, kind = fields[:3] + if not _decimal(seq_text): + fail("seq %r is not a decimal integer" % seq_text) + if not _decimal(tid_text): + fail("tid %r is not a decimal integer" % tid_text) + seq, tid = int(seq_text), int(tid_text) + if seq <= last_seq: + fail("seq %d does not exceed the previous seq %d (seq starts at 1 and increases)" + % (seq, last_seq)) + last_seq = seq + if kind == "T": + if len(fields) != 5: + fail("T record needs 5 TAB-separated fields (seq tid T start created), got %d" % len(fields)) + start = _parse_start(fields[3]) + if start is False: + fail("bad thread start %r (main, +0x or ?)" % fields[3]) + if not _decimal(fields[4]): + fail("created %r is not a decimal integer" % fields[4]) + thread = Thread(tid, intern(start), int(fields[4])) + current[tid] = thread + trace.threads.append(thread) + continue + if kind not in ("C", "E", "R"): + fail("unknown record kind %r (T, C, R or E)" % kind) + thread = current.get(tid) + if thread is None: + fail("thread %d has no T record before its first call" % tid) + if kind == "R": + if len(fields) != 5: + fail("R record needs 5 TAB-separated fields (seq tid R call-seq ret), got %d" % len(fields)) + if not _decimal(fields[3]): + fail("call-seq %r is not a decimal integer" % fields[3]) + call = thread.opens.pop(int(fields[3]), None) + if call is None: + fail("call-seq %s is not a C record of thread %d that is still open" % (fields[3], tid)) + ret_text = fields[4] + ret = ret_cache.get(ret_text, False) + if ret is False: + ret = _parse_ret(ret_text) + if ret is False: + fail("bad return %r (hr:0x<8 hex>, u:0x, b:0|1, p:0|1|-1 or -)" % ret_text) + if len(ret_cache) < _CACHE_LIMIT: + ret_cache[ret_text] = ret + call.open = False + call.ret_text = intern(ret_text) + call.ret = ret + continue + if len(fields) != 6: + fail("%s record needs 6 TAB-separated fields (seq tid %s module!function caller bind), got %d" + % (kind, kind, len(fields))) + named = call_cache.get(fields[3]) + if named is None: + module, bang, func = fields[3].partition("!") + if not bang or not module or not func: + fail("call %r is not !" % fields[3]) + named = (intern(module.lower()), intern(func)) + if len(call_cache) < _CACHE_LIMIT: + call_cache[fields[3]] = named + caller = caller_cache.get(fields[4]) + if caller is None: + parsed = _parse_caller(fields[4]) + if parsed is False: + fail("bad caller %r (+0x or ?)" % fields[4]) + caller = (intern(fields[4]), parsed) # one shared text and tuple per distinct caller + if len(caller_cache) < _CACHE_LIMIT: + caller_cache[fields[4]] = caller + bind = _BIND.get(fields[5]) + if bind is None: + fail("bad bind %r (shim, hle, host or unimpl)" % fields[5]) + call = Call(seq, named[0], named[1], caller[0], caller[1], bind, kind == "E") + if kind == "C": + thread.opens[seq] = call + thread.calls.append(call) + trace.ncalls += 1 + except OSError as exc: + raise TraceError("%s: cannot read: %s" % (name, exc)) + for thread in trace.threads: + thread.opens = None + trace.label = trace.stack or name + return trace + + +def _parse_ret(text): + if text == "-": + return None + match = _HR.match(text) + if match: + return ("hr", int(match.group(1), 16)) + match = _UINT.match(text) + if match: + return ("u", int(match.group(1), 16)) + match = _BOOL.match(text) + if match: + return ("b", int(match.group(1))) + match = _PTR.match(text) + if match: + return ("p", int(match.group(1))) + return False + + +def _parse_caller(text): + if text == "?": + return None + match = _CALLER.match(text) + if match: + return (match.group(1).lower(), int(match.group(2), 16)) + return False + + +def _parse_start(text): + if text == "main" or text == "?": + return text + match = _CALLER.match(text) + if match: + return "%s+0x%x" % (match.group(1).lower(), int(match.group(2), 16)) + return False + + +def visible_threads(trace, dropped): + """The trace's threads without the calls of `dropped` modules; a thread left with no call is dropped.""" + out = [] + for thread in trace.threads: + calls = [c for c in thread.calls if c.module not in dropped] if dropped else thread.calls + if calls: + kept = Thread(thread.tid, thread.start, thread.created) + kept.calls = calls + out.append(kept) + return out + + +def _prefix(a, b): + """Length of the common prefix of two identity arrays (binary search over slice equality).""" + n = min(len(a), len(b)) + if n == 0 or a[0] != b[0]: + return 0 + if a[:n] == b[:n]: + return n + lo, hi = 1, n - 1 # a[:1] matches, a[:n] does not + while lo < hi: + mid = (lo + hi + 1) // 2 + if a[:mid] == b[:mid]: + lo = mid + else: + hi = mid - 1 + return lo + + +def _identity_arrays(threads, wild, table): + """Per thread an array of small integers, one per call: equal numbers are equal identities.""" + out = [] + for thread in threads: + ids = array.array("I") + for c in thread.calls: + key = (c.module, c.func) + if key not in wild: + key += (c.caller,) + number = table.get(key) + if number is None: + number = table[key] = len(table) + ids.append(number) + out.append(ids) + return out + + +Entry = collections.namedtuple("Entry", "key start n left right") + + +def pair_threads(left_threads, right_threads): + """Pair the two sides' threads: [Entry(key, start, n, left Thread or None, right Thread or None)].""" + groups = {} + for side, threads in enumerate((left_threads, right_threads)): + for thread in sorted(threads, key=lambda t: t.created): # stable: file order for equal created + groups.setdefault(thread.start, ([], []))[side].append(thread) + entries = [] + for start in sorted(groups): + lefts, rights = groups[start] + if len(lefts) == 1 and len(rights) == 1: + pairs = [(0, 0)] + elif not lefts or not rights: + pairs = [] + else: + wild = set() + for thread in lefts + rights: + for c in thread.calls: + if c.caller is None: + wild.add((c.module, c.func)) + table = {} + ids_left = _identity_arrays(lefts, wild, table) + ids_right = _identity_arrays(rights, wild, table) + candidates = sorted((-_prefix(a, b), i, j) for i, a in enumerate(ids_left) + for j, b in enumerate(ids_right)) + used_left, used_right, pairs = set(), set(), [] + for _, i, j in candidates: + if i not in used_left and j not in used_right: + used_left.add(i) + used_right.add(j) + pairs.append((i, j)) + pairs.sort() + used_left = {i for i, _ in pairs} + used_right = {j for _, j in pairs} + ordered = [(lefts[i], rights[j]) for i, j in pairs] + ordered += [(lefts[i], None) for i in range(len(lefts)) if i not in used_left] + ordered += [(None, rights[j]) for j in range(len(rights)) if j not in used_right] + for n, (a, b) in enumerate(ordered, 1): + key = start if start == "main" and len(ordered) == 1 else "%s#%d" % (start, n) + entries.append(Entry(key, start, n, a, b)) + return entries + + +def select_entries(entries, selector): + """--thread: `main`, a start value (the whole group) or `#` (one thread of the group).""" + base, hash_, number = selector.rpartition("#") + if hash_ and _decimal(number): + number = int(number) + else: + base, number = selector, None + start = _parse_start(base) # the same normalisation as the T records: game+0x01A matches game+0x1a + if start is False: + start = base.lower() + return [e for e in entries if e.start == start and (number is None or e.n == number)] + + +def align(a, b, window): + """Align two lists of hashable identities: [(tag, i1, i2, j1, j2)], tag in equal / left / right.""" + n, m = len(a), len(b) + ops = [] + i = j = 0 + size = window + while i < n or j < m: + k = 0 + while i + k < n and j + k < m and a[i + k] == b[j + k]: + k += 1 + if k: + ops.append(("equal", i, i + k, j, j + k)) + i += k + j += k + size = window + continue + if i == n: + ops.append(("right", i, i, j, m)) + break + if j == m: + ops.append(("left", i, n, j, j)) + break + ae, be = min(n, i + size), min(m, j + size) + final = ae == n and be == m + matcher = difflib.SequenceMatcher(None, a[i:ae], b[j:be], autojunk=False) + opcodes = matcher.get_opcodes() + if not final: + equal = [op for op in opcodes if op[0] == "equal"] + if not equal: + size *= 2 # no common call in the chunk: widen it rather than commit a guess + continue + last = equal[-1] + opcodes = opcodes[:opcodes.index(last) + 1] + for tag, i1, i2, j1, j2 in opcodes: + ops.append(("equal" if tag == "equal" else "left" if tag == "delete" else "right" if tag == "insert" + else "replace", i + i1, i + i2, j + j1, j + j2)) + i, j = i + opcodes[-1][2], j + opcodes[-1][4] + size = window + if final: + break + out = [] + for tag, i1, i2, j1, j2 in ops: + if tag == "replace": + out.append(("left", i1, i2, j1, j1)) + out.append(("right", i2, i2, j1, j2)) + else: + out.append((tag, i1, i2, j1, j2)) + return out + + +def identities(left, right): + """Alignment identities of one thread's two call lists (see the module docstring for the `?` rule).""" + wild = set() + for rec in left + right: + if rec.caller is None: + wild.add((rec.module, rec.func)) + + def ident(rec): + key = (rec.module, rec.func) + return key if key in wild else key + (rec.caller,) + + return [ident(r) for r in left], [ident(r) for r in right] + + +def call_name(rec): + return "%s!%s" % (rec.module, rec.func) + + +def _caller_text(first, second=None): + if first.caller is not None or second is None: + return first.caller_text + return second.caller_text + + +def compare_thread(key, left, right, window, ignore_ret): + """Divergences of one thread: only-left / only-right runs, ret differences and calls open on one side. + + Each carries `anchor` (the seq of the nearest left call at or before its place in the alignment, 0 before the + first; the left counter is the one order shared by all threads) and `_pos`, its ordinal in the alignment.""" + found = [] + ids_left, ids_right = identities(left, right) + for tag, i1, i2, j1, j2 in align(ids_left, ids_right, window): + if tag == "equal": + for k, (x, y) in enumerate(zip(left[i1:i2], right[j1:j2])): + kind = None + if x.open != y.open: + if (y if x.open else x).entry: + continue # an E record never returns: nothing to compare with + kind = "open" + elif (x.ret is None or y.ret is None or x.ret == y.ret or call_name(x) in ignore_ret): + continue + else: + kind = "ret" + found.append({"thread": key, "kind": kind, "left_seq": x.seq, "right_seq": y.seq, + "call": call_name(x), "caller": _caller_text(x, y), "calls": 1, + "left": x.ret_text, "right": y.ret_text, + "left_bind": x.bind, "right_bind": y.bind, + "anchor": x.seq, "_pos": i1 + j1 + 2 * k}) + elif tag == "left" and i2 > i1: + first, last = left[i1], left[i2 - 1] + found.append({"thread": key, "kind": "only-left", "left_seq": first.seq, "right_seq": None, + "call": call_name(first), "caller": first.caller_text, "calls": i2 - i1, + "last_seq": last.seq, "left": first.ret_text, "right": None, + "left_bind": first.bind, "right_bind": None, + "anchor": first.seq, "_pos": i1 + j1}) + elif tag == "right" and j2 > j1: + first, last = right[j1], right[j2 - 1] + found.append({"thread": key, "kind": "only-right", "left_seq": None, "right_seq": first.seq, + "call": call_name(first), "caller": first.caller_text, "calls": j2 - j1, + "last_seq": last.seq, "left": None, "right": first.ret_text, + "left_bind": None, "right_bind": first.bind, + "anchor": left[i1 - 1].seq if i1 > 0 else 0, "_pos": i1 + j1}) + return found + + +def diff_threads(left_threads, right_threads, window=DEFAULT_WINDOW, ignore_ret=(), only_thread=None): + """Everything the report shows, unlimited: divergences, count differences, thread-only keys, open calls.""" + entries = pair_threads(left_threads, right_threads) + if only_thread is not None: + entries = select_entries(entries, only_thread) + if not entries: + raise TraceError("thread %r is in neither trace" % only_thread) + ignore = set(ignore_ret) + divergences, counts, thread_only, opens = [], [], [], [] + for order, entry in enumerate(entries): + left = entry.left.calls if entry.left else None + right = entry.right.calls if entry.right else None + for side, calls in (("left", left), ("right", right)): + for call in calls or (): + if call.open: + opens.append({"side": side, "thread": entry.key, "seq": call.seq, "call": call_name(call), + "caller": call.caller_text, "bind": call.bind}) + if left is None or right is None: + side = "left" if right is None else "right" + thread_only.append({"thread": entry.key, "side": side, "calls": len(left or right)}) + continue + for d in compare_thread(entry.key, left, right, window, ignore): + d["_order"] = order + divergences.append(d) + count_left = collections.Counter((r.module, r.func) for r in left) + count_right = collections.Counter((r.module, r.func) for r in right) + for module, func in sorted(set(count_left) | set(count_right)): + lc, rc = count_left[(module, func)], count_right[(module, func)] + if lc != rc: + counts.append({"thread": entry.key, "call": "%s!%s" % (module, func), "left": lc, "right": rc, + "delta": rc - lc}) + # positional: by the left call each divergence sits at or after, then thread pairing order, then place + divergences.sort(key=lambda d: (d["anchor"], d["_order"], d["_pos"])) + for d in divergences: + del d["_order"], d["_pos"] + counts.sort(key=lambda c: (-abs(c["delta"]), c["thread"], c["call"])) + opens.sort(key=lambda o: (o["thread"], o["side"], o["seq"])) + return divergences, counts, thread_only, opens + + +def _seq(value): + return "-" if value is None else str(value) + + +def divergence_line(d): + parts = ["thread=%s" % d["thread"], "kind=%s" % d["kind"], "left_seq=%s" % _seq(d["left_seq"]), + "right_seq=%s" % _seq(d["right_seq"]), "call=%s" % d["call"], "caller=%s" % d["caller"]] + if d["kind"] in ("ret", "open"): + parts += ["left=%s" % d["left"], "right=%s" % d["right"], + "left_bind=%s" % d["left_bind"], "right_bind=%s" % d["right_bind"]] + else: + parts.append("bind=%s" % (d["left_bind"] or d["right_bind"])) + if d["calls"] > 1: + parts += ["calls=%d" % d["calls"], "last_seq=%d" % d["last_seq"]] + return " ".join(parts) + + +def rules_differ(info): + return info["left"]["rules"] != info["right"]["rules"] + + +def format_report(info, divergences, counts, thread_only, opens, limit): + out = [] + for side in ("left", "right"): + i = info[side] + out.append("%s: %s (%s) records=%d threads=%d rules=%s truncated=%s unimpl=%d dropped=%d" % ( + side, i["label"], i["path"], i["records"], i["threads"], i["rules"] or "-", + "yes" if i["truncated"] else "no", i["unimpl"], i["dropped"])) + + for side in ("left", "right"): + if info[side]["dropped"]: + out.append("WARNING: %s: the writer dropped %d records (lock not taken in time): calls missing from " + "this side and its open calls may be drops, not behaviour" % (side, info[side]["dropped"])) + for side in ("left", "right"): + if not info[side]["header"]: + out.append("WARNING: %s: no leonida-call-trace header" % os.path.basename(info[side]["path"])) + if rules_differ(info): + out.append("WARNING: rules differ (left=%s right=%s): the traces were not made with the same rules" + % (info["left"]["rules"] or "-", info["right"]["rules"] or "-")) + if info["title_bound"]: + out.append("title-bound modules dropped from both sides: %s (calls dropped: left=%d right=%d)" % ( + ", ".join(info["title_bound"]), info["left"]["title_bound_calls"], info["right"]["title_bound_calls"])) + if info["thread"] is not None: + out.append("limited to thread %s" % info["thread"]) + out.append("divergences: %d (showing %d)" % (len(divergences), min(limit, len(divergences)))) + out.extend(divergence_line(d) for d in divergences[:limit]) + out.append("count differences: %d (showing %d)" % (len(counts), min(limit, len(counts)))) + for c in counts[:limit]: + out.append("thread=%s call=%s left=%d right=%d delta=%+d" % (c["thread"], c["call"], c["left"], c["right"], + c["delta"])) + out.append("threads on one side only: %d" % len(thread_only)) + for t in thread_only: + out.append("thread=%s only-%s calls=%d" % (t["thread"], t["side"], t["calls"])) + out.append("Open calls at end of trace: %d" % len(opens)) + for o in opens: + out.append("side=%s thread=%s seq=%d call=%s caller=%s bind=%s" % ( + o["side"], o["thread"], o["seq"], o["call"], o["caller"], o["bind"])) + return "\n".join(out) + "\n" + + +def build_parser(): + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("left", help="call trace of the first stack (e.g. gta6rt)") + ap.add_argument("right", help="call trace of the second stack (e.g. leonida-hle)") + ap.add_argument("--max", type=int, default=DEFAULT_MAX, metavar="N", + help="divergences and count differences to list (default %d); open calls are always all listed" + % DEFAULT_MAX) + ap.add_argument("--window", type=int, default=DEFAULT_WINDOW, metavar="N", + help="calls aligned per chunk (default %d)" % DEFAULT_WINDOW) + ap.add_argument("--ignore-ret", action="append", default=[], metavar="MODULE!FUNC", + help="do not compare the return of this function (repeatable)") + ap.add_argument("--thread", metavar="main|START[#N]", + help="limit the comparison to the main thread (`main`), to the threads with this start " + "(e.g. game+0x1a2b3c) or to one thread of that group (`START#N`: N counts the group's pairs " + "in the left trace's creation order, from 1, as the report's thread keys show)") + ap.add_argument("--json", action="store_true", help="emit JSON instead of text") + ap.add_argument("--out", metavar="PATH", help="write the report here instead of stdout") + return ap + + +def _side_info(trace, path, threads, dropped): + calls = [c for t in threads for c in t.calls] + return {"label": trace.label, "path": path, "records": len(calls), "threads": len(threads), + "rules": trace.rules, "truncated": trace.truncated, "stack": trace.stack, + "header": trace.has_header, + "unimpl": sum(1 for c in calls if c.bind == "unimpl"), + "dropped": trace.dropped, + "title_bound_calls": trace.ncalls - len(calls) if dropped else 0} + + +def main(argv=None): + ap = build_parser() + args = ap.parse_args(argv) + if args.max < 0: + ap.error("--max must not be negative") + if args.window < 1: + ap.error("--window must be at least 1") + ignore = [] + for item in args.ignore_ret: + module, bang, func = item.partition("!") + if not bang or not module or not func: + ap.error("--ignore-ret %r is not MODULE!FUNC" % item) + ignore.append("%s!%s" % (module.lower(), func)) + if args.out: + for name, path in (("left", args.left), ("right", args.right)): + if same_report_path(path, args.out): + ap.error("--out must not overwrite the %s input" % name) + try: + left = parse_trace(args.left) + right = parse_trace(args.right) + dropped = left.title_bound | right.title_bound + left_threads = visible_threads(left, dropped) + right_threads = visible_threads(right, dropped) + divergences, counts, thread_only, opens = diff_threads(left_threads, right_threads, args.window, ignore, + args.thread) + except TraceError as exc: + sys.stderr.write("error: %s\n" % exc) + return 2 + info = {"left": _side_info(left, args.left, left_threads, dropped), + "right": _side_info(right, args.right, right_threads, dropped), + "title_bound": sorted(dropped), "thread": args.thread} + if args.json: + text = json.dumps({ + "left": info["left"], "right": info["right"], "thread": args.thread, "max": args.max, + "title_bound": info["title_bound"], "rules_differ": rules_differ(info), + "divergences": {"total": len(divergences), "shown": divergences[:args.max]}, + "counts": {"total": len(counts), "shown": counts[:args.max]}, + "threads_only": thread_only, + "open_calls": {"total": len(opens), "shown": opens}, + "diverged": bool(divergences or counts or thread_only), + }, sort_keys=True, indent=2) + "\n" + else: + text = format_report(info, divergences, counts, thread_only, opens, args.max) + if args.out: + try: + with open(args.out, "w", encoding="utf-8", newline="\n") as handle: + handle.write(text) + except OSError as exc: + sys.stderr.write("error: cannot write %s: %s\n" % (args.out, exc)) + return 2 + else: + sys.stdout.write(text) + return 1 if (divergences or counts or thread_only) else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/call_trace_rules.def b/tools/call_trace_rules.def new file mode 100644 index 0000000000..787767b2f6 --- /dev/null +++ b/tools/call_trace_rules.def @@ -0,0 +1,236 @@ +// Rules of the import call trace (LEONIDA_CALL_TRACE), read by both runtimes so their traces are comparable: +// runtime/shims/call_trace.h includes this file with the CT_* macros defined; d3d12/crates/leonida-loader/src/ +// call_trace.rs parses the same text (include_str!). One rule per line, string literals only, no continuation lines. +// Function names are matched case-sensitively, module names are the lower-case DLL name of the import descriptor. +// +// CT_SKIP("name") the import is bound as without the trace: no thunk, no record +// CT_SKIP_HAS("text") the same for every function name that contains the text +// CT_SKIP_MODULE("prefix") the same for every import DLL whose name starts with the prefix +// CT_ENTRY("name") recorded at entry only (an E record) and reached by a jump, so no frame is interposed +// CT_ENTRY_HAS("text") the same for every function name that contains the text +// CT_VOID("name") return never recorded ("-"): void, or a value that depends on timing +// CT_BOOL("name") C++ bool: only AL is defined ("b:0" / "b:1") +// CT_U32("name") low 32 bits recorded ("u:0x%08x"); only for values that cannot carry title data +// CT_HR("name") HRESULT ("hr:0x%08x") +// CT_HR_MOD("module", "prefix") HRESULT for every function of that module whose name starts with the prefix +// CT_NOT_HR("name") exempt from CT_HR_MOD +// Order of precedence: SKIP, then ENTRY, then the class: VOID, BOOL, U32, HR, NOT_HR, HR_MOD, else the default class +// ("p:0" for 0, "p:-1" for all ones in 64 or in the low 32 bits with the high half zero, "p:1" for anything else). + +// Called too often to record, or with a calling convention a thunk cannot carry (__chkstk takes its size in RAX). +CT_SKIP_HAS("chkstk") +CT_SKIP_HAS("alloca_probe") +// Language-specific exception handlers: called by the exception dispatcher, never by title code directly. +CT_SKIP_HAS("FrameHandler") +CT_SKIP_HAS("GSHandlerCheck") +CT_SKIP_HAS("_specific_handler") +CT_SKIP_MODULE("api-ms-win-crt-string-") +CT_SKIP_MODULE("api-ms-win-crt-math-") +CT_SKIP_MODULE("api-ms-win-crt-heap-") +CT_SKIP_MODULE("api-ms-win-crt-convert-") +CT_SKIP_MODULE("api-ms-win-crt-utility-") +CT_SKIP_MODULE("api-ms-win-crt-locale-") +CT_SKIP_MODULE("api-ms-win-crt-multibyte-") +CT_SKIP("EnterCriticalSection") +CT_SKIP("LeaveCriticalSection") +CT_SKIP("TryEnterCriticalSection") +CT_SKIP("AcquireSRWLockExclusive") +CT_SKIP("AcquireSRWLockShared") +CT_SKIP("ReleaseSRWLockExclusive") +CT_SKIP("ReleaseSRWLockShared") +CT_SKIP("TryAcquireSRWLockExclusive") +CT_SKIP("TryAcquireSRWLockShared") +CT_SKIP("TlsGetValue") +CT_SKIP("TlsSetValue") +CT_SKIP("FlsGetValue") +CT_SKIP("FlsSetValue") +CT_SKIP("GetLastError") +CT_SKIP("SetLastError") +CT_SKIP("GetCurrentThreadId") +CT_SKIP("GetCurrentThread") +CT_SKIP("GetCurrentProcess") +CT_SKIP("GetCurrentProcessId") +CT_SKIP("GetCurrentProcessorNumber") +CT_SKIP("QueryPerformanceCounter") +CT_SKIP("QueryPerformanceFrequency") +CT_SKIP("GetTickCount") +CT_SKIP("GetTickCount64") +CT_SKIP("GetSystemTimeAsFileTime") +CT_SKIP("GetSystemTimePreciseAsFileTime") +CT_SKIP("QueryUnbiasedInterruptTime") +CT_SKIP("Sleep") +CT_SKIP("SleepEx") +CT_SKIP("SwitchToThread") +CT_SKIP("InterlockedPushEntrySList") +CT_SKIP("InterlockedPopEntrySList") +CT_SKIP("InterlockedFlushSList") +CT_SKIP("HeapAlloc") +CT_SKIP("HeapFree") +CT_SKIP("HeapReAlloc") +CT_SKIP("HeapSize") +CT_SKIP("malloc") +CT_SKIP("free") +CT_SKIP("calloc") +CT_SKIP("realloc") +CT_SKIP("_aligned_malloc") +CT_SKIP("_aligned_free") +CT_SKIP("_aligned_realloc") +CT_SKIP("_msize") +CT_SKIP("memcpy") +CT_SKIP("memmove") +CT_SKIP("memset") +CT_SKIP("memcmp") +CT_SKIP("memchr") +CT_SKIP("strlen") +CT_SKIP("wcslen") +CT_SKIP("strcmp") +CT_SKIP("strncmp") +CT_SKIP("wcscmp") +CT_SKIP("wcsncmp") +CT_SKIP("_stricmp") +CT_SKIP("_strnicmp") +CT_SKIP("_wcsicmp") +CT_SKIP("_wcsnicmp") +CT_SKIP("strchr") +CT_SKIP("strrchr") +CT_SKIP("strstr") +CT_SKIP("wcschr") +CT_SKIP("wcsrchr") +CT_SKIP("wcsstr") +CT_SKIP("toupper") +CT_SKIP("tolower") +CT_SKIP("towupper") +CT_SKIP("towlower") +// SVML vector math (__vdecl_*) passes arguments in YMM registers, which the stubs do not preserve. +CT_SKIP_HAS("__vdecl") + +// No frame may sit between these and their caller (setjmp records the caller's frame), they never return, they +// start an unwind, or they take more variadic arguments than the wrap stub copies. +CT_ENTRY_HAS("setjmp") +CT_ENTRY_HAS("longjmp") +CT_ENTRY_HAS("printf") +CT_ENTRY_HAS("scanf") +CT_ENTRY("RaiseException") +CT_ENTRY("RaiseFailFastException") +CT_ENTRY("RtlRaiseException") +CT_ENTRY("_CxxThrowException") +CT_ENTRY("RtlUnwind") +CT_ENTRY("RtlUnwindEx") +CT_ENTRY("RtlRestoreContext") +CT_ENTRY("RtlCaptureContext") +CT_ENTRY("RtlCaptureContext2") +// Stack walks and caller lookups: a wrap frame would end the walk at the stub or return the stub's address. +CT_ENTRY("RtlCaptureStackBackTrace") +CT_ENTRY("CaptureStackBackTrace") +CT_ENTRY("RtlWalkFrameChain") +CT_ENTRY("RtlGetCallersAddress") +CT_ENTRY("exit") +CT_ENTRY("_exit") +CT_ENTRY("_Exit") +CT_ENTRY("quick_exit") +CT_ENTRY("abort") +CT_ENTRY("terminate") +CT_ENTRY("__std_terminate") +CT_ENTRY("_purecall") +CT_ENTRY("_invalid_parameter_noinfo_noreturn") +CT_ENTRY("ExitProcess") +CT_ENTRY("ExitThread") +CT_ENTRY("TerminateProcess") +CT_ENTRY("TerminateThread") +CT_ENTRY("FreeLibraryAndExitThread") +CT_ENTRY("_endthread") +CT_ENTRY("_endthreadex") + +// Void, or a result that depends on timing (waits). +CT_VOID("InitializeCriticalSection") +CT_VOID("DeleteCriticalSection") +CT_VOID("InitializeSRWLock") +CT_VOID("InitializeConditionVariable") +CT_VOID("WakeConditionVariable") +CT_VOID("WakeAllConditionVariable") +CT_VOID("InitializeSListHead") +CT_VOID("OutputDebugStringA") +CT_VOID("OutputDebugStringW") +CT_VOID("DebugBreak") +CT_VOID("GetSystemInfo") +CT_VOID("GetNativeSystemInfo") +CT_VOID("GetSystemTime") +CT_VOID("GetLocalTime") +CT_VOID("GetStartupInfoW") +CT_VOID("WaitForSingleObject") +CT_VOID("WaitForSingleObjectEx") +CT_VOID("WaitForMultipleObjects") +CT_VOID("WaitForMultipleObjectsEx") +CT_VOID("SleepConditionVariableCS") +CT_VOID("SleepConditionVariableSRW") +CT_VOID("WaitOnAddress") +CT_VOID("GetQueuedCompletionStatus") +CT_VOID("GetQueuedCompletionStatusEx") +CT_VOID("XAsyncCancel") +CT_VOID("XAsyncComplete") +CT_VOID("XTaskQueueCloseHandle") +CT_VOID("XUserCloseHandle") + +CT_BOOL("XTaskQueueDispatch") +CT_BOOL("XUserIsStoreUser") +CT_BOOL("XStoreIsLicenseValid") +CT_BOOL("XStoreProductsQueryHasMorePages") +CT_BOOL("XPackageIsPackagedProcess") +CT_BOOL("XGameRuntimeIsFeatureAvailable") + +// HRESULT: the rules of classify() in runtime/shims/registry.cpp (its comment names the reference page of each). +CT_HR("XGameRuntimeInitialize") +CT_HR("XGameEventWrite") +CT_HR("D3D12XboxCreateDevice") +CT_HR("D3D12XboxCreateSyntheticDevice") +CT_HR("D3D12GetDebugInterface") +CT_HR("D3D12EnableExperimentalFeatures") +CT_HR("DXGIGetDebugInterface1") +CT_HR("DXGIDeclareAdapterRemovalSupport") +CT_HR("XAudio2Create") +CT_HR("GameInputCreate") +CT_HR("DStorageGetFactory") +CT_HR("AcpHalAllocateShapeContexts") +CT_HR("AcpHalCreate") +CT_HR("AcpHalReleaseShapeContexts") +CT_HR("ApuAlloc") +CT_HR("ApuCreateHeap") +CT_HR_MOD("d3d12.dll", "D3D12Create") +CT_HR_MOD("d3d12.dll", "D3D12Serialize") +CT_HR_MOD("d3d12_xs.dll", "D3D12Create") +CT_HR_MOD("d3d12_xs.dll", "D3D12Serialize") +CT_HR_MOD("dxgi.dll", "CreateDXGIFactory") +CT_HR_MOD("chad.dll", "XDsp") +CT_HR_MOD("xapu.dll", "XApu") +CT_HR_MOD("xgameruntime.dll", "XAsync") +CT_HR_MOD("xgameruntime.dll", "XTaskQueue") +CT_HR_MOD("xgameruntime.dll", "XUser") +CT_HR_MOD("xgameruntime.dll", "XStore") +CT_HR_MOD("xgameruntime.dll", "XGameSave") +CT_HR_MOD("xgameruntime.dll", "XPackage") +CT_HR_MOD("xgameruntime.dll", "XGameUi") +CT_NOT_HR("XApuGetResultCount") +CT_NOT_HR("XTaskQueueGetCurrentProcessTaskQueue") +CT_NOT_HR("XTaskQueueSetCurrentProcessTaskQueue") +CT_NOT_HR("XTaskQueueUnregisterMonitor") +CT_NOT_HR("XTaskQueueUnregisterWaiter") +CT_NOT_HR("XUserCloseSignOutDeferralHandle") +CT_NOT_HR("XUserCompare") +CT_NOT_HR("XUserUnregisterForChangeEvent") +CT_NOT_HR("XUserUnregisterForDefaultAudioEndpointUtf16Changed") +CT_NOT_HR("XUserUnregisterForDeviceAssociationChanged") +CT_NOT_HR("XStoreCloseContextHandle") +CT_NOT_HR("XStoreCloseLicenseHandle") +CT_NOT_HR("XStoreCloseProductsQueryHandle") +CT_NOT_HR("XStoreUnregisterGameLicenseChanged") +CT_NOT_HR("XStoreUnregisterPackageLicenseLost") +CT_NOT_HR("XGameSaveCloseContainer") +CT_NOT_HR("XGameSaveCloseProvider") +CT_NOT_HR("XGameSaveCloseUpdate") +CT_NOT_HR("XPackageCloseInstallationMonitorHandle") +CT_NOT_HR("XPackageCloseMountHandle") +CT_NOT_HR("XPackageGetInstallationProgress") +CT_NOT_HR("XPackageUninstallPackage") +CT_NOT_HR("XPackageUnregisterInstallationProgressChanged") +CT_NOT_HR("XPackageUnregisterPackageInstalled") +CT_NOT_HR("XPackageUpdateInstallationMonitor")