kernel.rs 30 KB

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