windows.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. //! Loading a prepared image as a real Windows module and binding it.
  2. use std::collections::HashSet;
  3. use std::ffi::{CString, c_void};
  4. use std::os::windows::ffi::OsStrExt;
  5. use std::path::{Path, PathBuf};
  6. use std::sync::Arc;
  7. use std::sync::atomic::AtomicU64;
  8. use anyhow::{Context, Result, bail};
  9. use victory_pe::{ImageInfo, ImportSymbol};
  10. use windows_sys::Win32::Foundation::{FreeLibrary, HMODULE};
  11. use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryExW};
  12. use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect};
  13. use crate::thunks::{ImportSite, ThunkBlock, UnimplementedPolicy};
  14. use crate::{DLL_PROCESS_ATTACH, ImportResolver, PreparedImage, Provenance, Resolution, prepare};
  15. /// A title image mapped into this process. A clone names the same mapping
  16. /// (no reference of its own): unload one copy only.
  17. #[derive(Debug, Clone)]
  18. pub struct LoadedImage {
  19. module: HMODULE,
  20. path: PathBuf,
  21. info: ImageInfo,
  22. }
  23. // SAFETY: HMODULE is a process-wide handle (the base address); using it from
  24. // any thread is fine.
  25. unsafe impl Send for LoadedImage {}
  26. // SAFETY: as above; `LoadedImage` has no interior mutability.
  27. unsafe impl Sync for LoadedImage {}
  28. #[derive(Debug, Clone, PartialEq, Eq)]
  29. pub struct MissingImport {
  30. pub dll: String,
  31. pub symbol: String,
  32. }
  33. /// Outcome of [`LoadedImage::bind_imports`].
  34. #[derive(Debug, Default, Clone)]
  35. pub struct BindReport {
  36. pub hle: usize,
  37. pub host: usize,
  38. pub title: usize,
  39. pub missing: Vec<MissingImport>,
  40. }
  41. /// Writes the prepared copy into `dir` and maps it with the Windows loader.
  42. ///
  43. /// `dir` receives derived game data, so it must be outside the repository.
  44. pub fn load(prepared: &PreparedImage, dir: &Path) -> Result<LoadedImage> {
  45. victory_core::ensure_outside_repo(dir)?;
  46. std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
  47. let path = dir.join(prepared.file_name());
  48. write_if_changed(&path, &prepared.bytes)?;
  49. let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
  50. // SAFETY: `wide` is a NUL-terminated path. The image has no entry point
  51. // and no imports, so loading it runs no title code.
  52. let module = unsafe { LoadLibraryExW(wide.as_ptr(), std::ptr::null_mut(), 0) };
  53. if module.is_null() {
  54. bail!(
  55. "LoadLibraryExW({}) failed: {}{}",
  56. path.display(),
  57. std::io::Error::last_os_error(),
  58. if prepared.info.has_relocations {
  59. ""
  60. } else {
  61. " (image has no relocations; its preferred base may be taken)"
  62. }
  63. );
  64. }
  65. let loaded = LoadedImage {
  66. module,
  67. path,
  68. info: prepared.info.clone(),
  69. };
  70. // A DLL indexes its TLS properly; only an exe assumes index 0.
  71. if !loaded.info.is_dll() {
  72. // SAFETY: just mapped, and no title code has run.
  73. unsafe { crate::tls::redirect(loaded.base(), &loaded.info) }?;
  74. }
  75. tracing::info!(
  76. base = format_args!("{:#x}", loaded.base()),
  77. preferred = format_args!("{:#x}", loaded.info.image_base),
  78. path = %loaded.path.display(),
  79. "image mapped"
  80. );
  81. Ok(loaded)
  82. }
  83. /// Maps the DLLs the title ships in `title_dir` that `main` imports,
  84. /// directly or through each other, in initialisation order (dependencies
  85. /// first). Only DLL names `wanted` accepts are considered, so DLLs the host
  86. /// or our runtime provide stay with them. Imports are not bound.
  87. pub fn load_title_dlls(
  88. main: &ImageInfo,
  89. title_dir: &Path,
  90. cache_dir: &Path,
  91. wanted: &dyn Fn(&str) -> bool,
  92. ) -> Result<Vec<(String, LoadedImage)>> {
  93. let mut loaded = Vec::new();
  94. let dirs = (title_dir, cache_dir);
  95. map_imports(main, dirs, wanted, &mut HashSet::new(), &mut loaded)?;
  96. Ok(loaded)
  97. }
  98. /// Maps the DLL `name` from `title_dir` like [`load_title_dlls`] does, with
  99. /// the title DLLs it imports (dependencies first, `name` last); empty if
  100. /// `wanted` refuses it or the folder has no such file. For DLLs a title
  101. /// loads itself; `wanted` must refuse those already mapped.
  102. pub fn load_title_dll(
  103. name: &str,
  104. title_dir: &Path,
  105. cache_dir: &Path,
  106. wanted: &dyn Fn(&str) -> bool,
  107. ) -> Result<Vec<(String, LoadedImage)>> {
  108. let mut loaded = Vec::new();
  109. let dirs = (title_dir, cache_dir);
  110. map_dll(name, dirs, wanted, &mut HashSet::new(), &mut loaded)?;
  111. Ok(loaded)
  112. }
  113. fn map_imports(
  114. info: &ImageInfo,
  115. dirs: (&Path, &Path),
  116. wanted: &dyn Fn(&str) -> bool,
  117. seen: &mut HashSet<String>,
  118. loaded: &mut Vec<(String, LoadedImage)>,
  119. ) -> Result<()> {
  120. for module in info.imports.iter().chain(&info.delay_imports) {
  121. map_dll(&module.dll, dirs, wanted, seen, loaded)?;
  122. }
  123. Ok(())
  124. }
  125. fn map_dll(
  126. name: &str,
  127. dirs: (&Path, &Path),
  128. wanted: &dyn Fn(&str) -> bool,
  129. seen: &mut HashSet<String>,
  130. loaded: &mut Vec<(String, LoadedImage)>,
  131. ) -> Result<()> {
  132. let name = name.to_ascii_lowercase();
  133. let path = dirs.0.join(&name);
  134. if !seen.insert(name.clone()) || !wanted(&name) || !path.is_file() {
  135. return Ok(());
  136. }
  137. let original = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?;
  138. let image = load(&prepare(&original)?, dirs.1)
  139. .with_context(|| format!("loading {}", path.display()))?;
  140. map_imports(&image.info, dirs, wanted, seen, loaded)?;
  141. loaded.push((name, image));
  142. Ok(())
  143. }
  144. /// Resolves through `inner`, then through the exports of the title's DLLs.
  145. pub struct WithTitleDlls<'a> {
  146. pub inner: &'a dyn ImportResolver,
  147. pub dlls: &'a [(String, LoadedImage)],
  148. }
  149. impl ImportResolver for WithTitleDlls<'_> {
  150. fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution {
  151. let found = self.inner.resolve(dll, symbol);
  152. if found != Resolution::Missing {
  153. return found;
  154. }
  155. self.dlls
  156. .iter()
  157. .find(|(name, _)| name.eq_ignore_ascii_case(dll))
  158. .and_then(|(_, image)| image.export_symbol(symbol))
  159. .map_or(Resolution::Missing, |address| Resolution::Found {
  160. address,
  161. provenance: Provenance::Title,
  162. })
  163. }
  164. }
  165. fn write_if_changed(path: &Path, bytes: &[u8]) -> Result<()> {
  166. if std::fs::read(path).is_ok_and(|existing| existing == bytes) {
  167. return Ok(());
  168. }
  169. let tmp = path.with_extension("tmp");
  170. std::fs::write(&tmp, bytes).with_context(|| format!("writing {}", tmp.display()))?;
  171. std::fs::rename(&tmp, path).with_context(|| format!("renaming to {}", path.display()))?;
  172. Ok(())
  173. }
  174. impl LoadedImage {
  175. pub fn base(&self) -> usize {
  176. self.module as usize
  177. }
  178. /// Parsed from the original image (imports, entry point, TLS callbacks).
  179. pub fn info(&self) -> &ImageInfo {
  180. &self.info
  181. }
  182. /// Address of an export of the image, if it has one by that name.
  183. pub fn export(&self, name: &str) -> Option<usize> {
  184. let name = CString::new(name).ok()?;
  185. // SAFETY: valid module handle and NUL-terminated name.
  186. unsafe { GetProcAddress(self.module, name.as_ptr().cast()) }
  187. .map(|f| f as *const () as usize)
  188. }
  189. /// Address of an export, by name or ordinal.
  190. pub fn export_symbol(&self, symbol: &ImportSymbol) -> Option<usize> {
  191. match symbol {
  192. ImportSymbol::Name { name, .. } => self.export(name),
  193. // SAFETY: MAKEINTRESOURCE-style ordinal lookup on a valid module.
  194. ImportSymbol::Ordinal(o) => unsafe { GetProcAddress(self.module, *o as usize as _) }
  195. .map(|f| f as *const () as usize),
  196. }
  197. }
  198. /// Fills every IAT slot of the image.
  199. ///
  200. /// Each import goes to `resolver`; whatever it cannot resolve gets an
  201. /// unimplemented-import stub that behaves according to `policy`.
  202. pub fn bind_imports(
  203. &self,
  204. resolver: &dyn ImportResolver,
  205. policy: UnimplementedPolicy,
  206. ) -> Result<BindReport> {
  207. let mut report = BindReport::default();
  208. let mut slots: Vec<(u32, usize)> = Vec::with_capacity(self.info.import_count());
  209. let mut unresolved: Vec<(u32, &str, &ImportSymbol)> = Vec::new();
  210. // Delay-load slots are bound eagerly too, so the title's own
  211. // delay-load helper (which would ask the host) never runs.
  212. for module in self.info.imports.iter().chain(&self.info.delay_imports) {
  213. for entry in &module.entries {
  214. match resolver.resolve(&module.dll, &entry.symbol) {
  215. Resolution::Found {
  216. address,
  217. provenance,
  218. } => {
  219. match provenance {
  220. Provenance::Hle => report.hle += 1,
  221. Provenance::Host => report.host += 1,
  222. Provenance::Title => report.title += 1,
  223. }
  224. slots.push((entry.iat_slot_rva, address));
  225. }
  226. Resolution::Missing => {
  227. unresolved.push((entry.iat_slot_rva, &module.dll, &entry.symbol));
  228. }
  229. }
  230. }
  231. }
  232. if !unresolved.is_empty() {
  233. let mut block = ThunkBlock::new(unresolved.len())?;
  234. for (slot, dll, symbol) in unresolved {
  235. let site: &'static ImportSite = Box::leak(Box::new(ImportSite {
  236. dll: dll.to_owned(),
  237. symbol: symbol.to_string(),
  238. policy,
  239. calls: AtomicU64::new(0),
  240. }));
  241. slots.push((slot, block.emit(site)?));
  242. report.missing.push(MissingImport {
  243. dll: site.dll.clone(),
  244. symbol: site.symbol.clone(),
  245. });
  246. }
  247. block.seal()?;
  248. }
  249. self.write_slots(&slots)?;
  250. tracing::info!(
  251. hle = report.hle,
  252. host = report.host,
  253. missing = report.missing.len(),
  254. "imports bound"
  255. );
  256. Ok(report)
  257. }
  258. /// Protects and restores each slot on its own: import tables can sit in
  259. /// sections with different protections (delay-load tables in `.didat`).
  260. fn write_slots(&self, slots: &[(u32, usize)]) -> Result<()> {
  261. for &(rva, address) in slots {
  262. let slot = (self.base() + rva as usize) as *mut u64;
  263. let mut old = 0;
  264. // SAFETY: the parser only yields slots inside the image.
  265. if unsafe { VirtualProtect(slot as *const c_void, 8, PAGE_READWRITE, &mut old) } == 0 {
  266. bail!(
  267. "VirtualProtect(IAT slot {rva:#x}) failed: {}",
  268. std::io::Error::last_os_error()
  269. );
  270. }
  271. // SAFETY: inside the image, now writable, 8-byte aligned by the PE format.
  272. unsafe { slot.write_volatile(address as u64) };
  273. let mut ignored = 0;
  274. // SAFETY: restoring the protection we just changed.
  275. unsafe { VirtualProtect(slot as *const c_void, 8, old, &mut ignored) };
  276. }
  277. Ok(())
  278. }
  279. /// Calls the image's TLS callbacks with `reason` (e.g. `DLL_PROCESS_ATTACH`).
  280. ///
  281. /// # Safety
  282. /// Runs title code. Imports must be bound first.
  283. pub unsafe fn run_tls_callbacks(&self, reason: u32) {
  284. let Some(tls) = &self.info.tls else { return };
  285. for &rva in &tls.callback_rvas {
  286. type TlsCallback = unsafe extern "system" fn(*mut c_void, u32, *mut c_void);
  287. // SAFETY: the RVA came from the image's own TLS directory.
  288. let callback: TlsCallback = unsafe { std::mem::transmute(self.base() + rva as usize) };
  289. // SAFETY: the caller guarantees imports are bound.
  290. unsafe { callback(self.module, reason, std::ptr::null_mut()) };
  291. }
  292. }
  293. /// Initialises a DLL as the Windows loader would: its TLS callbacks,
  294. /// then `DllMain(DLL_PROCESS_ATTACH)`.
  295. ///
  296. /// # Safety
  297. /// Runs title code. Imports must be bound first, and the DLLs this one
  298. /// depends on attached.
  299. pub unsafe fn attach(&self) -> Result<()> {
  300. // SAFETY: forwarded from the caller.
  301. unsafe { self.run_tls_callbacks(DLL_PROCESS_ATTACH) };
  302. if self.info.entry_rva == 0 {
  303. return Ok(());
  304. }
  305. type DllMain = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32;
  306. // SAFETY: the entry RVA came from the original image header.
  307. let main: DllMain =
  308. unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) };
  309. // SAFETY: forwarded from the caller.
  310. if unsafe { main(self.module, DLL_PROCESS_ATTACH, std::ptr::null_mut()) } == 0 {
  311. bail!("DllMain returned FALSE");
  312. }
  313. Ok(())
  314. }
  315. /// Starts the title: on a new thread with the stack size from the image
  316. /// header, attaches `dlls` in order (see [`Self::attach`]), runs the
  317. /// image's TLS callbacks (`DLL_PROCESS_ATTACH`), then its original entry
  318. /// point. Returns the thread so the caller can join it.
  319. ///
  320. /// # Safety
  321. /// Runs title code. Imports of the image and of `dlls` must be bound.
  322. pub unsafe fn spawn_main(
  323. self: Arc<Self>,
  324. dlls: Vec<(String, LoadedImage)>,
  325. ) -> Result<std::thread::JoinHandle<Result<u32>>> {
  326. if self.info.entry_rva == 0 {
  327. bail!("image has no entry point");
  328. }
  329. let stack = usize::try_from(self.info.stack_reserve)
  330. .unwrap_or(usize::MAX)
  331. .max(1 << 20);
  332. std::thread::Builder::new()
  333. .name("title-main".into())
  334. .stack_size(stack)
  335. .spawn(move || {
  336. for (name, dll) in &dlls {
  337. // SAFETY: forwarded from the caller of `spawn_main`.
  338. unsafe { dll.attach() }.with_context(|| format!("attaching {name}"))?;
  339. }
  340. // SAFETY: forwarded from the caller of `spawn_main`.
  341. unsafe { self.run_tls_callbacks(DLL_PROCESS_ATTACH) };
  342. type Entry = unsafe extern "system" fn(*mut c_void) -> u32;
  343. // SAFETY: the entry RVA came from the original image header.
  344. let entry: Entry =
  345. unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) };
  346. // SAFETY: forwarded from the caller of `spawn_main`.
  347. Ok(unsafe { entry(std::ptr::null_mut()) })
  348. })
  349. .context("spawning title main thread")
  350. }
  351. /// Unmaps the image.
  352. ///
  353. /// # Safety
  354. /// No title code may be running or run later, and no pointer into the
  355. /// image may be used afterwards.
  356. pub unsafe fn unload(self) {
  357. // SAFETY: guaranteed by the caller.
  358. unsafe { FreeLibrary(self.module) };
  359. }
  360. }