windows.rs 16 KB

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