windows.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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 prepared = prepare(&original).with_context(|| format!("preparing {}", path.display()))?;
  143. let image = load(&prepared, dirs.1).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. crate::publish::write_if_changed(path, bytes)
  171. .with_context(|| format!("publishing {}", path.display()))
  172. }
  173. impl LoadedImage {
  174. pub fn base(&self) -> usize {
  175. self.module as usize
  176. }
  177. /// Parsed from the original image (imports, entry point, TLS callbacks).
  178. pub fn info(&self) -> &ImageInfo {
  179. &self.info
  180. }
  181. /// Address of an export of the image, if it has one by that name.
  182. pub fn export(&self, name: &str) -> Option<usize> {
  183. let name = CString::new(name).ok()?;
  184. // SAFETY: valid module handle and NUL-terminated name.
  185. unsafe { GetProcAddress(self.module, name.as_ptr().cast()) }
  186. .map(|f| f as *const () as usize)
  187. }
  188. /// Address of an export, by name or ordinal.
  189. pub fn export_symbol(&self, symbol: &ImportSymbol) -> Option<usize> {
  190. match symbol {
  191. ImportSymbol::Name { name, .. } => self.export(name),
  192. // SAFETY: MAKEINTRESOURCE-style ordinal lookup on a valid module.
  193. ImportSymbol::Ordinal(o) => unsafe { GetProcAddress(self.module, *o as usize as _) }
  194. .map(|f| f as *const () as usize),
  195. }
  196. }
  197. /// Fills every IAT slot of the image.
  198. ///
  199. /// Each import goes to `resolver`; whatever it cannot resolve gets an
  200. /// unimplemented-import stub that behaves according to `policy`.
  201. pub fn bind_imports(
  202. &self,
  203. resolver: &dyn ImportResolver,
  204. policy: UnimplementedPolicy,
  205. ) -> Result<BindReport> {
  206. let mut report = BindReport::default();
  207. let mut slots: Vec<(u32, usize)> = Vec::with_capacity(self.info.import_count());
  208. let mut unresolved: Vec<(u32, &str, &ImportSymbol)> = Vec::new();
  209. // Delay-load slots are bound eagerly too, so the title's own
  210. // delay-load helper (which would ask the host) never runs.
  211. for module in self.info.imports.iter().chain(&self.info.delay_imports) {
  212. for entry in &module.entries {
  213. match resolver.resolve(&module.dll, &entry.symbol) {
  214. Resolution::Found {
  215. address,
  216. provenance,
  217. } => {
  218. match provenance {
  219. Provenance::Hle => report.hle += 1,
  220. Provenance::Host => report.host += 1,
  221. Provenance::Title => report.title += 1,
  222. }
  223. slots.push((entry.iat_slot_rva, address));
  224. }
  225. Resolution::Missing => {
  226. unresolved.push((entry.iat_slot_rva, &module.dll, &entry.symbol));
  227. }
  228. }
  229. }
  230. }
  231. if !unresolved.is_empty() {
  232. let mut block = ThunkBlock::new(unresolved.len())?;
  233. for (slot, dll, symbol) in unresolved {
  234. let site: &'static ImportSite = Box::leak(Box::new(ImportSite {
  235. dll: dll.to_owned(),
  236. symbol: symbol.to_string(),
  237. policy,
  238. calls: AtomicU64::new(0),
  239. }));
  240. slots.push((slot, block.emit(site)?));
  241. report.missing.push(MissingImport {
  242. dll: site.dll.clone(),
  243. symbol: site.symbol.clone(),
  244. });
  245. }
  246. block.seal()?;
  247. }
  248. self.write_slots(&slots)?;
  249. tracing::info!(
  250. hle = report.hle,
  251. host = report.host,
  252. missing = report.missing.len(),
  253. "imports bound"
  254. );
  255. Ok(report)
  256. }
  257. /// Protects and restores each slot on its own: import tables can sit in
  258. /// sections with different protections (delay-load tables in `.didat`).
  259. fn write_slots(&self, slots: &[(u32, usize)]) -> Result<()> {
  260. for &(rva, address) in slots {
  261. let slot = (self.base() + rva as usize) as *mut u64;
  262. let mut old = 0;
  263. // SAFETY: the parser only yields slots inside the image.
  264. if unsafe { VirtualProtect(slot as *const c_void, 8, PAGE_READWRITE, &mut old) } == 0 {
  265. bail!(
  266. "VirtualProtect(IAT slot {rva:#x}) failed: {}",
  267. std::io::Error::last_os_error()
  268. );
  269. }
  270. // SAFETY: inside the image, now writable, 8-byte aligned by the PE format.
  271. unsafe { slot.write_volatile(address as u64) };
  272. let mut ignored = 0;
  273. // SAFETY: restoring the protection we just changed.
  274. unsafe { VirtualProtect(slot as *const c_void, 8, old, &mut ignored) };
  275. }
  276. Ok(())
  277. }
  278. /// Calls the image's TLS callbacks with `reason` (e.g. `DLL_PROCESS_ATTACH`).
  279. ///
  280. /// # Safety
  281. /// Runs title code. Imports must be bound first.
  282. pub unsafe fn run_tls_callbacks(&self, reason: u32) {
  283. // SAFETY: forwarded from the caller.
  284. unsafe { self.tls_callbacks(reason, std::ptr::null_mut()) }
  285. }
  286. /// # Safety
  287. /// See [`Self::run_tls_callbacks`].
  288. unsafe fn tls_callbacks(&self, reason: u32, reserved: *mut c_void) {
  289. let Some(tls) = &self.info.tls else { return };
  290. for &rva in &tls.callback_rvas {
  291. type TlsCallback = unsafe extern "system" fn(*mut c_void, u32, *mut c_void);
  292. // SAFETY: the RVA came from the image's own TLS directory.
  293. let callback: TlsCallback = unsafe { std::mem::transmute(self.base() + rva as usize) };
  294. // SAFETY: the caller guarantees imports are bound.
  295. unsafe { callback(self.module, reason, reserved) };
  296. }
  297. }
  298. /// Initialises a DLL as the Windows loader would: its TLS callbacks,
  299. /// then `DllMain(DLL_PROCESS_ATTACH)`. From then on it hears of every
  300. /// thread start and end (see `threads`).
  301. ///
  302. /// # Safety
  303. /// Runs title code. Imports must be bound first, and the DLLs this one
  304. /// depends on attached.
  305. pub unsafe fn attach(&self) -> Result<()> {
  306. // SAFETY: forwarded from the caller.
  307. if unsafe { self.notify(DLL_PROCESS_ATTACH, true, std::ptr::null_mut()) } == Some(0) {
  308. bail!("DllMain returned FALSE");
  309. }
  310. crate::threads::attached(self.base());
  311. Ok(())
  312. }
  313. /// `DLL_PROCESS_DETACH` as `FreeLibrary` sends it (TLS callbacks, then
  314. /// `DllMain`); the image hears of no more threads.
  315. ///
  316. /// # Safety
  317. /// Runs title code. The image must have been attached (or its attach
  318. /// failed), and no other thread may be using it.
  319. pub unsafe fn detach(&self) {
  320. crate::threads::detached(self.base());
  321. // SAFETY: forwarded from the caller.
  322. unsafe { self.notify(DLL_PROCESS_DETACH, true, std::ptr::null_mut()) };
  323. }
  324. /// Runs the image's TLS callbacks with `reason`, then, if `dll_main` and
  325. /// the image is a DLL with an entry point, its `DllMain`, whose result
  326. /// is returned. `reserved` is the entry points' third argument.
  327. ///
  328. /// # Safety
  329. /// Runs title code. Imports must be bound first.
  330. pub(crate) unsafe fn notify(
  331. &self,
  332. reason: u32,
  333. dll_main: bool,
  334. reserved: *mut c_void,
  335. ) -> Option<i32> {
  336. // SAFETY: forwarded from the caller.
  337. unsafe { self.tls_callbacks(reason, reserved) };
  338. if !dll_main || !self.info.is_dll() || self.info.entry_rva == 0 {
  339. return None;
  340. }
  341. type DllMain = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32;
  342. // SAFETY: the entry RVA came from the original image header.
  343. let main: DllMain =
  344. unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) };
  345. // SAFETY: forwarded from the caller.
  346. Some(unsafe { main(self.module, reason, reserved) })
  347. }
  348. /// Starts the title: on a new thread with the stack size from the image
  349. /// header, attaches `dlls` in order (see [`Self::attach`]), runs the
  350. /// image's TLS callbacks (`DLL_PROCESS_ATTACH`), then its original entry
  351. /// point. Returns the thread so the caller can join it.
  352. ///
  353. /// # Safety
  354. /// Runs title code. Imports of the image and of `dlls` must be bound.
  355. pub unsafe fn spawn_main(
  356. self: Arc<Self>,
  357. dlls: Vec<(String, LoadedImage)>,
  358. ) -> Result<std::thread::JoinHandle<Result<u32>>> {
  359. if self.info.entry_rva == 0 {
  360. bail!("image has no entry point");
  361. }
  362. let stack = usize::try_from(self.info.stack_reserve)
  363. .unwrap_or(usize::MAX)
  364. .max(1 << 20);
  365. std::thread::Builder::new()
  366. .name("title-main".into())
  367. .stack_size(stack)
  368. .spawn(move || {
  369. for (name, dll) in &dlls {
  370. // SAFETY: forwarded from the caller of `spawn_main`.
  371. unsafe { dll.attach() }.with_context(|| format!("attaching {name}"))?;
  372. }
  373. // SAFETY: forwarded from the caller of `spawn_main`.
  374. unsafe { self.run_tls_callbacks(DLL_PROCESS_ATTACH) };
  375. crate::threads::attached(self.base());
  376. type Entry = unsafe extern "system" fn(*mut c_void) -> u32;
  377. // SAFETY: the entry RVA came from the original image header.
  378. let entry: Entry =
  379. unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) };
  380. // SAFETY: forwarded from the caller of `spawn_main`.
  381. Ok(unsafe { entry(std::ptr::null_mut()) })
  382. })
  383. .context("spawning title main thread")
  384. }
  385. /// Unmaps the image.
  386. ///
  387. /// # Safety
  388. /// No title code may be running or run later, and no pointer into the
  389. /// image may be used afterwards.
  390. pub unsafe fn unload(self) {
  391. crate::threads::unmapped(self.base());
  392. // SAFETY: guaranteed by the caller.
  393. unsafe { FreeLibrary(self.module) };
  394. }
  395. }