kernel.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. //! Overrides of shared Windows APIs whose console meaning differs.
  2. //!
  3. //! Only the differences live here; everything else passes through to the
  4. //! host (see `HostPolicy`).
  5. #![allow(non_snake_case)]
  6. // Title code calls these through its import table, passing pointers the real
  7. // API would trust.
  8. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  9. use std::ffi::{CStr, c_char, c_void};
  10. use crate::{HleModule, HostPolicy, hle_export, registry, runtime};
  11. /// `GetModuleHandleW(NULL)` must return the title's image, not our exe;
  12. /// title images and our console modules are found by name.
  13. pub extern "system" fn GetModuleHandleW(name: *const u16) -> *mut c_void {
  14. if name.is_null() {
  15. return runtime::main_image().unwrap_or(0) as *mut c_void;
  16. }
  17. find_module(&wide(name), false).unwrap_or_else(|| host::get_module_handle_w(name))
  18. }
  19. /// See [`GetModuleHandleW`].
  20. pub extern "system" fn GetModuleHandleA(name: *const u8) -> *mut c_void {
  21. if name.is_null() {
  22. return runtime::main_image().unwrap_or(0) as *mut c_void;
  23. }
  24. find_module(&narrow(name), false).unwrap_or_else(|| host::get_module_handle_a(name))
  25. }
  26. /// A NUL-terminated string from the title.
  27. fn narrow(text: *const u8) -> String {
  28. // SAFETY: the title passes a NUL-terminated string.
  29. unsafe { CStr::from_ptr(text.cast()) }
  30. .to_string_lossy()
  31. .into_owned()
  32. }
  33. /// See [`narrow`].
  34. fn wide(text: *const u16) -> String {
  35. // SAFETY: the title passes a NUL-terminated string.
  36. unsafe {
  37. let len = (0..).take_while(|&i| *text.add(i) != 0).count();
  38. String::from_utf16_lossy(std::slice::from_raw_parts(text, len))
  39. }
  40. }
  41. /// A title image's path is its original file, not our cache copy;
  42. /// `NULL` means the title's exe.
  43. pub extern "system" fn GetModuleFileNameW(module: *mut c_void, out: *mut u16, size: u32) -> u32 {
  44. let Some(path) = title_path(module) else {
  45. return host::get_module_file_name_w(module, out, size);
  46. };
  47. let wide: Vec<u16> = path.encode_utf16().collect();
  48. // SAFETY: the title passes a buffer of `size` characters.
  49. copy_truncated(&wide, unsafe {
  50. std::slice::from_raw_parts_mut(out, size as usize)
  51. })
  52. }
  53. /// See [`GetModuleFileNameW`].
  54. pub extern "system" fn GetModuleFileNameA(module: *mut c_void, out: *mut u8, size: u32) -> u32 {
  55. let Some(path) = title_path(module) else {
  56. return host::get_module_file_name_a(module, out, size);
  57. };
  58. // SAFETY: the title passes a buffer of `size` bytes.
  59. copy_truncated(path.as_bytes(), unsafe {
  60. std::slice::from_raw_parts_mut(out, size as usize)
  61. })
  62. }
  63. fn title_path(module: *mut c_void) -> Option<String> {
  64. let base = if module.is_null() {
  65. runtime::main_image()?
  66. } else {
  67. module as usize
  68. };
  69. Some(runtime::image_path(base)?.to_string_lossy().into_owned())
  70. }
  71. /// `GetModuleFileName`'s contract: copy with a NUL; if it does not fit,
  72. /// truncate to the buffer, report `ERROR_INSUFFICIENT_BUFFER` and return
  73. /// the buffer size.
  74. fn copy_truncated<T: Copy + Default>(text: &[T], out: &mut [T]) -> u32 {
  75. let Some(room) = out.len().checked_sub(1) else {
  76. host::set_last_error(ERROR_INSUFFICIENT_BUFFER);
  77. return 0;
  78. };
  79. let n = text.len().min(room);
  80. out[..n].copy_from_slice(&text[..n]);
  81. out[n] = T::default();
  82. if n < text.len() {
  83. host::set_last_error(ERROR_INSUFFICIENT_BUFFER);
  84. return out.len() as u32;
  85. }
  86. n as u32
  87. }
  88. const ERROR_INSUFFICIENT_BUFFER: u32 = 122;
  89. /// Console-only DLLs we implement load as a pseudo handle (titles load
  90. /// `xgameruntime.dll` this way), the title's DLLs as the images we map
  91. /// (on first use if nothing imports them); anything else loads on the host.
  92. pub extern "system" fn LoadLibraryExA(
  93. name: *const u8,
  94. file: *mut c_void,
  95. flags: u32,
  96. ) -> *mut c_void {
  97. if !name.is_null()
  98. && let Some(handle) = find_module(&narrow(name), runs_code(flags))
  99. {
  100. return handle;
  101. }
  102. host::load_library_ex_a(name, file, flags)
  103. }
  104. /// See [`LoadLibraryExA`].
  105. pub extern "system" fn LoadLibraryExW(
  106. name: *const u16,
  107. file: *mut c_void,
  108. flags: u32,
  109. ) -> *mut c_void {
  110. if !name.is_null()
  111. && let Some(handle) = find_module(&wide(name), runs_code(flags))
  112. {
  113. return handle;
  114. }
  115. host::load_library_ex_w(name, file, flags)
  116. }
  117. /// False for loads as data or resources (`DONT_RESOLVE_DLL_REFERENCES`,
  118. /// `LOAD_LIBRARY_AS_DATAFILE(_EXCLUSIVE)`, `AS_IMAGE_RESOURCE`): those run
  119. /// no code, so a title DLL we have not mapped can go to the host.
  120. fn runs_code(flags: u32) -> bool {
  121. flags & (0x1 | 0x2 | 0x20 | 0x40) == 0
  122. }
  123. pub extern "system" fn LoadLibraryA(name: *const u8) -> *mut c_void {
  124. LoadLibraryExA(name, std::ptr::null_mut(), 0)
  125. }
  126. pub extern "system" fn LoadLibraryW(name: *const u16) -> *mut c_void {
  127. LoadLibraryExW(name, std::ptr::null_mut(), 0)
  128. }
  129. /// Looks up our implementations behind a pseudo handle; real modules go to
  130. /// the host.
  131. pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void {
  132. // `NULL` is the process's exe, which for the title is its own image.
  133. let module = if module.is_null() {
  134. runtime::main_image().unwrap_or(0) as *mut c_void
  135. } else {
  136. module
  137. };
  138. let Some(m) = registry().iter().find(|m| handle(m) == module) else {
  139. return host_override(module, name).unwrap_or_else(|| host::get_proc_address(module, name));
  140. };
  141. // Values below 0x10000 are ordinals; we export by name only.
  142. if (name as usize) < 0x1_0000 {
  143. tracing::warn!(
  144. module = m.name,
  145. ordinal = name as usize,
  146. "GetProcAddress by ordinal"
  147. );
  148. return std::ptr::null_mut();
  149. }
  150. // SAFETY: not an ordinal, so the title passes a NUL-terminated name.
  151. let name = unsafe { CStr::from_ptr(name.cast()) }.to_string_lossy();
  152. match m.exports.iter().find(|e| e.name == name) {
  153. Some(e) => e.address as *mut c_void,
  154. None => {
  155. tracing::warn!(module = m.name, %name, "GetProcAddress: not implemented");
  156. std::ptr::null_mut()
  157. }
  158. }
  159. }
  160. /// What a host module's `name` (or ordinal) is bound to at import binding
  161. /// when we override it: a title that looks a function up by name must not
  162. /// get past our overrides (the network guard, path rewriting).
  163. fn host_override(module: *mut c_void, name: *const u8) -> Option<*mut c_void> {
  164. if module.is_null() || runtime::image_path(module as usize).is_some() {
  165. return None;
  166. }
  167. let symbol = if (name as usize) < 0x1_0000 {
  168. format!("#{}", name as usize)
  169. } else {
  170. narrow(name)
  171. };
  172. let mut path = [0u16; 260];
  173. let len = host::get_module_file_name_w(module, path.as_mut_ptr(), path.len() as u32) as usize;
  174. let path = String::from_utf16_lossy(&path[..len.min(path.len())]);
  175. let file = path.rsplit('\\').next()?;
  176. crate::registry::lookup(file, &symbol).map(|address| address as *mut c_void)
  177. }
  178. /// Our pseudo modules and the title's images stay loaded: `LoadLibrary`
  179. /// took no reference on them, so the host's count must not drop.
  180. pub extern "system" fn FreeLibrary(module: *mut c_void) -> i32 {
  181. if registry().iter().any(|m| handle(m) == module)
  182. || runtime::image_path(module as usize).is_some()
  183. {
  184. return 1;
  185. }
  186. host::free_library(module)
  187. }
  188. /// Title images hear of thread starts and ends from us, not from the
  189. /// Windows loader (`victory_loader::disable_thread_calls`).
  190. pub extern "system" fn DisableThreadLibraryCalls(module: *mut c_void) -> i32 {
  191. host::disable_thread_library_calls(module)
  192. }
  193. /// Title debug output goes to our log (no debugger needs to be attached).
  194. pub extern "system" fn OutputDebugStringA(text: *const u8) {
  195. if !text.is_null() {
  196. let text = narrow(text);
  197. host::note_title_output(text.trim());
  198. tracing::info!(target: "title", "{}", text.trim_end());
  199. }
  200. }
  201. /// See [`OutputDebugStringA`].
  202. pub extern "system" fn OutputDebugStringW(text: *const u16) {
  203. if !text.is_null() {
  204. let text = wide(text);
  205. host::note_title_output(text.trim());
  206. tracing::info!(target: "title", "{}", text.trim_end());
  207. }
  208. }
  209. /// The CRT's `exit`, through which the title's entry point returns: logs
  210. /// the code and the caller, then exits on the host.
  211. pub extern "C" fn exit(code: i32) -> ! {
  212. tracing::warn!(code, from = %host::callers(), "title exits");
  213. host::exit(code)
  214. }
  215. /// The CRT's `abort` (also reached from `terminate`): logged like [`exit`].
  216. pub extern "C" fn abort() -> ! {
  217. tracing::error!(from = %host::callers(), "title aborts");
  218. host::abort()
  219. }
  220. /// The CRT's `terminate` and the STL's invalid-argument exit: logged, then
  221. /// the host's `abort`.
  222. pub extern "C" fn terminate() -> ! {
  223. tracing::error!(from = %host::callers(), "title calls terminate");
  224. host::abort()
  225. }
  226. /// See [`terminate`].
  227. pub extern "C" fn _invalid_parameter_noinfo_noreturn() -> ! {
  228. tracing::error!(from = %host::callers(), "title passed an invalid parameter");
  229. host::abort()
  230. }
  231. /// The title's unhandled-exception filter. Ours stands in front of it and
  232. /// reports the crash first; the title still gets its own back.
  233. static TITLE_FILTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
  234. pub extern "system" fn SetUnhandledExceptionFilter(filter: usize) -> usize {
  235. host::set_unhandled_exception_filter(report_unhandled);
  236. TITLE_FILTER.swap(filter, std::sync::atomic::Ordering::AcqRel)
  237. }
  238. extern "system" fn report_unhandled(info: *const c_void) -> i32 {
  239. host::report_unhandled(info);
  240. match TITLE_FILTER.load(std::sync::atomic::Ordering::Acquire) {
  241. 0 => 0, // EXCEPTION_CONTINUE_SEARCH
  242. filter => {
  243. type Filter = extern "system" fn(*const c_void) -> i32;
  244. // SAFETY: the title registered this filter.
  245. let filter: Filter = unsafe { std::mem::transmute(filter) };
  246. filter(info)
  247. }
  248. }
  249. }
  250. /// See [`exit`]; only the current process is logged.
  251. pub extern "system" fn TerminateProcess(process: *mut c_void, code: u32) -> i32 {
  252. if process as isize == -1 {
  253. tracing::warn!(code, from = %host::callers(), "title terminates the process");
  254. }
  255. host::terminate_process(process, code)
  256. }
  257. /// The pseudo handle of one of our modules: its address, never a real image.
  258. fn handle(m: &HleModule) -> *mut c_void {
  259. m as *const HleModule as *mut c_void
  260. }
  261. /// The title's images and our console modules by name; `None` leaves the
  262. /// name to the host, which only DLLs `HostPolicy` passes through get (as at
  263. /// import binding); others fail. With `load`, a title DLL not mapped yet is
  264. /// mapped now.
  265. fn find_module(path: &str, load: bool) -> Option<*mut c_void> {
  266. let file = path.rsplit(['\\', '/']).next().unwrap_or(path);
  267. // As the Windows loader does, a name without extension means a DLL.
  268. let file = if file.contains('.') {
  269. file.to_owned()
  270. } else {
  271. format!("{file}.dll")
  272. };
  273. // Loads go through the title DLL loader first: it waits for a DLL that
  274. // another thread is still initialising, as the Windows loader lock does.
  275. if load {
  276. match runtime::load_title_dll(&file) {
  277. Ok(Some(base)) => return Some(base as *mut c_void),
  278. Ok(None) => {}
  279. // Not the host: it would load the unpatched DLL from the title's folder.
  280. Err(error) => {
  281. tracing::error!(dll = file, %error, "mapping a title DLL failed");
  282. host::set_last_error(ERROR_MOD_NOT_FOUND);
  283. return Some(std::ptr::null_mut());
  284. }
  285. }
  286. }
  287. if let Some(base) = runtime::image_named(&file) {
  288. return Some(base as *mut c_void);
  289. }
  290. // DLLs the host has too are real host modules, whatever `--strict` says.
  291. let host_dll = HostPolicy::default().allows(&file);
  292. if !host_dll && let Some(m) = registry().iter().find(|m| m.serves(&file)) {
  293. if load {
  294. tracing::info!(dll = file, "loaded as a pseudo module");
  295. }
  296. return Some(handle(m));
  297. }
  298. if host_dll {
  299. return None;
  300. }
  301. // Any other host DLL (wininet, urlmon, ...) is beyond what we guard, and
  302. // the console does not have it.
  303. refuse(&file);
  304. host::set_last_error(ERROR_MOD_NOT_FOUND);
  305. Some(std::ptr::null_mut())
  306. }
  307. /// Logs a DLL name the title is refused, once.
  308. fn refuse(file: &str) {
  309. static REFUSED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
  310. let file = file.to_ascii_lowercase();
  311. let mut refused = REFUSED.lock().unwrap_or_else(|e| e.into_inner());
  312. if !refused.contains(&file) {
  313. tracing::warn!(dll = file, "a host DLL outside the host policy: refused");
  314. refused.push(file);
  315. }
  316. }
  317. const ERROR_MOD_NOT_FOUND: u32 = 126;
  318. /// The title's argument list: the program, then what was given after `--`.
  319. /// The host's own would be ours (`victory run <exe> ...`), and the title
  320. /// looks at fixed places in it (`-skipToIIS` only as the first argument).
  321. struct TitleArgv {
  322. count: std::cell::UnsafeCell<i32>,
  323. list: std::cell::UnsafeCell<*mut *mut c_char>,
  324. }
  325. // SAFETY: never written here after it was made; the title's C runtime start
  326. // reads it once, on one thread.
  327. unsafe impl Send for TitleArgv {}
  328. // SAFETY: as above.
  329. unsafe impl Sync for TitleArgv {}
  330. /// Kept for the whole run: the title holds on to the pointers.
  331. fn title_argv(program: &str, args: &[String]) -> TitleArgv {
  332. let list: Vec<*mut c_char> = std::iter::once(program)
  333. .chain(args.iter().map(String::as_str))
  334. .filter_map(|a| std::ffi::CString::new(a).ok())
  335. .map(std::ffi::CString::into_raw)
  336. .collect();
  337. let count = list.len() as i32;
  338. // `argv[argc]` is null.
  339. let list: Box<[*mut c_char]> = list.into_iter().chain(Some(std::ptr::null_mut())).collect();
  340. TitleArgv {
  341. count: count.into(),
  342. list: Box::leak(list).as_mut_ptr().into(),
  343. }
  344. }
  345. fn argv() -> &'static TitleArgv {
  346. static ARGV: std::sync::OnceLock<TitleArgv> = std::sync::OnceLock::new();
  347. ARGV.get_or_init(|| {
  348. // The program's name stays what the host says (as it was before).
  349. let program = std::env::args_os().next().unwrap_or_default();
  350. let args = runtime::title_args();
  351. tracing::info!(?args, "the title's arguments");
  352. title_argv(&program.to_string_lossy(), args)
  353. })
  354. }
  355. /// See [`TitleArgv`].
  356. pub extern "C" fn __p___argc() -> *mut i32 {
  357. argv().count.get()
  358. }
  359. /// See [`TitleArgv`].
  360. pub extern "C" fn __p___argv() -> *mut *mut *mut c_char {
  361. argv().list.get()
  362. }
  363. pub(crate) fn module() -> HleModule {
  364. HleModule {
  365. name: "kernel",
  366. dlls: &[
  367. "kernel32.dll",
  368. "kernelbase.dll",
  369. "api-ms-win-core-libraryloader-*",
  370. "api-ms-win-core-processthreads-*",
  371. "api-ms-win-core-debug-*",
  372. "api-ms-win-core-errorhandling-*",
  373. "api-ms-win-crt-runtime-*",
  374. ],
  375. exports: vec![
  376. hle_export!(__p___argc),
  377. hle_export!(__p___argv),
  378. hle_export!(GetModuleHandleW),
  379. hle_export!(GetModuleHandleA),
  380. hle_export!(GetModuleFileNameW),
  381. hle_export!(GetModuleFileNameA),
  382. hle_export!(LoadLibraryExA),
  383. hle_export!(LoadLibraryExW),
  384. hle_export!(LoadLibraryA),
  385. hle_export!(LoadLibraryW),
  386. hle_export!(GetProcAddress),
  387. hle_export!(FreeLibrary),
  388. hle_export!(DisableThreadLibraryCalls),
  389. hle_export!(OutputDebugStringA),
  390. hle_export!(OutputDebugStringW),
  391. hle_export!(exit),
  392. hle_export!(abort),
  393. hle_export!(terminate),
  394. hle_export!(_invalid_parameter_noinfo_noreturn),
  395. hle_export!(TerminateProcess),
  396. hle_export!(SetUnhandledExceptionFilter),
  397. ],
  398. }
  399. }
  400. /// The return addresses above the caller, as `module+rva`, for logs.
  401. #[cfg(feature = "diagnostics")]
  402. pub(crate) fn callers() -> String {
  403. host::callers()
  404. }
  405. #[cfg(windows)]
  406. mod host {
  407. use std::ffi::c_void;
  408. use windows_sys::Win32::Foundation::{FreeLibrary, SetLastError};
  409. use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace;
  410. use windows_sys::Win32::System::LibraryLoader::{
  411. DisableThreadLibraryCalls, GetModuleFileNameA, GetModuleFileNameW, GetModuleHandleA,
  412. GetModuleHandleW, GetProcAddress, LoadLibraryExA, LoadLibraryExW,
  413. };
  414. use windows_sys::Win32::System::Threading::TerminateProcess;
  415. unsafe extern "C" {
  416. #[link_name = "exit"]
  417. fn crt_exit(code: i32) -> !;
  418. #[link_name = "abort"]
  419. fn crt_abort() -> !;
  420. }
  421. // SAFETY (every function): forwarding the title's own arguments to the
  422. // host API of the same name.
  423. pub(super) fn get_module_handle_w(name: *const u16) -> *mut c_void {
  424. // SAFETY: see above.
  425. unsafe { GetModuleHandleW(name) }
  426. }
  427. pub(super) fn get_module_handle_a(name: *const u8) -> *mut c_void {
  428. // SAFETY: see above.
  429. unsafe { GetModuleHandleA(name) }
  430. }
  431. pub(super) fn get_module_file_name_w(module: *mut c_void, out: *mut u16, size: u32) -> u32 {
  432. // SAFETY: see above.
  433. unsafe { GetModuleFileNameW(module, out, size) }
  434. }
  435. pub(super) fn get_module_file_name_a(module: *mut c_void, out: *mut u8, size: u32) -> u32 {
  436. // SAFETY: see above.
  437. unsafe { GetModuleFileNameA(module, out, size) }
  438. }
  439. pub(super) fn set_last_error(code: u32) {
  440. // SAFETY: see above.
  441. unsafe { SetLastError(code) }
  442. }
  443. pub(super) fn load_library_ex_a(name: *const u8, file: *mut c_void, flags: u32) -> *mut c_void {
  444. // SAFETY: see above.
  445. unsafe { LoadLibraryExA(name, file, flags) }
  446. }
  447. pub(super) fn load_library_ex_w(
  448. name: *const u16,
  449. file: *mut c_void,
  450. flags: u32,
  451. ) -> *mut c_void {
  452. // SAFETY: see above.
  453. unsafe { LoadLibraryExW(name, file, flags) }
  454. }
  455. pub(super) fn get_proc_address(module: *mut c_void, name: *const u8) -> *mut c_void {
  456. // SAFETY: see above.
  457. unsafe { GetProcAddress(module, name) }.map_or(std::ptr::null_mut(), |f| f as *mut c_void)
  458. }
  459. pub(super) fn free_library(module: *mut c_void) -> i32 {
  460. // SAFETY: see above.
  461. unsafe { FreeLibrary(module) }
  462. }
  463. pub(super) fn disable_thread_library_calls(module: *mut c_void) -> i32 {
  464. match victory_loader::disable_thread_calls(module as usize) {
  465. Some(done) => i32::from(done),
  466. // SAFETY: see above.
  467. None => unsafe { DisableThreadLibraryCalls(module) },
  468. }
  469. }
  470. pub(super) fn exit(code: i32) -> ! {
  471. // SAFETY: see above.
  472. unsafe { crt_exit(code) }
  473. }
  474. pub(super) fn abort() -> ! {
  475. // SAFETY: see above.
  476. unsafe { crt_abort() }
  477. }
  478. pub(super) fn terminate_process(process: *mut c_void, code: u32) -> i32 {
  479. // SAFETY: see above.
  480. unsafe { TerminateProcess(process, code) }
  481. }
  482. pub(super) fn set_unhandled_exception_filter(filter: extern "system" fn(*const c_void) -> i32) {
  483. // SAFETY: our filter takes the exception pointers as an opaque pointer.
  484. unsafe {
  485. windows_sys::Win32::System::Diagnostics::Debug::SetUnhandledExceptionFilter(
  486. std::mem::transmute::<
  487. extern "system" fn(*const c_void) -> i32,
  488. windows_sys::Win32::System::Diagnostics::Debug::LPTOP_LEVEL_EXCEPTION_FILTER,
  489. >(filter),
  490. )
  491. };
  492. }
  493. pub(super) fn report_unhandled(info: *const c_void) {
  494. // SAFETY: the system's exception pointers, passed to the filter.
  495. unsafe { victory_loader::report_unhandled(info.cast()) };
  496. }
  497. pub(super) fn note_title_output(line: &str) {
  498. victory_loader::note_title_output(line);
  499. }
  500. /// Our caller's callers, as `module+rva`.
  501. pub(super) fn callers() -> String {
  502. let mut frames = [std::ptr::null_mut(); 12];
  503. // SAFETY: fills at most `frames.len()` return addresses.
  504. let n = unsafe {
  505. RtlCaptureStackBackTrace(
  506. 2,
  507. frames.len() as u32,
  508. frames.as_mut_ptr(),
  509. std::ptr::null_mut(),
  510. )
  511. };
  512. let names: Vec<_> = frames[..usize::from(n)]
  513. .iter()
  514. .map(|&f| victory_loader::locate(f as usize))
  515. .collect();
  516. names.join(" < ")
  517. }
  518. }
  519. #[cfg(not(windows))]
  520. mod host {
  521. use std::ffi::c_void;
  522. pub(super) fn get_module_handle_w(_: *const u16) -> *mut c_void {
  523. std::ptr::null_mut()
  524. }
  525. pub(super) fn get_module_handle_a(_: *const u8) -> *mut c_void {
  526. std::ptr::null_mut()
  527. }
  528. pub(super) fn load_library_ex_a(_: *const u8, _: *mut c_void, _: u32) -> *mut c_void {
  529. std::ptr::null_mut()
  530. }
  531. pub(super) fn get_module_file_name_w(_: *mut c_void, _: *mut u16, _: u32) -> u32 {
  532. 0
  533. }
  534. pub(super) fn get_module_file_name_a(_: *mut c_void, _: *mut u8, _: u32) -> u32 {
  535. 0
  536. }
  537. pub(super) fn set_last_error(_: u32) {}
  538. pub(super) fn load_library_ex_w(_: *const u16, _: *mut c_void, _: u32) -> *mut c_void {
  539. std::ptr::null_mut()
  540. }
  541. pub(super) fn get_proc_address(_: *mut c_void, _: *const u8) -> *mut c_void {
  542. std::ptr::null_mut()
  543. }
  544. pub(super) fn free_library(_: *mut c_void) -> i32 {
  545. 0
  546. }
  547. pub(super) fn disable_thread_library_calls(_: *mut c_void) -> i32 {
  548. 0
  549. }
  550. pub(super) fn exit(code: i32) -> ! {
  551. std::process::exit(code)
  552. }
  553. pub(super) fn abort() -> ! {
  554. std::process::abort()
  555. }
  556. pub(super) fn terminate_process(_: *mut c_void, code: u32) -> i32 {
  557. std::process::exit(code as i32)
  558. }
  559. pub(super) fn set_unhandled_exception_filter(_: extern "system" fn(*const c_void) -> i32) {}
  560. pub(super) fn report_unhandled(_: *const c_void) {}
  561. pub(super) fn note_title_output(_: &str) {}
  562. pub(super) fn callers() -> String {
  563. String::new()
  564. }
  565. }
  566. #[cfg(test)]
  567. mod tests {
  568. use super::*;
  569. #[test]
  570. fn title_images_report_their_original_path() {
  571. let base = 0x7000_0000_0000;
  572. runtime::set_image_path(base, std::path::Path::new(r"C:\title\game.exe"));
  573. let module = base as *mut c_void;
  574. let mut buf = [0xFFFFu16; 32];
  575. let n = GetModuleFileNameW(module, buf.as_mut_ptr(), buf.len() as u32);
  576. assert_eq!(
  577. String::from_utf16_lossy(&buf[..n as usize]),
  578. r"C:\title\game.exe"
  579. );
  580. assert_eq!(buf[n as usize], 0);
  581. // Too small: truncated, NUL-terminated, the buffer size returned.
  582. let mut small = [0u8; 4];
  583. assert_eq!(GetModuleFileNameA(module, small.as_mut_ptr(), 4), 4);
  584. assert_eq!(&small, &[b'C', b':', b'\\', 0]);
  585. }
  586. /// The title's arguments come right after the program, and the list ends
  587. /// in a null pointer; without any there is only the program.
  588. #[test]
  589. fn the_title_gets_its_own_arguments() {
  590. let read = |made: &TitleArgv| {
  591. // SAFETY: made above, kept for the whole run.
  592. unsafe {
  593. let (count, list) = (*made.count.get() as usize, *made.list.get());
  594. assert!((*list.add(count)).is_null());
  595. (0..count)
  596. .map(|i| CStr::from_ptr(*list.add(i)).to_str().unwrap().to_owned())
  597. .collect::<Vec<_>>()
  598. }
  599. };
  600. let some = title_argv("victory.exe", &["-skipToIIS".into(), "-x=1".into()]);
  601. assert_eq!(read(&some), ["victory.exe", "-skipToIIS", "-x=1"]);
  602. assert_eq!(read(&title_argv("victory.exe", &[])), ["victory.exe"]);
  603. // What the title is given: the same list every time.
  604. assert_eq!(__p___argc(), __p___argc());
  605. // SAFETY: as above.
  606. unsafe { assert_eq!((*__p___argc(), (**__p___argv()).is_null()), (1, false)) };
  607. }
  608. fn w(text: &str) -> Vec<u16> {
  609. text.encode_utf16().chain(Some(0)).collect()
  610. }
  611. #[cfg(windows)]
  612. #[test]
  613. fn host_lookups_by_name_get_our_overrides() {
  614. let kernel32 = GetModuleHandleW(w("kernel32.dll").as_ptr());
  615. assert!(!kernel32.is_null());
  616. let ours = crate::registry::lookup("kernel32.dll", "CreateFileW").unwrap();
  617. assert_eq!(
  618. GetProcAddress(kernel32, c"CreateFileW".as_ptr().cast()) as usize,
  619. ours
  620. );
  621. // A plain name stays the host's.
  622. let host = host::get_proc_address(kernel32, c"GetTickCount".as_ptr().cast());
  623. assert!(!host.is_null());
  624. assert_eq!(
  625. GetProcAddress(kernel32, c"GetTickCount".as_ptr().cast()),
  626. host
  627. );
  628. // Host DLLs outside the host policy do not exist for the title.
  629. assert!(LoadLibraryW(w("wininet.dll").as_ptr()).is_null());
  630. assert!(LoadLibraryA(c"C:\\Windows\\System32\\urlmon".as_ptr().cast()).is_null());
  631. assert!(GetModuleHandleW(w("WININET.DLL").as_ptr()).is_null());
  632. assert_eq!(
  633. // SAFETY: reads this thread's last error.
  634. unsafe { windows_sys::Win32::Foundation::GetLastError() },
  635. ERROR_MOD_NOT_FOUND
  636. );
  637. assert!(!LoadLibraryW(w("kernel32").as_ptr()).is_null());
  638. // By ordinal too (ws2_32 #4 is `connect`).
  639. let ws2 = LoadLibraryW(w("ws2_32.dll").as_ptr());
  640. assert_eq!(
  641. GetProcAddress(ws2, 4 as *const u8) as usize,
  642. crate::registry::lookup("ws2_32.dll", "connect").unwrap()
  643. );
  644. }
  645. #[test]
  646. fn title_dlls_and_pseudo_modules_are_found_by_name() {
  647. let base = 0x7100_0000_0000usize;
  648. runtime::set_image_path(base, std::path::Path::new(r"C:\title\Mapped.dll"));
  649. runtime::set_title_dll_loader(Box::new(|file| match file {
  650. "late.dll" => Ok(Some(0x7200_0000_0000)),
  651. "broken.dll" => Err("bad image".into()),
  652. _ => Ok(None),
  653. }));
  654. let mapped = base as *mut c_void;
  655. assert_eq!(GetModuleHandleW(w("MAPPED").as_ptr()), mapped);
  656. assert_eq!(GetModuleHandleA(c"sub\\mapped.dll".as_ptr().cast()), mapped);
  657. assert_eq!(LoadLibraryW(w("mapped.dll").as_ptr()), mapped);
  658. assert_eq!(FreeLibrary(mapped), 1, "title images stay loaded");
  659. // Not mapped yet: `LoadLibrary` maps it, `GetModuleHandle` does not.
  660. assert!(GetModuleHandleW(w("late.dll").as_ptr()).is_null());
  661. assert_eq!(
  662. LoadLibraryA(c"late".as_ptr().cast()) as usize,
  663. 0x7200_0000_0000
  664. );
  665. assert!(LoadLibraryA(c"broken.dll".as_ptr().cast()).is_null());
  666. // As data it runs no code, so the host loads it (and finds nothing).
  667. let data = LoadLibraryExW(w("late.dll").as_ptr(), std::ptr::null_mut(), 0x2);
  668. assert_ne!(data as usize, 0x7200_0000_0000);
  669. let runtime = LoadLibraryA(c"xgameruntime.dll".as_ptr().cast());
  670. assert!(!runtime.is_null());
  671. assert_eq!(GetModuleHandleW(w("XGameRuntime.dll").as_ptr()), runtime);
  672. }
  673. }