load_probe.rs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. //! End-to-end: prepare, load, bind and call into a stand-in title
  2. //! (tests/fixtures/hle-probe), without any game data.
  3. #![cfg(windows)]
  4. use std::ffi::CString;
  5. use std::path::{Path, PathBuf};
  6. use std::process::Command;
  7. use victory_loader::{
  8. ImportResolver, Provenance, Resolution, UnimplementedPolicy, WithTitleDlls, prepare,
  9. unimplemented_call_count,
  10. };
  11. use victory_pe::ImportSymbol;
  12. use windows_sys::Win32::Foundation::CloseHandle;
  13. use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA};
  14. use windows_sys::Win32::System::Threading::{CreateThread, INFINITE, WaitForSingleObject};
  15. fn workspace_root() -> PathBuf {
  16. Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..")
  17. }
  18. /// Builds the fixture into its own target dir (the outer cargo holds the
  19. /// lock on the main one while tests run), in the outer one's scratch folder
  20. /// for tests, so that it follows `CARGO_TARGET_DIR` like the rest of the
  21. /// build.
  22. fn build_probe() -> PathBuf {
  23. let manifest = workspace_root().join("tests/fixtures/hle-probe/Cargo.toml");
  24. let target = Path::new(env!("CARGO_TARGET_TMPDIR")).join("hle-probe");
  25. let status = Command::new(env!("CARGO"))
  26. .args(["build", "--quiet", "--manifest-path"])
  27. .arg(&manifest)
  28. .arg("--target-dir")
  29. .arg(&target)
  30. .status()
  31. .expect("running cargo");
  32. assert!(status.success(), "building hle-probe failed");
  33. target.join("debug").join("hle_probe.dll")
  34. }
  35. extern "system" fn fake_xgameruntime_initialize() -> i32 {
  36. 0x1234
  37. }
  38. /// Asks for the current thread, as our logging does: on a thread std is
  39. /// still starting, that must not abort the process.
  40. extern "system" fn fake_get_tick_count() -> u32 {
  41. let _ = std::thread::current().id();
  42. 777
  43. }
  44. extern "system" fn fake_delayed() -> u32 {
  45. 4242
  46. }
  47. struct TestResolver;
  48. impl ImportResolver for TestResolver {
  49. fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution {
  50. let dll = dll.to_ascii_lowercase();
  51. let ImportSymbol::Name { name, .. } = symbol else {
  52. return Resolution::Missing;
  53. };
  54. let hle = match (dll.as_str(), name.as_str()) {
  55. ("xgameruntime.dll", "XGameRuntimeInitialize") => {
  56. Some(fake_xgameruntime_initialize as *const () as usize)
  57. }
  58. ("kernel32.dll", "GetTickCount") => Some(fake_get_tick_count as *const () as usize),
  59. ("victory-probe-delayed.dll", "VIctoryProbeDelayed") => {
  60. Some(fake_delayed as *const () as usize)
  61. }
  62. _ => None,
  63. };
  64. if let Some(address) = hle {
  65. return Resolution::Found {
  66. address,
  67. provenance: Provenance::Hle,
  68. };
  69. }
  70. host(&dll, name)
  71. .map(|address| Resolution::Found {
  72. address,
  73. provenance: Provenance::Host,
  74. })
  75. .unwrap_or(Resolution::Missing)
  76. }
  77. }
  78. fn host(dll: &str, name: &str) -> Option<usize> {
  79. let dll = CString::new(dll).ok()?;
  80. let name = CString::new(name).ok()?;
  81. // SAFETY: NUL-terminated strings; loading system DLLs into the test process.
  82. unsafe {
  83. let module = LoadLibraryA(dll.as_ptr().cast());
  84. if module.is_null() {
  85. return None;
  86. }
  87. GetProcAddress(module, name.as_ptr().cast()).map(|f| f as *const () as usize)
  88. }
  89. }
  90. #[test]
  91. fn loads_binds_and_calls_probe() {
  92. let dll = build_probe();
  93. let original = std::fs::read(&dll).unwrap();
  94. let prepared = prepare(&original).unwrap();
  95. let imports: Vec<_> = prepared
  96. .info
  97. .imports
  98. .iter()
  99. .map(|m| m.dll.to_ascii_lowercase())
  100. .collect();
  101. assert!(
  102. imports.contains(&"xgameruntime.dll".to_owned()),
  103. "{imports:?}"
  104. );
  105. assert!(
  106. imports.contains(&"victory-probe-missing.dll".to_owned()),
  107. "{imports:?}"
  108. );
  109. assert!(
  110. prepared
  111. .info
  112. .delay_imports
  113. .iter()
  114. .any(|m| m.dll.eq_ignore_ascii_case("victory-probe-delayed.dll")),
  115. "fixture must delay-load victory-probe-delayed.dll"
  116. );
  117. let dir = tempfile::tempdir().unwrap();
  118. let image = victory_loader::load(&prepared, dir.path()).unwrap();
  119. // The "title" ships victory-probe-title.dll: any real DLL will do.
  120. let title_dir = tempfile::tempdir().unwrap();
  121. std::fs::copy(
  122. r"C:\Windows\System32\version.dll",
  123. title_dir.path().join("victory-probe-title.dll"),
  124. )
  125. .unwrap();
  126. let dlls =
  127. victory_loader::load_title_dlls(image.info(), title_dir.path(), dir.path(), &|_| true)
  128. .unwrap();
  129. let names: Vec<_> = dlls.iter().map(|(n, _)| n.as_str()).collect();
  130. assert_eq!(names, ["victory-probe-title.dll"]);
  131. let resolver = WithTitleDlls {
  132. inner: &TestResolver,
  133. dlls: &dlls,
  134. };
  135. for (_, dll) in &dlls {
  136. dll.bind_imports(&resolver, UnimplementedPolicy::ReturnZero)
  137. .unwrap();
  138. // SAFETY: its imports are bound, and it depends on no other title DLL.
  139. unsafe { dll.attach() }.unwrap();
  140. }
  141. let report = image
  142. .bind_imports(&resolver, UnimplementedPolicy::ReturnZero)
  143. .unwrap();
  144. assert_eq!(report.title, 1);
  145. assert_eq!(report.hle, 3);
  146. assert!(report.host > 0);
  147. assert_eq!(report.missing.len(), 1);
  148. assert_eq!(report.missing[0].symbol, "VIctoryProbeNotImplemented");
  149. let call = |name: &str| -> usize { image.export(name).unwrap_or_else(|| panic!("{name}")) };
  150. // SAFETY: the exports have the signatures declared in the fixture and
  151. // every import they use has been bound.
  152. unsafe {
  153. let f: extern "system" fn() -> i32 = std::mem::transmute(call("probe_xgameruntime_init"));
  154. assert_eq!(f(), 0x1234, "console API must reach our implementation");
  155. let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_tick"));
  156. assert_eq!(f(), 777, "host API must be overridable");
  157. let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_pid"));
  158. assert_eq!(f(), std::process::id(), "host API must pass through");
  159. let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_title"));
  160. assert_ne!(f(), 0, "title DLL export must be bound");
  161. let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_delayed"));
  162. assert_eq!(f(), 4242, "delay-loaded API must be bound");
  163. let before = unimplemented_call_count();
  164. let f: extern "system" fn() -> u64 = std::mem::transmute(call("probe_missing"));
  165. assert_eq!(f(), 0);
  166. assert_eq!(unimplemented_call_count(), before + 1);
  167. // Once attached, every thread start reaches its TLS callback and
  168. // DllMain (other tests may start threads too, hence at least one).
  169. assert!(
  170. image
  171. .info()
  172. .tls
  173. .as_ref()
  174. .is_some_and(|t| !t.callback_rvas.is_empty())
  175. );
  176. image.attach().unwrap();
  177. let f: extern "system" fn() -> u64 = std::mem::transmute(call("probe_thread_starts"));
  178. let before = f();
  179. // A thread std starts, as our runtime's workers are: notified
  180. // before std sets it up, which must still find its state pristine.
  181. let worker = std::thread::Builder::new()
  182. .name("probe-worker".into())
  183. .spawn(|| std::thread::current().name().map(str::to_owned))
  184. .unwrap();
  185. assert_eq!(worker.join().unwrap().as_deref(), Some("probe-worker"));
  186. let mid = f();
  187. assert!(mid >> 32 > before >> 32 && mid as u32 > before as u32);
  188. let before = mid;
  189. // Starting in title code, as a title's threads do; the extra
  190. // argument is ignored.
  191. let start: unsafe extern "system" fn(*mut std::ffi::c_void) -> u32 =
  192. std::mem::transmute(call("probe_pid"));
  193. let thread = CreateThread(
  194. std::ptr::null(),
  195. 0,
  196. Some(start),
  197. std::ptr::null(),
  198. 0,
  199. std::ptr::null_mut(),
  200. );
  201. assert!(!thread.is_null());
  202. WaitForSingleObject(thread, INFINITE);
  203. CloseHandle(thread);
  204. let after = f();
  205. assert!(
  206. after >> 32 > before >> 32,
  207. "TLS callback: {before:#x} → {after:#x}"
  208. );
  209. assert!(
  210. after as u32 > before as u32,
  211. "DllMain: {before:#x} → {after:#x}"
  212. );
  213. // It has static TLS, so Windows would refuse too.
  214. assert_eq!(
  215. victory_loader::disable_thread_calls(image.base()),
  216. Some(false)
  217. );
  218. assert_eq!(victory_loader::disable_thread_calls(1), None);
  219. // `FreeLibrary`'s notice, as a failed late load sends it.
  220. let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_detaches"));
  221. assert_eq!(f(), 0);
  222. image.detach();
  223. assert_eq!(f(), 1);
  224. image.unload();
  225. }
  226. }
  227. #[test]
  228. fn maps_a_title_dll_the_title_loads_itself() {
  229. let title_dir = tempfile::tempdir().unwrap();
  230. let cache = tempfile::tempdir().unwrap();
  231. // Any real DLL will do; it imports only host DLLs, which are not in the folder.
  232. std::fs::copy(
  233. r"C:\Windows\System32\version.dll",
  234. title_dir.path().join("Late.dll"),
  235. )
  236. .unwrap();
  237. let load = |name: &str, wanted: &dyn Fn(&str) -> bool| {
  238. victory_loader::load_title_dll(name, title_dir.path(), cache.path(), wanted).unwrap()
  239. };
  240. let dlls = load("LATE.DLL", &|_| true);
  241. let names: Vec<_> = dlls.iter().map(|(n, _)| n.as_str()).collect();
  242. assert_eq!(names, ["late.dll"]);
  243. assert!(dlls[0].1.export("GetFileVersionInfoW").is_some());
  244. assert!(load("absent.dll", &|_| true).is_empty());
  245. assert!(load("late.dll", &|_| false).is_empty());
  246. }