#![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::ffi::{CStr, c_char, c_void}; use crate::hle::{HleModule, HostPolicy, registry, runtime}; use crate::hle_export; 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; } match find_module(&wide(name), Ask::Probe) { ModuleLookup::Resolved(handle) => handle, ModuleLookup::Host(dll) => host::get_system_module_handle(&dll), } } 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; } match find_module(&narrow(name), Ask::Probe) { ModuleLookup::Resolved(handle) => handle, ModuleLookup::Host(dll) => host::get_system_module_handle(&dll), } } const FROM_ADDRESS: u32 = 4; fn title_module(flags: u32, name: Option, address: usize) -> Option<*mut c_void> { if flags & FROM_ADDRESS != 0 { return runtime::image_containing(address).map(|base| base as *mut c_void); } match name { None => runtime::main_image().map(|base| base as *mut c_void), Some(name) => match find_module(&name, Ask::Probe) { ModuleLookup::Resolved(handle) => Some(handle), ModuleLookup::Host(dll) => Some(host::get_system_module_handle(&dll)), }, } } fn give_module(out: *mut *mut c_void, module: *mut c_void) -> i32 { const ERROR_INVALID_PARAMETER: u32 = 87; if out.is_null() { host::set_last_error(ERROR_INVALID_PARAMETER); return 0; } unsafe { out.write(module) }; 1 } pub extern "system" fn GetModuleHandleExW( flags: u32, name: *const u16, out: *mut *mut c_void, ) -> i32 { let text = (flags & FROM_ADDRESS == 0 && !name.is_null()).then(|| wide(name)); match title_module(flags, text, name as usize) { Some(module) => give_module(out, module), None => host::get_module_handle_ex_w(flags, name, out), } } pub extern "system" fn GetModuleHandleExA( flags: u32, name: *const u8, out: *mut *mut c_void, ) -> i32 { let text = (flags & FROM_ADDRESS == 0 && !name.is_null()).then(|| narrow(name)); match title_module(flags, text, name as usize) { Some(module) => give_module(out, module), None => host::get_module_handle_ex_a(flags, name, out), } } fn narrow(text: *const u8) -> String { unsafe { CStr::from_ptr(text.cast()) } .to_string_lossy() .into_owned() } fn wide(text: *const u16) -> String { unsafe { let len = (0..).take_while(|&i| *text.add(i) != 0).count(); String::from_utf16_lossy(std::slice::from_raw_parts(text, len)) } } 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(); copy_truncated(&wide, title_buffer(out, size)) } 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); }; copy_truncated(path.as_bytes(), title_buffer(out, size)) } fn title_buffer<'a, T>(out: *mut T, size: u32) -> &'a mut [T] { if out.is_null() { return &mut []; } 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()) } 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; } host::set_last_error(ERROR_SUCCESS); n as u32 } const ERROR_SUCCESS: u32 = 0; const ERROR_INSUFFICIENT_BUFFER: u32 = 122; pub extern "system" fn LoadLibraryExA( name: *const u8, file: *mut c_void, flags: u32, ) -> *mut c_void { if name.is_null() { return host::load_null_library(file, flags); } match find_module(&narrow(name), Ask::library(flags)) { ModuleLookup::Resolved(handle) => handle, ModuleLookup::Host(dll) => host::load_system_library(&dll, file, flags), } } pub extern "system" fn LoadLibraryExW( name: *const u16, file: *mut c_void, flags: u32, ) -> *mut c_void { if name.is_null() { return host::load_null_library(file, flags); } match find_module(&wide(name), Ask::library(flags)) { ModuleLookup::Resolved(handle) => handle, ModuleLookup::Host(dll) => host::load_system_library(&dll, file, flags), } } #[derive(Clone, Copy, Debug, PartialEq)] enum Ask { Probe, Load, Data(u32), } impl Ask { fn library(flags: u32) -> Ask { if flags & (0x1 | 0x2 | 0x20 | 0x40) == 0 { Ask::Load } else { Ask::Data(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) } pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void { let module = if module.is_null() { runtime::main_image().unwrap_or(0) as *mut c_void } else { module }; let Some(m) = registry().iter().find(|m| handle(m) == module) else { if let Some(ours) = host_override(module, name) { return ours; } return title_export(module, name, host::get_proc_address(module, name)); }; if (name as usize) < 0x1_0000 { tracing::warn!( module = m.name, ordinal = name as usize, "GetProcAddress by ordinal" ); return std::ptr::null_mut(); } 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() } } } fn title_export(module: *mut c_void, name: *const u8, found: *mut c_void) -> *mut c_void { if found.is_null() || (name as usize) < 0x1_0000 { return found; } let Some(dll) = runtime::image_path(module as usize) .and_then(|p| p.file_name().map(|f| f.to_string_lossy().into_owned())) else { return found; }; let symbol = narrow(name); let address = super::bink::wrap(&dll, &symbol, found as usize); #[cfg(windows)] let address = super::fidelityfx::wrap(&dll, &symbol, address); address as *mut c_void } fn host_override(module: *mut c_void, name: *const u8) -> Option<*mut c_void> { if module.is_null() || runtime::image_path(module as usize).is_some() { return None; } let symbol = if (name as usize) < 0x1_0000 { format!("#{}", name as usize) } else { narrow(name) }; let mut path = [0u16; 260]; let len = host::get_module_file_name_w(module, path.as_mut_ptr(), path.len() as u32) as usize; let path = String::from_utf16_lossy(&path[..len.min(path.len())]); let file = path.rsplit('\\').next()?; let api_sets = HOST_API_SETS .iter() .filter(|(host, _)| host.eq_ignore_ascii_case(file)) .flat_map(|(_, sets)| sets.iter().copied()); std::iter::once(file) .chain(api_sets) .find_map(|dll| crate::hle::registry::lookup(dll, &symbol)) .map(|address| address as *mut c_void) } const HOST_API_SETS: &[(&str, &[&str])] = &[( "user32.dll", &["ext-ms-win-rtcore-ntuser-window-l1-1-0.dll"], )]; pub extern "system" fn FreeLibrary(module: *mut c_void) -> i32 { if registry().iter().any(|m| handle(m) == module) || runtime::image_path(module as usize).is_some() { return 1; } host::free_library(module) } pub extern "system" fn DisableThreadLibraryCalls(module: *mut c_void) -> i32 { if registry().iter().any(|m| handle(m) == module) { return 1; } host::disable_thread_library_calls(module) } pub extern "system" fn OutputDebugStringA(text: *const u8) { if !text.is_null() { let text = narrow(text); host::note_title_output(text.trim()); tracing::info!(target: "title", "{}", text.trim_end()); } } pub extern "system" fn OutputDebugStringW(text: *const u16) { if !text.is_null() { let text = wide(text); host::note_title_output(text.trim()); tracing::info!(target: "title", "{}", text.trim_end()); } } pub extern "C" fn exit(code: i32) -> ! { tracing::warn!(code, from = %host::callers(), "title exits"); host::exit(code) } pub extern "system" fn ExitProcess(code: u32) -> ! { tracing::warn!(code, from = %host::callers(), "title calls ExitProcess"); #[cfg(windows)] eonacat_xsbox_gpu::loader::exit_notices(); host::exit_process(code) } pub extern "C" fn abort() -> ! { tracing::error!(from = %host::callers(), "title aborts"); host::abort() } pub extern "C" fn terminate() -> ! { tracing::error!(from = %host::callers(), "title calls terminate"); host::abort() } pub extern "C" fn _invalid_parameter_noinfo_noreturn() -> ! { tracing::error!(from = %host::callers(), "title passed an invalid parameter"); host::abort() } static TITLE_FILTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); pub extern "system" fn SetUnhandledExceptionFilter(filter: usize) -> usize { host::set_unhandled_exception_filter(report_unhandled); TITLE_FILTER.swap(filter, std::sync::atomic::Ordering::AcqRel) } extern "system" fn report_unhandled(info: *const c_void) -> i32 { host::report_unhandled(info); match TITLE_FILTER.load(std::sync::atomic::Ordering::Acquire) { 0 => 0, filter => { type Filter = extern "system" fn(*const c_void) -> i32; let filter: Filter = unsafe { std::mem::transmute(filter) }; filter(info) } } } 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) } fn handle(m: &HleModule) -> *mut c_void { m as *const HleModule as *mut c_void } enum ModuleLookup { Resolved(*mut c_void), Host(String), } fn system32_dir() -> Option { static DIR: std::sync::OnceLock> = std::sync::OnceLock::new(); DIR.get_or_init(|| { let name: Vec = "kernel32.dll".encode_utf16().chain([0]).collect(); let module = host::get_module_handle_w(name.as_ptr()); if module.is_null() { return None; } let mut buf = [0u16; 512]; let len = host::get_module_file_name_w(module, buf.as_mut_ptr(), buf.len() as u32) as usize; if len == 0 || len >= buf.len() { return None; } let full = String::from_utf16_lossy(&buf[..len]); let full = full.strip_prefix(r"\\?\").unwrap_or(&full); let (dir, _) = full.rsplit_once('\\')?; Some(dir.trim_end_matches('\\').to_ascii_lowercase()) }) .clone() } fn is_allowed_host_path(path: &str) -> bool { if crate::hle::host::is_bare_dll_name(path) { return true; } let trimmed = path.strip_prefix(r"\\?\").unwrap_or(path); if trimmed.starts_with(['\\', '/']) { return false; } let Some((dir, name)) = trimmed.rsplit_once(['\\', '/']) else { return false; }; if !crate::hle::host::is_bare_dll_name(name) { return false; } let normalized_dir = dir.replace('/', "\\"); let normalized_dir = normalized_dir.trim_end_matches('\\'); if normalized_dir .split('\\') .any(|part| part.is_empty() || part == "." || part == "..") { return false; } system32_dir().is_some_and(|sys32| normalized_dir.eq_ignore_ascii_case(&sys32)) } fn find_module(path: &str, ask: Ask) -> ModuleLookup { let file = dll_file(path); match resolve(&file, ask, runtime::title_dir().as_deref()) { Found::Host if !is_allowed_host_path(path) => answer(path, Found::Refused), found => answer(&file, found), } } fn dll_file(path: &str) -> String { let file = path.rsplit(['\\', '/']).next().unwrap_or(path); if file.contains('.') { file.to_owned() } else { format!("{file}.dll") } } #[derive(Debug, PartialEq)] enum Found { Module(*mut c_void), Host, NotLoaded, DataFile(std::path::PathBuf, u32), Refused, } fn resolve(file: &str, ask: Ask, title_dir: Option<&std::path::Path>) -> Found { let load = ask == Ask::Load; if load { match runtime::load_title_dll(file) { Ok(Some(base)) => return Found::Module(base as *mut c_void), Ok(None) => {} Err(error) => { tracing::error!(dll = file, %error, "mapping a title DLL failed"); host::set_last_error(ERROR_MOD_NOT_FOUND); return Found::Module(std::ptr::null_mut()); } } } if let Some(base) = runtime::image_named(file) { return Found::Module(base as *mut c_void); } let host_dll = HostPolicy::default().allows(file); if !host_dll && let Some(m) = registry().iter().find(|m| m.serves(file)) { if load { tracing::info!(dll = file, "loaded as a pseudo module"); } return Found::Module(handle(m)); } if host_dll { return Found::Host; } let title_file = title_dir .map(|dir| dir.join(file)) .filter(|path| path.is_file()); match (ask, title_file) { (Ask::Probe, Some(_)) => return Found::NotLoaded, (Ask::Data(flags), Some(path)) => return Found::DataFile(path, flags), _ => {} } Found::Refused } fn answer(file: &str, found: Found) -> ModuleLookup { match found { Found::Module(module) => return ModuleLookup::Resolved(module), Found::Host => return ModuleLookup::Host(file.to_owned()), Found::DataFile(path, flags) => { tracing::debug!(dll = file, flags, "a title DLL loaded as data by the host"); let (path, none) = (wide_path(&path), std::ptr::null_mut()); return ModuleLookup::Resolved(host::load_library_ex_w(path.as_ptr(), none, flags)); } Found::NotLoaded => tracing::debug!(dll = file, "a title DLL not loaded yet"), Found::Refused => refuse(file), } host::set_last_error(ERROR_MOD_NOT_FOUND); ModuleLookup::Resolved(std::ptr::null_mut()) } fn wide_path(path: &std::path::Path) -> Vec { path.to_string_lossy() .encode_utf16() .chain(Some(0)) .collect() } static REFUSED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); fn refuse(file: &str) { let file = file.to_ascii_lowercase(); let mut refused = REFUSED.lock().unwrap_or_else(|e| e.into_inner()); if !refused.contains(&file) { tracing::info!(dll = file, "a host DLL outside the host policy: refused"); refused.push(file); } } const ERROR_MOD_NOT_FOUND: u32 = 126; struct TitleArgv { count: std::cell::UnsafeCell, list: std::cell::UnsafeCell<*mut *mut c_char>, } unsafe impl Send for TitleArgv {} unsafe impl Sync for TitleArgv {} fn title_argv(program: &str, args: &[String]) -> TitleArgv { let list: Vec<*mut c_char> = std::iter::once(program) .chain(args.iter().map(String::as_str)) .filter_map(|a| std::ffi::CString::new(a).ok()) .map(std::ffi::CString::into_raw) .collect(); let count = list.len() as i32; let list: Box<[*mut c_char]> = list.into_iter().chain(Some(std::ptr::null_mut())).collect(); TitleArgv { count: count.into(), list: Box::leak(list).as_mut_ptr().into(), } } fn argv() -> &'static TitleArgv { static ARGV: std::sync::OnceLock = std::sync::OnceLock::new(); ARGV.get_or_init(|| { let program = std::env::args_os().next().unwrap_or_default(); let args = runtime::title_args(); tracing::info!(?args, "the title's arguments"); title_argv(&program.to_string_lossy(), args) }) } pub extern "C" fn __p___argc() -> *mut i32 { argv().count.get() } pub extern "C" fn __p___argv() -> *mut *mut *mut c_char { argv().list.get() } fn quote_arg(arg: &str, line: &mut String) { if !arg.is_empty() && !arg.contains([' ', '\t', '\n', '\x0b', '"']) { line.push_str(arg); return; } line.push('"'); let mut slashes = 0; for c in arg.chars() { match c { '\\' => slashes += 1, '"' => { line.extend(std::iter::repeat_n('\\', slashes * 2 + 1)); slashes = 0; } _ => { line.extend(std::iter::repeat_n('\\', slashes)); slashes = 0; } } if c != '\\' { line.push(c); } } line.extend(std::iter::repeat_n('\\', slashes * 2)); line.push('"'); } fn command_line(program: &str, args: &[String]) -> String { let mut line = if program.contains([' ', '\t']) { format!("\"{program}\"") } else { program.to_owned() }; for arg in args { line.push(' '); quote_arg(arg, &mut line); } line } fn title_command_line() -> &'static (std::ffi::CString, Vec) { static LINE: std::sync::OnceLock<(std::ffi::CString, Vec)> = std::sync::OnceLock::new(); LINE.get_or_init(|| { let program = std::env::args_os().next().unwrap_or_default(); let line = command_line(&program.to_string_lossy(), runtime::title_args()); tracing::info!(%line, "the title's command line"); let wide: Vec = line.encode_utf16().chain(Some(0)).collect(); (host::ansi(&wide), wide) }) } pub extern "system" fn GetCommandLineA() -> *const c_char { title_command_line().0.as_ptr() } pub extern "system" fn GetCommandLineW() -> *const u16 { title_command_line().1.as_ptr() } fn title_priority(asked: i32, raise: bool, cap: bool) -> i32 { const IDLE: i32 = -15; const LOWEST: i32 = -2; const BELOW_NORMAL: i32 = -1; const NORMAL: i32 = 0; const TIME_CRITICAL: i32 = 15; match asked { IDLE..=LOWEST if raise => BELOW_NORMAL, 1..=TIME_CRITICAL if cap => NORMAL, other => other, } } fn priority_rules( as_set: bool, startup: Option, elapsed: std::time::Duration, ) -> (bool, bool) { match startup { None => (!as_set, false), Some(window) => (!as_set || elapsed < window, true), } } fn startup_window() -> Option { static WINDOW: std::sync::OnceLock> = std::sync::OnceLock::new(); *WINDOW.get_or_init(|| { let window = std::env::var("EONACAT_XS_STARTUP_PRIORITIES") .ok()? .trim() .parse::() .ok() .filter(|s| s.is_finite() && *s > 0.0) .map(std::time::Duration::from_secs_f64)?; tracing::info!( seconds = window.as_secs_f64(), "title threads raised at startup, and held at normal at most" ); std::thread::Builder::new() .name("startup-priorities".into()) .spawn(move || { std::thread::sleep(window.saturating_sub(run_time())); give_back_startup_raises(); }) .ok(); Some(window) }) } fn run_time() -> std::time::Duration { use windows_sys::Win32::Foundation::FILETIME; use windows_sys::Win32::System::SystemInformation::GetSystemTimeAsFileTime; use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes}; let ticks = |t: FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime); let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0, }; let [mut created, mut exited, mut kernel, mut user, mut now] = [zero; 5]; let ok = unsafe { GetSystemTimeAsFileTime(&mut now); GetProcessTimes( GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user, ) } != 0; if !ok { return std::time::Duration::ZERO; } std::time::Duration::from_nanos(ticks(now).saturating_sub(ticks(created)) * 100) } static STARTUP_RAISED: std::sync::Mutex>> = std::sync::Mutex::new(Some(Vec::new())); fn give_back_startup_raises() { use windows_sys::Win32::Foundation::CloseHandle; let Some(raised) = STARTUP_RAISED .lock() .unwrap_or_else(|e| e.into_inner()) .take() else { return; }; let threads = raised.len(); for (thread, asked) in raised { unsafe { windows_sys::Win32::System::Threading::SetThreadPriority(thread as _, asked); CloseHandle(thread as _); } } tracing::info!( threads, at = run_time().as_secs_f64(), "startup raise of title threads ended" ); } pub extern "system" fn SetThreadPriority(thread: *mut c_void, priority: i32) -> i32 { use windows_sys::Win32::Foundation::{DUPLICATE_SAME_ACCESS, DuplicateHandle}; use windows_sys::Win32::System::Threading::GetCurrentProcess; static AS_SET: std::sync::OnceLock = std::sync::OnceLock::new(); static ASKED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); let as_set = *AS_SET .get_or_init(|| std::env::var_os("EONACAT_XS_TITLE_PRIORITIES").is_some_and(|v| v == "0")); let startup = startup_window(); let (mut raise, cap) = priority_rules(as_set, startup, run_time()); if raise && as_set && title_priority(priority, true, cap) != title_priority(priority, false, cap) { let mut raised = STARTUP_RAISED.lock().unwrap_or_else(|e| e.into_inner()); let mut kept = std::ptr::null_mut(); raise = raised.is_some() && unsafe { DuplicateHandle( GetCurrentProcess(), thread, GetCurrentProcess(), &mut kept, 0, 0, DUPLICATE_SAME_ACCESS, ) } != 0; if let Some(raised) = raised.as_mut().filter(|_| raise) { raised.push((kept as usize, priority)); } } let given = title_priority(priority, raise, cap); let mut asked = ASKED.lock().unwrap_or_else(|e| e.into_inner()); if !asked.contains(&priority) { asked.push(priority); tracing::info!( asked = priority, given, "a title thread asks for this priority (logged once per value)" ); } drop(asked); unsafe { windows_sys::Win32::System::Threading::SetThreadPriority(thread, given) } } #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum TitleAffinity { Fast, Free, Keep, } fn title_affinity() -> TitleAffinity { static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); *MODE.get_or_init(|| { match std::env::var("EONACAT_XS_TITLE_AFFINITY") .ok() .as_deref() .map(str::trim) { Some("free") => TitleAffinity::Free, Some("keep") => TitleAffinity::Keep, _ => TitleAffinity::Fast, } }) } #[cfg(windows)] fn fast_first() -> Option<(&'static [u8], usize)> { static ORDER: std::sync::OnceLock, usize)>> = std::sync::OnceLock::new(); ORDER .get_or_init(|| { use windows_sys::Win32::System::SystemInformation::{ GetSystemCpuSetInformation, SYSTEM_CPU_SET_INFORMATION, }; use windows_sys::Win32::System::Threading::GetCurrentProcess; let mut bytes = 0u32; unsafe { GetSystemCpuSetInformation( std::ptr::null_mut(), 0, &mut bytes, GetCurrentProcess(), 0, ) }; let mut buffer = vec![0u64; (bytes as usize).div_ceil(8).max(1)]; let ok = unsafe { GetSystemCpuSetInformation( buffer.as_mut_ptr().cast(), bytes, &mut bytes, GetCurrentProcess(), 0, ) }; if ok == 0 { return None; } let mut cores = Vec::new(); let mut at = 0usize; while at + size_of::() <= bytes as usize { let info = unsafe { &*(buffer .as_ptr() .cast::() .add(at) .cast::()) }; if info.Size == 0 { break; } let set = unsafe { &info.Anonymous.CpuSet }; if set.Group == 0 { cores.push((set.LogicalProcessorIndex, set.EfficiencyClass)); } at += info.Size as usize; } Some((order_fast_first(&cores), fastest(&cores))) }) .as_ref() .map(|(order, fast)| (order.as_slice(), *fast)) } fn order_fast_first(cores: &[(u8, u8)]) -> Vec { let mut cores = cores.to_vec(); cores.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); cores.into_iter().map(|c| c.0).collect() } fn fastest(cores: &[(u8, u8)]) -> usize { let top = cores.iter().map(|c| c.1).max(); cores.iter().filter(|c| Some(c.1) == top).count() } fn title_slow_spread() -> bool { #[cfg(all(windows, any(feature = "ab", feature = "diagnostics")))] if let Some(on) = eonacat_xsbox_gpu::ab_pick("EONACAT_XS_TITLE_SLOW_SPREAD") { return on; } static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("EONACAT_XS_TITLE_SLOW_SPREAD").is_some_and(|v| v == "1")) } #[cfg(all(windows, any(feature = "ab", feature = "diagnostics")))] static ASKED_PROCESSORS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); #[cfg(all(windows, any(feature = "ab", feature = "diagnostics")))] fn note_asked_processors(thread: *mut c_void, mask: usize) { use windows_sys::Win32::Foundation::{DUPLICATE_SAME_ACCESS, DuplicateHandle}; use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetThreadId}; static HUNG: std::sync::Once = std::sync::Once::new(); HUNG.call_once(|| eonacat_xsbox_gpu::ab_on_change(place_again)); let id = unsafe { GetThreadId(thread) }; if id == 0 { return; } let mut asked = ASKED_PROCESSORS.lock().unwrap_or_else(|e| e.into_inner()); if let Some(entry) = asked.iter_mut().find(|e| e.0 == id) { entry.2 = mask; return; } let mut kept = std::ptr::null_mut(); let ok = unsafe { DuplicateHandle(GetCurrentProcess(), thread, GetCurrentProcess(), &mut kept, 0, 0, DUPLICATE_SAME_ACCESS) } != 0; if ok { asked.push((id, kept as usize, mask)); } } #[cfg(all(windows, any(feature = "ab", feature = "diagnostics")))] fn place_again(switch: &str, spread: bool) { use windows_sys::Win32::System::SystemInformation::GROUP_AFFINITY; use windows_sys::Win32::System::Threading::SetThreadGroupAffinity as host_set; if switch != "EONACAT_XS_TITLE_SLOW_SPREAD" { return; } let Some((order, fast)) = fast_first() else { return; }; let asked = ASKED_PROCESSORS.lock().unwrap_or_else(|e| e.into_inner()); let mut placed = 0; for &(_, thread, mask) in asked.iter() { let mapped = if spread { spread_mask(mask, order, fast) } else { remap_mask(mask, order) }; if mapped == 0 { continue; } let affinity = GROUP_AFFINITY { Mask: mapped, Group: 0, Reserved: [0; 3] }; placed += usize::from(unsafe { host_set(thread as _, &affinity, std::ptr::null_mut()) } != 0); } tracing::info!(spread, threads = asked.len(), placed, "the title's threads placed again (EONACAT_XS_TITLE_SLOW_SPREAD)"); } fn spread_mask(mask: usize, order: &[u8], fast: usize) -> usize { if mask.count_ones() < 2 { return remap_mask(mask, order); } let slow = order .iter() .skip(fast) .filter(|&&p| u32::from(p) < usize::BITS) .fold(0usize, |m, &p| m | 1 << p); let mut out = 0usize; for i in 0..usize::BITS as usize { if mask & (1 << i) == 0 { continue; } out |= if i >= fast && i < order.len() { slow } else { remap_mask(1 << i, order) }; } out } fn remap_mask(mask: usize, order: &[u8]) -> usize { let mut out = 0usize; for i in 0..usize::BITS as usize { if mask & (1 << i) == 0 { continue; } let to = order.get(i).map_or(i, |&p| p as usize); if to < usize::BITS as usize { out |= 1 << to; } } out } #[cfg(windows)] pub extern "system" fn SetThreadGroupAffinity( thread: *mut c_void, affinity: *const windows_sys::Win32::System::SystemInformation::GROUP_AFFINITY, previous: *mut windows_sys::Win32::System::SystemInformation::GROUP_AFFINITY, ) -> i32 { use windows_sys::Win32::System::Threading::{ GetThreadGroupAffinity, SetThreadGroupAffinity as host_set, }; let mode = title_affinity(); if affinity.is_null() || mode == TitleAffinity::Keep { return unsafe { host_set(thread, affinity, previous) }; } if mode == TitleAffinity::Free { if !previous.is_null() { return unsafe { GetThreadGroupAffinity(thread, previous) }; } return 1; } let mut asked = unsafe { *affinity }; if asked.Group == 0 && let Some((order, fast)) = fast_first() { let mapped = if title_slow_spread() { spread_mask(asked.Mask, order, fast) } else { remap_mask(asked.Mask, order) }; static SAID: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); if said.len() < 64 && !said.contains(&asked.Mask) { said.push(asked.Mask); tracing::info!( asked = format_args!("{:#x}", asked.Mask), given = format_args!("{mapped:#x}"), "a title thread asks for these processors (logged once per mask)" ); } drop(said); #[cfg(any(feature = "ab", feature = "diagnostics"))] note_asked_processors(thread, asked.Mask); if mapped != 0 { asked.Mask = mapped; } } unsafe { host_set(thread, &asked, previous) } } 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-processtopology-*", "api-ms-win-core-debug-*", "api-ms-win-core-errorhandling-*", "api-ms-win-core-processenvironment-*", "api-ms-win-crt-runtime-*", ], exports: vec![ hle_export!(__p___argc), hle_export!(__p___argv), hle_export!(GetCommandLineA), hle_export!(GetCommandLineW), hle_export!(GetModuleHandleW), hle_export!(GetModuleHandleA), hle_export!(GetModuleHandleExW), hle_export!(GetModuleHandleExA), 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!(DisableThreadLibraryCalls), hle_export!(OutputDebugStringA), hle_export!(OutputDebugStringW), hle_export!(exit), hle_export!(ExitProcess), hle_export!(abort), hle_export!(terminate), hle_export!(_invalid_parameter_noinfo_noreturn), hle_export!(TerminateProcess), hle_export!(SetUnhandledExceptionFilter), hle_export!(SetThreadPriority), #[cfg(windows)] hle_export!(SetThreadGroupAffinity), ], } } #[cfg(feature = "diagnostics")] pub(crate) fn callers() -> String { host::callers() } #[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::{ DisableThreadLibraryCalls, GetModuleFileNameA, GetModuleFileNameW, GetModuleHandleW, GetProcAddress, LOAD_LIBRARY_SEARCH_APPLICATION_DIR, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LOAD_LIBRARY_SEARCH_USER_DIRS, LOAD_WITH_ALTERED_SEARCH_PATH, LoadLibraryExW, GetModuleHandleExA, GetModuleHandleExW, }; use windows_sys::Win32::System::Threading::{ExitProcess, TerminateProcess}; const UNSAFE_SEARCH_FLAGS: u32 = LOAD_WITH_ALTERED_SEARCH_PATH | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_APPLICATION_DIR | LOAD_LIBRARY_SEARCH_USER_DIRS | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS; unsafe extern "C" { #[link_name = "exit"] fn crt_exit(code: i32) -> !; #[link_name = "abort"] fn crt_abort() -> !; } pub(super) fn get_module_handle_w(name: *const u16) -> *mut c_void { unsafe { GetModuleHandleW(name) } } pub(super) fn get_system_module_handle(dll: &str) -> *mut c_void { if !crate::hle::host::is_bare_dll_name(dll) { set_last_error(super::ERROR_MOD_NOT_FOUND); return std::ptr::null_mut(); } let wide: Vec = dll.encode_utf16().chain([0]).collect(); unsafe { GetModuleHandleW(wide.as_ptr()) } } pub(super) fn get_module_handle_ex_w(flags: u32, name: *const u16, out: *mut *mut c_void) -> i32 { unsafe { GetModuleHandleExW(flags, name, out.cast()) } } pub(super) fn get_module_handle_ex_a(flags: u32, name: *const u8, out: *mut *mut c_void) -> i32 { unsafe { GetModuleHandleExA(flags, name, out.cast()) } } pub(super) fn get_module_file_name_w(module: *mut c_void, out: *mut u16, size: u32) -> u32 { unsafe { GetModuleFileNameW(module, out, size) } } pub(super) fn load_library_ex_w(name: *const u16, file: *mut c_void, flags: u32) -> *mut c_void { unsafe { windows_sys::Win32::System::LibraryLoader::LoadLibraryExW(name, file, flags) } } pub(super) fn get_module_file_name_a(module: *mut c_void, out: *mut u8, size: u32) -> u32 { unsafe { GetModuleFileNameA(module, out, size) } } pub(super) fn set_last_error(code: u32) { unsafe { SetLastError(code) } } pub(super) fn load_null_library(file: *mut c_void, flags: u32) -> *mut c_void { unsafe { LoadLibraryExW(std::ptr::null(), file, flags) } } pub(super) fn load_system_library(dll: &str, file: *mut c_void, flags: u32) -> *mut c_void { if !crate::hle::host::is_bare_dll_name(dll) { set_last_error(super::ERROR_MOD_NOT_FOUND); return std::ptr::null_mut(); } let wide: Vec = dll.encode_utf16().chain([0]).collect(); let flags = (flags & !UNSAFE_SEARCH_FLAGS) | LOAD_LIBRARY_SEARCH_SYSTEM32; unsafe { LoadLibraryExW(wide.as_ptr(), file, flags) } } pub(super) fn get_proc_address(module: *mut c_void, name: *const u8) -> *mut c_void { 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 { unsafe { FreeLibrary(module) } } pub(super) fn disable_thread_library_calls(module: *mut c_void) -> i32 { match eonacat_xsbox_gpu::loader::disable_thread_calls(module as usize) { Some(done) => i32::from(done), None => unsafe { DisableThreadLibraryCalls(module) }, } } pub(super) fn exit(code: i32) -> ! { unsafe { crt_exit(code) } } pub(super) fn exit_process(code: u32) -> ! { unsafe { ExitProcess(code) } } pub(super) fn abort() -> ! { unsafe { crt_abort() } } pub(super) fn terminate_process(process: *mut c_void, code: u32) -> i32 { unsafe { TerminateProcess(process, code) } } pub(super) fn set_unhandled_exception_filter(filter: extern "system" fn(*const c_void) -> i32) { unsafe { windows_sys::Win32::System::Diagnostics::Debug::SetUnhandledExceptionFilter( std::mem::transmute::< extern "system" fn(*const c_void) -> i32, windows_sys::Win32::System::Diagnostics::Debug::LPTOP_LEVEL_EXCEPTION_FILTER, >(filter), ) }; } pub(super) fn report_unhandled(info: *const c_void) { unsafe { eonacat_xsbox_gpu::loader::report_unhandled(info.cast()) }; } pub(super) fn note_title_output(line: &str) { eonacat_xsbox_gpu::loader::note_title_output(line); } pub(super) fn ansi(wide: &[u16]) -> std::ffi::CString { use windows_sys::Win32::Globalization::{CP_ACP, WideCharToMultiByte}; let (null, no_default) = (std::ptr::null(), std::ptr::null_mut()); let bytes = unsafe { let size_only = std::ptr::null_mut(); let len = WideCharToMultiByte(CP_ACP, 0, wide.as_ptr(), -1, size_only, 0, null, no_default); let mut bytes = vec![0u8; len.max(1) as usize]; let len = WideCharToMultiByte( CP_ACP, 0, wide.as_ptr(), -1, bytes.as_mut_ptr(), bytes.len() as i32, null, no_default, ); bytes.truncate(len.max(1) as usize - 1); bytes }; std::ffi::CString::new(bytes).unwrap_or_default() } pub(super) fn callers() -> String { let mut frames = [std::ptr::null_mut(); 12]; 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| eonacat_xsbox_gpu::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_ex_w(_: u32, _: *const u16, _: *mut *mut c_void) -> i32 { 0 } pub(super) fn get_module_handle_ex_a(_: u32, _: *const u8, _: *mut *mut c_void) -> i32 { 0 } pub(super) fn get_system_module_handle(_: &str) -> *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 load_library_ex_w(_: *const u16, _: *mut c_void, _: u32) -> *mut c_void { std::ptr::null_mut() } 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_null_library(_: *mut c_void, _: u32) -> *mut c_void { std::ptr::null_mut() } pub(super) fn load_system_library(_: &str, _: *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 disable_thread_library_calls(_: *mut c_void) -> i32 { 0 } pub(super) fn exit(code: i32) -> ! { std::process::exit(code) } pub(super) fn exit_process(code: u32) -> ! { std::process::exit(code as i32) } 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 set_unhandled_exception_filter(_: extern "system" fn(*const c_void) -> i32) {} pub(super) fn report_unhandled(_: *const c_void) {} pub(super) fn note_title_output(_: &str) {} pub(super) fn ansi(wide: &[u16]) -> std::ffi::CString { let len = wide.iter().position(|&c| c == 0).unwrap_or(wide.len()); std::ffi::CString::new(String::from_utf16_lossy(&wide[..len])).unwrap_or_default() } pub(super) fn callers() -> String { String::new() } }