host.rs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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 mut cache = MODULES.lock().unwrap_or_else(|e| e.into_inner());
  114. if let Some(&m) = cache.get(&key) {
  115. return Some(m);
  116. }
  117. let name = CString::new(key.as_str()).ok()?;
  118. // System32 only: never pick up a same-named DLL from the current folder or PATH.
  119. // SAFETY: NUL-terminated DLL name; only allow-listed system DLLs get here.
  120. let handle = unsafe {
  121. LoadLibraryExA(
  122. name.as_ptr().cast(),
  123. std::ptr::null_mut(),
  124. LOAD_LIBRARY_SEARCH_SYSTEM32,
  125. )
  126. } as usize;
  127. (handle != 0).then(|| *cache.entry(key).or_insert(handle))
  128. }
  129. }
  130. #[cfg(not(windows))]
  131. mod imp {
  132. pub(super) fn resolve(_dll: &str, _symbol: &victory_pe::ImportSymbol) -> Option<usize> {
  133. None
  134. }
  135. }