host.rs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. //! Pass-through to the host's own implementation of shared APIs.
  2. use victory_pe::ImportSymbol;
  3. /// Which DLLs may be satisfied by the host's own implementation.
  4. ///
  5. /// Console titles link mostly against Windows API sets that behave the same
  6. /// on PC. Passing those through lets bring-up focus on what really differs.
  7. /// Anything whose semantics differ on console (memory, files, threads) is
  8. /// overridden in `modules`, which always wins over the host.
  9. #[derive(Debug, Clone)]
  10. pub struct HostPolicy {
  11. /// Lower-case patterns; a trailing `*` matches a prefix.
  12. pub allow: Vec<String>,
  13. }
  14. impl Default for HostPolicy {
  15. fn default() -> Self {
  16. let allow = [
  17. "api-ms-win-core-*",
  18. "api-ms-win-eventing-*",
  19. "api-ms-win-security-*",
  20. "api-ms-win-crt-*",
  21. "kernel32.dll",
  22. "kernelbase.dll",
  23. "ntdll.dll",
  24. "ucrtbase.dll",
  25. "vcruntime140*",
  26. "msvcp140*",
  27. // Off-machine traffic is refused in `modules::net`.
  28. "ws2_32.dll",
  29. "bcrypt.dll",
  30. "crypt32.dll",
  31. "ncrypt.dll",
  32. "winhttp.dll",
  33. "sspicli.dll",
  34. "cabinet.dll",
  35. "avrt.dll",
  36. // Window, message and shell APIs: the host's desktop window
  37. // stands in for the console's single core window.
  38. "ext-ms-win-rtcore-ntuser-*",
  39. "api-ms-win-shcore-*",
  40. "msvcp_win.dll",
  41. "ole32.dll",
  42. "advapi32.dll",
  43. "iphlpapi.dll",
  44. // The title's crash handler writes minidumps with it (loaded by name).
  45. "dbghelp.dll",
  46. // Same APIs as the console's (XAudio2 ordinal 1 is XAudio2Create
  47. // on both); Media Foundation reads local media files.
  48. "xaudio2_9.dll",
  49. "mfplat.dll",
  50. "mfreadwrite.dll",
  51. ];
  52. HostPolicy {
  53. allow: allow.iter().map(|s| s.to_string()).collect(),
  54. }
  55. }
  56. }
  57. impl HostPolicy {
  58. /// No pass-through at all: shows the full surface a title needs.
  59. pub fn none() -> Self {
  60. HostPolicy { allow: Vec::new() }
  61. }
  62. pub fn allows(&self, dll: &str) -> bool {
  63. let dll = dll.to_ascii_lowercase();
  64. self.allow
  65. .iter()
  66. .any(|pattern| match pattern.strip_suffix('*') {
  67. Some(prefix) => dll.starts_with(prefix),
  68. None => dll == *pattern,
  69. })
  70. }
  71. pub(crate) fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Option<usize> {
  72. if !self.allows(dll) {
  73. return None;
  74. }
  75. imp::resolve(dll, symbol)
  76. }
  77. }
  78. /// The host's own `name` from the System32 DLL `dll`: what a title import
  79. /// of it is bound to when we do not override it.
  80. pub(crate) fn function(dll: &str, name: &str) -> Option<usize> {
  81. let name = ImportSymbol::Name {
  82. hint: 0,
  83. name: name.into(),
  84. };
  85. imp::resolve(dll, &name)
  86. }
  87. #[cfg(windows)]
  88. mod imp {
  89. use std::collections::HashMap;
  90. use std::ffi::CString;
  91. use std::sync::{LazyLock, Mutex};
  92. use victory_pe::ImportSymbol;
  93. use windows_sys::Win32::System::LibraryLoader::{
  94. GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExA,
  95. };
  96. /// Module handles by lower-case DLL name (stored as usize: Send + Sync).
  97. static MODULES: LazyLock<Mutex<HashMap<String, usize>>> = LazyLock::new(Default::default);
  98. pub(super) fn resolve(dll: &str, symbol: &ImportSymbol) -> Option<usize> {
  99. let module = module(dll)?;
  100. let proc = match symbol {
  101. ImportSymbol::Name { name, .. } => {
  102. let name = CString::new(name.as_str()).ok()?;
  103. // SAFETY: valid module handle, NUL-terminated name.
  104. unsafe { GetProcAddress(module as _, name.as_ptr().cast()) }
  105. }
  106. // SAFETY: MAKEINTRESOURCE-style ordinal lookup on a valid module.
  107. ImportSymbol::Ordinal(o) => unsafe { GetProcAddress(module as _, *o as usize as _) },
  108. };
  109. proc.map(|f| f as *const () as usize)
  110. }
  111. fn module(dll: &str) -> Option<usize> {
  112. let key = dll.to_ascii_lowercase();
  113. let cache = || MODULES.lock().unwrap_or_else(|e| e.into_inner());
  114. let cached = cache().get(&key).copied();
  115. if cached.is_some() {
  116. return cached;
  117. }
  118. let name = CString::new(key.as_str()).ok()?;
  119. // Not under the cache's lock: loading takes the OS loader lock, and
  120. // title code that runs under that one (a DLL's thread attach, a TLS
  121. // callback) may look a function up here.
  122. // System32 only: never pick up a same-named DLL from the current folder or PATH.
  123. // SAFETY: NUL-terminated DLL name; only allow-listed system DLLs get here.
  124. let handle = unsafe {
  125. LoadLibraryExA(
  126. name.as_ptr().cast(),
  127. std::ptr::null_mut(),
  128. LOAD_LIBRARY_SEARCH_SYSTEM32,
  129. )
  130. } as usize;
  131. // A thread that loaded it meanwhile got the same module, which stays loaded.
  132. (handle != 0).then(|| *cache().entry(key).or_insert(handle))
  133. }
  134. #[cfg(test)]
  135. mod tests {
  136. use std::ffi::c_void;
  137. use std::ptr::{null, null_mut};
  138. use std::sync::atomic::{AtomicBool, Ordering};
  139. use std::time::{Duration, Instant};
  140. use windows_sys::Win32::System::Threading::{
  141. CreateThread, INFINITE, Sleep, WaitForSingleObject,
  142. };
  143. const CHILD: &str = "VICTORY_HOST_LOCK_CHILD";
  144. static ARMED: AtomicBool = AtomicBool::new(false);
  145. static IN_ATTACH: AtomicBool = AtomicBool::new(false);
  146. static STARTED: AtomicBool = AtomicBool::new(false);
  147. /// Runs as title TLS callbacks do: under the loader lock, as a new
  148. /// thread starts.
  149. #[used]
  150. #[unsafe(link_section = ".CRT$XLY")]
  151. static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = attach;
  152. unsafe extern "system" fn attach(_: *mut c_void, reason: u32, _: *mut c_void) {
  153. const DLL_THREAD_ATTACH: u32 = 2;
  154. if reason == DLL_THREAD_ATTACH && ARMED.swap(false, Ordering::SeqCst) {
  155. IN_ATTACH.store(true, Ordering::SeqCst);
  156. // SAFETY: a plain sleep, for the other thread to start a load.
  157. unsafe { Sleep(500) };
  158. let found = super::super::function("kernel32.dll", "GetTickCount");
  159. assert!(found.is_some());
  160. }
  161. }
  162. unsafe extern "system" fn idle(_: *mut c_void) -> u32 {
  163. 0
  164. }
  165. /// One thread loads a DLL nothing has loaded yet, which needs the
  166. /// loader lock, while another thread's attach holds that lock and
  167. /// looks a function up. Run in a child process: a deadlock inside the
  168. /// loader keeps a process from exiting, so the parent kills it.
  169. #[test]
  170. fn loading_a_host_dll_does_not_block_thread_attach() {
  171. if std::env::var_os(CHILD).is_none() {
  172. let name = "host::imp::tests::loading_a_host_dll_does_not_block_thread_attach";
  173. let mut child = std::process::Command::new(std::env::current_exe().unwrap())
  174. .args(["--exact", name])
  175. .env(CHILD, "1")
  176. .spawn()
  177. .unwrap();
  178. let start = Instant::now();
  179. loop {
  180. if let Some(status) = child.try_wait().unwrap() {
  181. assert!(status.success());
  182. return;
  183. }
  184. if start.elapsed() > Duration::from_secs(30) {
  185. child.kill().unwrap();
  186. panic!("deadlock: a host DLL loads under the module cache's lock");
  187. }
  188. std::thread::sleep(Duration::from_millis(50));
  189. }
  190. }
  191. // The attach below only needs the cache, no load of its own.
  192. assert!(super::super::function("kernel32.dll", "GetTickCount").is_some());
  193. let loader = std::thread::spawn(|| {
  194. STARTED.store(true, Ordering::SeqCst);
  195. while !IN_ATTACH.load(Ordering::SeqCst) {
  196. std::hint::spin_loop();
  197. }
  198. super::super::function("cabinet.dll", "FDICreate")
  199. });
  200. // Its own attach is over: the next is the thread below.
  201. while !STARTED.load(Ordering::SeqCst) {
  202. std::hint::spin_loop();
  203. }
  204. ARMED.store(true, Ordering::SeqCst);
  205. let (security, start) = (std::ptr::null(), Some(idle as _));
  206. // SAFETY: a thread that returns at once.
  207. let thread = unsafe { CreateThread(security, 0, start, null(), 0, null_mut()) };
  208. assert!(!thread.is_null());
  209. assert!(loader.join().unwrap().is_some());
  210. // SAFETY: our own thread's handle.
  211. unsafe { WaitForSingleObject(thread, INFINITE) };
  212. }
  213. }
  214. }
  215. #[cfg(not(windows))]
  216. mod imp {
  217. pub(super) fn resolve(_dll: &str, _symbol: &victory_pe::ImportSymbol) -> Option<usize> {
  218. None
  219. }
  220. }