load_probe.rs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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, prepare, unimplemented_call_count,
  9. };
  10. use victory_pe::ImportSymbol;
  11. use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA};
  12. fn workspace_root() -> PathBuf {
  13. Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..")
  14. }
  15. /// Builds the fixture into its own target dir (the outer cargo holds the
  16. /// lock on the main one while tests run).
  17. fn build_probe() -> PathBuf {
  18. let root = workspace_root();
  19. let manifest = root.join("tests/fixtures/hle-probe/Cargo.toml");
  20. let target = root.join("target/fixtures");
  21. let status = Command::new(env!("CARGO"))
  22. .args(["build", "--quiet", "--manifest-path"])
  23. .arg(&manifest)
  24. .arg("--target-dir")
  25. .arg(&target)
  26. .status()
  27. .expect("running cargo");
  28. assert!(status.success(), "building hle-probe failed");
  29. target.join("debug").join("hle_probe.dll")
  30. }
  31. extern "system" fn fake_xgameruntime_initialize() -> i32 {
  32. 0x1234
  33. }
  34. extern "system" fn fake_get_tick_count() -> u32 {
  35. 777
  36. }
  37. extern "system" fn fake_delayed() -> u32 {
  38. 4242
  39. }
  40. struct TestResolver;
  41. impl ImportResolver for TestResolver {
  42. fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution {
  43. let dll = dll.to_ascii_lowercase();
  44. let ImportSymbol::Name { name, .. } = symbol else {
  45. return Resolution::Missing;
  46. };
  47. let hle = match (dll.as_str(), name.as_str()) {
  48. ("xgameruntime.dll", "XGameRuntimeInitialize") => {
  49. Some(fake_xgameruntime_initialize as *const () as usize)
  50. }
  51. ("kernel32.dll", "GetTickCount") => Some(fake_get_tick_count as *const () as usize),
  52. ("victory-probe-delayed.dll", "VIctoryProbeDelayed") => {
  53. Some(fake_delayed as *const () as usize)
  54. }
  55. _ => None,
  56. };
  57. if let Some(address) = hle {
  58. return Resolution::Found {
  59. address,
  60. provenance: Provenance::Hle,
  61. };
  62. }
  63. host(&dll, name)
  64. .map(|address| Resolution::Found {
  65. address,
  66. provenance: Provenance::Host,
  67. })
  68. .unwrap_or(Resolution::Missing)
  69. }
  70. }
  71. fn host(dll: &str, name: &str) -> Option<usize> {
  72. let dll = CString::new(dll).ok()?;
  73. let name = CString::new(name).ok()?;
  74. // SAFETY: NUL-terminated strings; loading system DLLs into the test process.
  75. unsafe {
  76. let module = LoadLibraryA(dll.as_ptr().cast());
  77. if module.is_null() {
  78. return None;
  79. }
  80. GetProcAddress(module, name.as_ptr().cast()).map(|f| f as *const () as usize)
  81. }
  82. }
  83. #[test]
  84. fn loads_binds_and_calls_probe() {
  85. let dll = build_probe();
  86. let original = std::fs::read(&dll).unwrap();
  87. let prepared = prepare(&original).unwrap();
  88. let imports: Vec<_> = prepared
  89. .info
  90. .imports
  91. .iter()
  92. .map(|m| m.dll.to_ascii_lowercase())
  93. .collect();
  94. assert!(
  95. imports.contains(&"xgameruntime.dll".to_owned()),
  96. "{imports:?}"
  97. );
  98. assert!(
  99. imports.contains(&"victory-probe-missing.dll".to_owned()),
  100. "{imports:?}"
  101. );
  102. assert!(
  103. prepared
  104. .info
  105. .delay_imports
  106. .iter()
  107. .any(|m| m.dll.eq_ignore_ascii_case("victory-probe-delayed.dll")),
  108. "fixture must delay-load victory-probe-delayed.dll"
  109. );
  110. let dir = tempfile::tempdir().unwrap();
  111. let image = victory_loader::load(&prepared, dir.path()).unwrap();
  112. let report = image
  113. .bind_imports(&TestResolver, UnimplementedPolicy::ReturnZero)
  114. .unwrap();
  115. assert_eq!(report.hle, 3);
  116. assert!(report.host > 0);
  117. assert_eq!(report.missing.len(), 1);
  118. assert_eq!(report.missing[0].symbol, "VIctoryProbeNotImplemented");
  119. let call = |name: &str| -> usize { image.export(name).unwrap_or_else(|| panic!("{name}")) };
  120. // SAFETY: the exports have the signatures declared in the fixture and
  121. // every import they use has been bound.
  122. unsafe {
  123. let f: extern "system" fn() -> i32 = std::mem::transmute(call("probe_xgameruntime_init"));
  124. assert_eq!(f(), 0x1234, "console API must reach our implementation");
  125. let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_tick"));
  126. assert_eq!(f(), 777, "host API must be overridable");
  127. let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_pid"));
  128. assert_eq!(f(), std::process::id(), "host API must pass through");
  129. let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_delayed"));
  130. assert_eq!(f(), 4242, "delay-loaded API must be bound");
  131. let before = unimplemented_call_count();
  132. let f: extern "system" fn() -> u64 = std::mem::transmute(call("probe_missing"));
  133. assert_eq!(f(), 0);
  134. assert_eq!(unimplemented_call_count(), before + 1);
  135. image.unload();
  136. }
  137. }