//! Overrides of shared Windows APIs whose console meaning differs. //! //! Only the differences live here; everything else passes through to the //! host (see `HostPolicy`). #![allow(non_snake_case)] // Title code calls these through its import table, passing pointers the real // API would trust. #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::ffi::{CStr, c_void}; use crate::{HleModule, HostPolicy, hle_export, registry, runtime}; /// `GetModuleHandleW(NULL)` must return the title's image, not our exe. pub extern "system" fn GetModuleHandleW(name: *const u16) -> *mut c_void { if name.is_null() { return runtime::main_image().unwrap_or(0) as *mut c_void; } host::get_module_handle_w(name) } /// `GetModuleHandleA(NULL)` must return the title's image, not our exe. pub extern "system" fn GetModuleHandleA(name: *const u8) -> *mut c_void { if name.is_null() { return runtime::main_image().unwrap_or(0) as *mut c_void; } host::get_module_handle_a(name) } /// A title image's path is its original file, not our cache copy; /// `NULL` means the title's exe. pub extern "system" fn GetModuleFileNameW(module: *mut c_void, out: *mut u16, size: u32) -> u32 { let Some(path) = title_path(module) else { return host::get_module_file_name_w(module, out, size); }; let wide: Vec = path.encode_utf16().collect(); // SAFETY: the title passes a buffer of `size` characters. copy_truncated(&wide, unsafe { std::slice::from_raw_parts_mut(out, size as usize) }) } /// See [`GetModuleFileNameW`]. pub extern "system" fn GetModuleFileNameA(module: *mut c_void, out: *mut u8, size: u32) -> u32 { let Some(path) = title_path(module) else { return host::get_module_file_name_a(module, out, size); }; // SAFETY: the title passes a buffer of `size` bytes. copy_truncated(path.as_bytes(), unsafe { std::slice::from_raw_parts_mut(out, size as usize) }) } fn title_path(module: *mut c_void) -> Option { let base = if module.is_null() { runtime::main_image()? } else { module as usize }; Some(runtime::image_path(base)?.to_string_lossy().into_owned()) } /// `GetModuleFileName`'s contract: copy with a NUL; if it does not fit, /// truncate to the buffer, report `ERROR_INSUFFICIENT_BUFFER` and return /// the buffer size. fn copy_truncated(text: &[T], out: &mut [T]) -> u32 { let Some(room) = out.len().checked_sub(1) else { host::set_last_error(ERROR_INSUFFICIENT_BUFFER); return 0; }; let n = text.len().min(room); out[..n].copy_from_slice(&text[..n]); out[n] = T::default(); if n < text.len() { host::set_last_error(ERROR_INSUFFICIENT_BUFFER); return out.len() as u32; } n as u32 } const ERROR_INSUFFICIENT_BUFFER: u32 = 122; /// Console-only DLLs we implement load as a pseudo handle (titles load /// `xgameruntime.dll` this way); anything else loads on the host. pub extern "system" fn LoadLibraryExA( name: *const u8, file: *mut c_void, flags: u32, ) -> *mut c_void { if !name.is_null() { // SAFETY: the title passes a NUL-terminated file name. let text = unsafe { CStr::from_ptr(name.cast()) }.to_string_lossy(); if let Some(handle) = console_module(&text) { return handle; } } host::load_library_ex_a(name, file, flags) } /// See [`LoadLibraryExA`]. pub extern "system" fn LoadLibraryExW( name: *const u16, file: *mut c_void, flags: u32, ) -> *mut c_void { if !name.is_null() { // SAFETY: the title passes a NUL-terminated file name. let text = unsafe { let len = (0..).take_while(|&i| *name.add(i) != 0).count(); String::from_utf16_lossy(std::slice::from_raw_parts(name, len)) }; if let Some(handle) = console_module(&text) { return handle; } } host::load_library_ex_w(name, file, flags) } pub extern "system" fn LoadLibraryA(name: *const u8) -> *mut c_void { LoadLibraryExA(name, std::ptr::null_mut(), 0) } pub extern "system" fn LoadLibraryW(name: *const u16) -> *mut c_void { LoadLibraryExW(name, std::ptr::null_mut(), 0) } /// Looks up our implementations behind a pseudo handle; real modules go to /// the host. pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void { let Some(m) = registry().iter().find(|m| handle(m) == module) else { return host::get_proc_address(module, name); }; // Values below 0x10000 are ordinals; we export by name only. if (name as usize) < 0x1_0000 { tracing::warn!( module = m.name, ordinal = name as usize, "GetProcAddress by ordinal" ); return std::ptr::null_mut(); } // SAFETY: not an ordinal, so the title passes a NUL-terminated name. let name = unsafe { CStr::from_ptr(name.cast()) }.to_string_lossy(); match m.exports.iter().find(|e| e.name == name) { Some(e) => e.address as *mut c_void, None => { tracing::warn!(module = m.name, %name, "GetProcAddress: not implemented"); std::ptr::null_mut() } } } pub extern "system" fn FreeLibrary(module: *mut c_void) -> i32 { if registry().iter().any(|m| handle(m) == module) { return 1; } host::free_library(module) } /// Title debug output goes to our log (no debugger needs to be attached). pub extern "system" fn OutputDebugStringA(text: *const u8) { if !text.is_null() { // SAFETY: the title passes a NUL-terminated string. let text = unsafe { CStr::from_ptr(text.cast()) }.to_string_lossy(); tracing::info!(target: "title", "{}", text.trim_end()); } } /// See [`OutputDebugStringA`]. pub extern "system" fn OutputDebugStringW(text: *const u16) { if !text.is_null() { // SAFETY: the title passes a NUL-terminated string. let text = unsafe { let len = (0..).take_while(|&i| *text.add(i) != 0).count(); String::from_utf16_lossy(std::slice::from_raw_parts(text, len)) }; tracing::info!(target: "title", "{}", text.trim_end()); } } /// The CRT's `exit`, through which the title's entry point returns: logs /// the code and the caller, then exits on the host. pub extern "C" fn exit(code: i32) -> ! { tracing::warn!(code, from = %host::callers(), "title exits"); host::exit(code) } /// The CRT's `abort` (also reached from `terminate`): logged like [`exit`]. pub extern "C" fn abort() -> ! { tracing::error!(from = %host::callers(), "title aborts"); host::abort() } /// The CRT's `terminate` and the STL's invalid-argument exit: logged, then /// the host's `abort`. pub extern "C" fn terminate() -> ! { tracing::error!(from = %host::callers(), "title calls terminate"); host::abort() } /// See [`terminate`]. pub extern "C" fn _invalid_parameter_noinfo_noreturn() -> ! { tracing::error!(from = %host::callers(), "title passed an invalid parameter"); host::abort() } /// See [`exit`]; only the current process is logged. pub extern "system" fn TerminateProcess(process: *mut c_void, code: u32) -> i32 { if process as isize == -1 { tracing::warn!(code, from = %host::callers(), "title terminates the process"); } host::terminate_process(process, code) } /// The pseudo handle of one of our modules: its address, never a real image. fn handle(m: &HleModule) -> *mut c_void { m as *const HleModule as *mut c_void } fn console_module(path: &str) -> Option<*mut c_void> { let file = path.rsplit(['\\', '/']).next().unwrap_or(path); // DLLs the host has too are real host modules, whatever `--strict` says. if HostPolicy::default().allows(file) { return None; } let m = registry().iter().find(|m| m.serves(file))?; tracing::info!(dll = file, "loaded as a pseudo module"); Some(handle(m)) } pub(crate) fn module() -> HleModule { HleModule { name: "kernel", dlls: &[ "kernel32.dll", "kernelbase.dll", "api-ms-win-core-libraryloader-*", "api-ms-win-core-processthreads-*", "api-ms-win-core-debug-*", "api-ms-win-crt-runtime-*", ], exports: vec![ hle_export!(GetModuleHandleW), hle_export!(GetModuleHandleA), hle_export!(GetModuleFileNameW), hle_export!(GetModuleFileNameA), hle_export!(LoadLibraryExA), hle_export!(LoadLibraryExW), hle_export!(LoadLibraryA), hle_export!(LoadLibraryW), hle_export!(GetProcAddress), hle_export!(FreeLibrary), hle_export!(OutputDebugStringA), hle_export!(OutputDebugStringW), hle_export!(exit), hle_export!(abort), hle_export!(terminate), hle_export!(_invalid_parameter_noinfo_noreturn), hle_export!(TerminateProcess), ], } } #[cfg(windows)] mod host { use std::ffi::c_void; use windows_sys::Win32::Foundation::{FreeLibrary, SetLastError}; use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; use windows_sys::Win32::System::LibraryLoader::{ GetModuleFileNameA, GetModuleFileNameW, GetModuleHandleA, GetModuleHandleW, GetProcAddress, LoadLibraryExA, LoadLibraryExW, }; use windows_sys::Win32::System::Threading::TerminateProcess; unsafe extern "C" { #[link_name = "exit"] fn crt_exit(code: i32) -> !; #[link_name = "abort"] fn crt_abort() -> !; } // SAFETY (every function): forwarding the title's own arguments to the // host API of the same name. pub(super) fn get_module_handle_w(name: *const u16) -> *mut c_void { // SAFETY: see above. unsafe { GetModuleHandleW(name) } } pub(super) fn get_module_handle_a(name: *const u8) -> *mut c_void { // SAFETY: see above. unsafe { GetModuleHandleA(name) } } pub(super) fn get_module_file_name_w(module: *mut c_void, out: *mut u16, size: u32) -> u32 { // SAFETY: see above. unsafe { GetModuleFileNameW(module, out, size) } } pub(super) fn get_module_file_name_a(module: *mut c_void, out: *mut u8, size: u32) -> u32 { // SAFETY: see above. unsafe { GetModuleFileNameA(module, out, size) } } pub(super) fn set_last_error(code: u32) { // SAFETY: see above. unsafe { SetLastError(code) } } pub(super) fn load_library_ex_a(name: *const u8, file: *mut c_void, flags: u32) -> *mut c_void { // SAFETY: see above. unsafe { LoadLibraryExA(name, file, flags) } } pub(super) fn load_library_ex_w( name: *const u16, file: *mut c_void, flags: u32, ) -> *mut c_void { // SAFETY: see above. unsafe { LoadLibraryExW(name, file, flags) } } pub(super) fn get_proc_address(module: *mut c_void, name: *const u8) -> *mut c_void { // SAFETY: see above. unsafe { GetProcAddress(module, name) }.map_or(std::ptr::null_mut(), |f| f as *mut c_void) } pub(super) fn free_library(module: *mut c_void) -> i32 { // SAFETY: see above. unsafe { FreeLibrary(module) } } pub(super) fn exit(code: i32) -> ! { // SAFETY: see above. unsafe { crt_exit(code) } } pub(super) fn abort() -> ! { // SAFETY: see above. unsafe { crt_abort() } } pub(super) fn terminate_process(process: *mut c_void, code: u32) -> i32 { // SAFETY: see above. unsafe { TerminateProcess(process, code) } } /// Our caller's callers, as `module+rva`. pub(super) fn callers() -> String { let mut frames = [std::ptr::null_mut(); 12]; // SAFETY: fills at most `frames.len()` return addresses. let n = unsafe { RtlCaptureStackBackTrace( 2, frames.len() as u32, frames.as_mut_ptr(), std::ptr::null_mut(), ) }; let names: Vec<_> = frames[..usize::from(n)] .iter() .map(|&f| victory_loader::locate(f as usize)) .collect(); names.join(" < ") } } #[cfg(not(windows))] mod host { use std::ffi::c_void; pub(super) fn get_module_handle_w(_: *const u16) -> *mut c_void { std::ptr::null_mut() } pub(super) fn get_module_handle_a(_: *const u8) -> *mut c_void { std::ptr::null_mut() } pub(super) fn load_library_ex_a(_: *const u8, _: *mut c_void, _: u32) -> *mut c_void { std::ptr::null_mut() } pub(super) fn get_module_file_name_w(_: *mut c_void, _: *mut u16, _: u32) -> u32 { 0 } pub(super) fn get_module_file_name_a(_: *mut c_void, _: *mut u8, _: u32) -> u32 { 0 } pub(super) fn set_last_error(_: u32) {} pub(super) fn load_library_ex_w(_: *const u16, _: *mut c_void, _: u32) -> *mut c_void { std::ptr::null_mut() } pub(super) fn get_proc_address(_: *mut c_void, _: *const u8) -> *mut c_void { std::ptr::null_mut() } pub(super) fn free_library(_: *mut c_void) -> i32 { 0 } pub(super) fn exit(code: i32) -> ! { std::process::exit(code) } pub(super) fn abort() -> ! { std::process::abort() } pub(super) fn terminate_process(_: *mut c_void, code: u32) -> i32 { std::process::exit(code as i32) } pub(super) fn callers() -> String { String::new() } } #[cfg(test)] mod tests { use super::*; #[test] fn title_images_report_their_original_path() { let base = 0x7000_0000_0000; runtime::set_image_path(base, std::path::Path::new(r"C:\title\game.exe")); let module = base as *mut c_void; let mut buf = [0xFFFFu16; 32]; let n = GetModuleFileNameW(module, buf.as_mut_ptr(), buf.len() as u32); assert_eq!( String::from_utf16_lossy(&buf[..n as usize]), r"C:\title\game.exe" ); assert_eq!(buf[n as usize], 0); // Too small: truncated, NUL-terminated, the buffer size returned. let mut small = [0u8; 4]; assert_eq!(GetModuleFileNameA(module, small.as_mut_ptr(), 4), 4); assert_eq!(&small, &[b'C', b':', b'\\', 0]); } }