Initial commit

Rust workspace for VIctory: PE analysis, loader, HLE skeleton,
DXBC/DXIL parsing with a GFX10 decoder, conversion cache, CLI and
asset-policy enforcement.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
MarvisandClaude Sonnet 5.5 committed 2026-11-23 01:15:26 +01:00
commit f4504f6413
69 files changed
+7952

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
[package]
name = "victory-loader"
description = "Runs an Xbox title's original x86-64 image natively inside our process."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
victory-core.workspace = true
victory-pe.workspace = true
anyhow.workspace = true
thiserror.workspace = true
tracing.workspace = true
blake3.workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = [
"Win32_Foundation",
"Win32_System_Diagnostics_Debug",
"Win32_System_LibraryLoader",
"Win32_System_Memory",
"Win32_System_Threading",
] }
[dev-dependencies]
tempfile.workspace = true
[lints]
workspace = true
+35
View File
@@ -0,0 +1,35 @@
//! Runs a title's original x86-64 code natively, inside our process.
//!
//! Xbox Series X|S executables are x86-64 PE32+ images built for a Zen 2
//! CPU, so the machine code needs no translation. What differs is the
//! platform underneath, so the loader's job is to:
//!
//! 1. [`prepare`] a lightly patched copy of the image (pure, portable): mark
//! it as a DLL, remove its entry point and import directory, and detach
//! its TLS callbacks, so the Windows loader maps it, relocates it,
//! allocates its static TLS and registers its unwind tables, but runs
//! none of its code and resolves none of its imports;
//! 2. load that copy as a real module (debuggers, profilers, crash dumps
//! and stack walks all see it); this step is Windows-only;
//! 3. bind every import ourselves through an [`ImportResolver`], our
//! runtime (`victory-hle`) or the host, and route anything unresolved
//! to a generated stub that reports exactly what was called;
//! 4. run TLS callbacks and the entry point on a thread with the stack size
//! the image asks for.
pub mod prepare;
pub mod resolve;
#[cfg(windows)]
mod thunks;
#[cfg(windows)]
mod windows;
pub use prepare::{PrepareError, PreparedImage, prepare};
pub use resolve::{ImportResolver, Provenance, Resolution};
#[cfg(windows)]
pub use thunks::{UnimplementedPolicy, unimplemented_call_count};
#[cfg(windows)]
pub use windows::{BindReport, LoadedImage, MissingImport, load};
/// `DLL_PROCESS_ATTACH`, for TLS callbacks.
pub const DLL_PROCESS_ATTACH: u32 = 1;
+141
View File
@@ -0,0 +1,141 @@
//! Turns a title's image into something the Windows loader maps but does
//! not run. Pure byte manipulation, so it is testable on any host.
use victory_pe::layout::{self, dir, dll_flags, file_flags};
use victory_pe::{ImageInfo, PeError};
#[derive(Debug, thiserror::Error)]
pub enum PrepareError {
#[error(transparent)]
Pe(#[from] PeError),
#[error("cannot patch image: {0}")]
Patch(&'static str),
}
/// A patched copy of an image plus everything we need from the original.
#[derive(Debug, Clone)]
pub struct PreparedImage {
/// Parsed from the *original* bytes: imports, TLS callbacks and entry
/// point as the title expects them.
pub info: ImageInfo,
/// The patched bytes to hand to the Windows loader.
pub bytes: Vec<u8>,
/// BLAKE3 of the original bytes: identifies the exact build.
pub original_hash: blake3::Hash,
}
impl PreparedImage {
/// File name for the patched copy, unique per original build.
pub fn file_name(&self) -> String {
format!("victory-image-{}.dll", &self.original_hash.to_hex()[..16])
}
}
/// Produces the patched copy. The changes are:
///
/// * `IMAGE_FILE_DLL` set, entry point cleared: the OS maps it like a DLL
/// and calls nothing;
/// * import and bound-import directories cleared: we bind imports
/// ourselves, using `info.imports` from the original;
/// * TLS callback pointer cleared: the OS still allocates static TLS for
/// the image, but callbacks only run when we call them (after binding);
/// * `FORCE_INTEGRITY` cleared, checksum zeroed: the copy is unsigned.
pub fn prepare(original: &[u8]) -> Result<PreparedImage, PrepareError> {
let info = ImageInfo::parse(original)?;
let mut bytes = original.to_vec();
let fh = layout::file_header_offset(&bytes).ok_or(PrepareError::Patch("no file header"))?;
let opt =
layout::optional_header_offset(&bytes).ok_or(PrepareError::Patch("no optional header"))?;
let characteristics = info.characteristics | file_flags::DLL;
write_u16(
&mut bytes,
fh + layout::FILE_HEADER_CHARACTERISTICS,
characteristics,
)?;
write_u32(&mut bytes, opt + layout::OPT_ADDRESS_OF_ENTRY_POINT, 0)?;
write_u32(&mut bytes, opt + layout::OPT_CHECKSUM, 0)?;
let dll_characteristics = info.dll_characteristics & !dll_flags::FORCE_INTEGRITY;
write_u16(
&mut bytes,
opt + layout::OPT_DLL_CHARACTERISTICS,
dll_characteristics,
)?;
for index in [dir::IMPORT, dir::BOUND_IMPORT] {
if let Some(at) = layout::data_directory_offset(&bytes, index) {
write_u32(&mut bytes, at, 0)?;
write_u32(&mut bytes, at + 4, 0)?;
}
}
if let Some(tls) = &info.tls
&& tls.callbacks_va != 0
{
let at = info
.rva_to_file_offset(tls.directory_rva)
.ok_or(PrepareError::Patch("TLS directory is not file-backed"))?;
write_u64(
&mut bytes,
at as usize + layout::TLS64_ADDRESS_OF_CALLBACKS,
0,
)?;
}
Ok(PreparedImage {
info,
bytes,
original_hash: blake3::hash(original),
})
}
fn write_u16(bytes: &mut [u8], at: usize, v: u16) -> Result<(), PrepareError> {
write(bytes, at, &v.to_le_bytes())
}
fn write_u32(bytes: &mut [u8], at: usize, v: u32) -> Result<(), PrepareError> {
write(bytes, at, &v.to_le_bytes())
}
fn write_u64(bytes: &mut [u8], at: usize, v: u64) -> Result<(), PrepareError> {
write(bytes, at, &v.to_le_bytes())
}
fn write(bytes: &mut [u8], at: usize, v: &[u8]) -> Result<(), PrepareError> {
bytes
.get_mut(at..at + v.len())
.ok_or(PrepareError::Patch("header field outside of file"))?
.copy_from_slice(v);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn patches_own_test_binary() {
let original = std::fs::read(std::env::current_exe().unwrap()).unwrap();
let prepared = prepare(&original).unwrap();
assert!(!prepared.info.is_dll(), "info describes the original");
assert!(prepared.info.import_count() > 0);
let patched = ImageInfo::parse(&prepared.bytes).unwrap();
assert!(patched.is_dll());
assert_eq!(patched.entry_rva, 0);
assert!(patched.imports.is_empty());
assert_eq!(patched.dll_characteristics & dll_flags::FORCE_INTEGRITY, 0);
if let Some(tls) = &patched.tls {
assert_eq!(tls.callbacks_va, 0);
}
// Nothing else moved: same sections, same size.
assert_eq!(patched.sections.len(), prepared.info.sections.len());
assert_eq!(prepared.bytes.len(), original.len());
}
#[test]
fn file_name_is_stable_per_build() {
let original = std::fs::read(std::env::current_exe().unwrap()).unwrap();
let a = prepare(&original).unwrap();
let b = prepare(&original).unwrap();
assert_eq!(a.file_name(), b.file_name());
}
}
+31
View File
@@ -0,0 +1,31 @@
//! How imports get their addresses.
use victory_pe::ImportSymbol;
/// Who provides a bound import.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Provenance {
/// Our implementation of the console API.
Hle,
/// The host's own implementation (e.g. Windows API sets that behave the
/// same on console and PC).
Host,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Resolution {
Found {
address: usize,
provenance: Provenance,
},
/// Nobody implements it; the loader installs a reporting stub.
Missing,
}
/// Supplies an address for each `dll!symbol` the title imports.
///
/// `dll` is passed exactly as written in the image; implementations should
/// compare case-insensitively.
pub trait ImportResolver {
fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution;
}
+149
View File
@@ -0,0 +1,149 @@
//! Stubs for imports nobody implements yet.
//!
//! Each unresolved import gets 32 bytes of generated code:
//!
//! ```text
//! mov rcx, <&'static ImportSite> ; 48 B9 imm64
//! mov rax, <unimplemented_import> ; 48 B8 imm64
//! jmp rax ; FF E0
//! ```
//!
//! The jump keeps the title's return address on the stack, so the handler
//! returns straight to the caller. Bring-up then shows exactly which API to
//! implement next, rather than failing at load time.
use std::sync::atomic::{AtomicU64, Ordering};
use anyhow::{Result, bail};
use windows_sys::Win32::System::Diagnostics::Debug::{
DebugBreak, FlushInstructionCache, IsDebuggerPresent,
};
use windows_sys::Win32::System::Memory::{
MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_READWRITE, VirtualAlloc, VirtualProtect,
};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
/// What an unimplemented import does when called.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum UnimplementedPolicy {
/// Log, break into an attached debugger, then abort. The default:
/// silently continuing usually crashes later and further from the cause.
#[default]
Trap,
/// Log once per import and return 0. Useful to push through bring-up.
ReturnZero,
}
/// Identifies one unresolved import. Leaked: lives as long as the process.
#[derive(Debug)]
pub struct ImportSite {
pub dll: String,
pub symbol: String,
pub policy: UnimplementedPolicy,
pub calls: AtomicU64,
}
static UNIMPLEMENTED_CALLS: AtomicU64 = AtomicU64::new(0);
/// Total number of calls that reached an unimplemented-import stub.
pub fn unimplemented_call_count() -> u64 {
UNIMPLEMENTED_CALLS.load(Ordering::Relaxed)
}
extern "system" fn unimplemented_import(site: &'static ImportSite) -> u64 {
UNIMPLEMENTED_CALLS.fetch_add(1, Ordering::Relaxed);
let previous = site.calls.fetch_add(1, Ordering::Relaxed);
match site.policy {
UnimplementedPolicy::ReturnZero => {
if previous == 0 {
tracing::warn!(dll = %site.dll, symbol = %site.symbol, "unimplemented import called, returning 0");
}
0
}
UnimplementedPolicy::Trap => {
tracing::error!(dll = %site.dll, symbol = %site.symbol, "unimplemented import called");
eprintln!(
"VIctory: unimplemented import {}!{} called",
site.dll, site.symbol
);
// SAFETY: plain Win32 calls without preconditions.
unsafe {
if IsDebuggerPresent() != 0 {
DebugBreak();
}
}
std::process::abort();
}
}
}
const THUNK_SIZE: usize = 32;
/// Executable memory holding one stub per unresolved import.
pub(crate) struct ThunkBlock {
base: *mut u8,
len: usize,
used: usize,
}
impl ThunkBlock {
/// Reserves room for `count` stubs (writable until [`Self::seal`]).
pub(crate) fn new(count: usize) -> Result<Self> {
let len = (count.max(1) * THUNK_SIZE).next_multiple_of(4096);
// SAFETY: fresh anonymous allocation; no existing memory is touched.
let base = unsafe {
VirtualAlloc(
std::ptr::null(),
len,
MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE,
)
} as *mut u8;
if base.is_null() {
bail!(
"VirtualAlloc for import stubs failed: {}",
std::io::Error::last_os_error()
);
}
Ok(ThunkBlock { base, len, used: 0 })
}
/// Emits a stub for `site` and returns its address.
pub(crate) fn emit(&mut self, site: &'static ImportSite) -> Result<usize> {
if self.used + THUNK_SIZE > self.len {
bail!("import stub block is full");
}
let mut code = [0xCC_u8; THUNK_SIZE]; // int3 padding
code[0..2].copy_from_slice(&[0x48, 0xB9]);
code[2..10].copy_from_slice(&(site as *const ImportSite as u64).to_le_bytes());
code[10..12].copy_from_slice(&[0x48, 0xB8]);
let handler = unimplemented_import as extern "system" fn(&'static ImportSite) -> u64;
code[12..20].copy_from_slice(&(handler as *const () as u64).to_le_bytes());
code[20..22].copy_from_slice(&[0xFF, 0xE0]);
// SAFETY: `used + THUNK_SIZE <= len`, and the block is still writable.
let at = unsafe {
let at = self.base.add(self.used);
std::ptr::copy_nonoverlapping(code.as_ptr(), at, THUNK_SIZE);
at
};
self.used += THUNK_SIZE;
Ok(at as usize)
}
/// Makes the block read+execute. The block is intentionally leaked:
/// title code may hold these addresses for the life of the process.
pub(crate) fn seal(self) -> Result<()> {
let mut old = 0;
// SAFETY: `base..base+len` is the allocation made in `new`.
let ok = unsafe { VirtualProtect(self.base as _, self.len, PAGE_EXECUTE_READ, &mut old) };
if ok == 0 {
bail!(
"VirtualProtect for import stubs failed: {}",
std::io::Error::last_os_error()
);
}
// SAFETY: flushing our own process's instruction cache for our own block.
unsafe { FlushInstructionCache(GetCurrentProcess(), self.base as _, self.len) };
Ok(())
}
}
+250
View File
@@ -0,0 +1,250 @@
//! Loading a prepared image as a real Windows module and binding it.
use std::ffi::{CString, c_void};
use std::os::windows::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicU64;
use anyhow::{Context, Result, bail};
use victory_pe::{ImageInfo, ImportSymbol};
use windows_sys::Win32::Foundation::{FreeLibrary, HMODULE};
use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryExW};
use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect};
use crate::thunks::{ImportSite, ThunkBlock, UnimplementedPolicy};
use crate::{DLL_PROCESS_ATTACH, ImportResolver, PreparedImage, Provenance, Resolution};
/// A title image mapped into this process.
#[derive(Debug)]
pub struct LoadedImage {
module: HMODULE,
path: PathBuf,
info: ImageInfo,
}
// SAFETY: HMODULE is a process-wide handle (the base address); using it from
// any thread is fine.
unsafe impl Send for LoadedImage {}
// SAFETY: as above; `LoadedImage` has no interior mutability.
unsafe impl Sync for LoadedImage {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MissingImport {
pub dll: String,
pub symbol: String,
}
/// Outcome of [`LoadedImage::bind_imports`].
#[derive(Debug, Default, Clone)]
pub struct BindReport {
pub hle: usize,
pub host: usize,
pub missing: Vec<MissingImport>,
}
/// Writes the prepared copy into `dir` and maps it with the Windows loader.
///
/// `dir` receives derived game data, so it must be outside the repository.
pub fn load(prepared: &PreparedImage, dir: &Path) -> Result<LoadedImage> {
victory_core::ensure_outside_repo(dir)?;
std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
let path = dir.join(prepared.file_name());
write_if_changed(&path, &prepared.bytes)?;
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
// SAFETY: `wide` is a NUL-terminated path. The image has no entry point
// and no imports, so loading it runs no title code.
let module = unsafe { LoadLibraryExW(wide.as_ptr(), std::ptr::null_mut(), 0) };
if module.is_null() {
bail!(
"LoadLibraryExW({}) failed: {}{}",
path.display(),
std::io::Error::last_os_error(),
if prepared.info.has_relocations {
""
} else {
" (image has no relocations; its preferred base may be taken)"
}
);
}
let loaded = LoadedImage {
module,
path,
info: prepared.info.clone(),
};
tracing::info!(
base = format_args!("{:#x}", loaded.base()),
preferred = format_args!("{:#x}", loaded.info.image_base),
path = %loaded.path.display(),
"image mapped"
);
Ok(loaded)
}
fn write_if_changed(path: &Path, bytes: &[u8]) -> Result<()> {
if std::fs::read(path).is_ok_and(|existing| existing == bytes) {
return Ok(());
}
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, bytes).with_context(|| format!("writing {}", tmp.display()))?;
std::fs::rename(&tmp, path).with_context(|| format!("renaming to {}", path.display()))?;
Ok(())
}
impl LoadedImage {
pub fn base(&self) -> usize {
self.module as usize
}
/// Parsed from the original image (imports, entry point, TLS callbacks).
pub fn info(&self) -> &ImageInfo {
&self.info
}
/// Address of an export of the image, if it has one by that name.
pub fn export(&self, name: &str) -> Option<usize> {
let name = CString::new(name).ok()?;
// SAFETY: valid module handle and NUL-terminated name.
unsafe { GetProcAddress(self.module, name.as_ptr().cast()) }
.map(|f| f as *const () as usize)
}
/// Fills every IAT slot of the image.
///
/// Each import goes to `resolver`; whatever it cannot resolve gets an
/// unimplemented-import stub that behaves according to `policy`.
pub fn bind_imports(
&self,
resolver: &dyn ImportResolver,
policy: UnimplementedPolicy,
) -> Result<BindReport> {
let mut report = BindReport::default();
let mut slots: Vec<(u32, usize)> = Vec::with_capacity(self.info.import_count());
let mut unresolved: Vec<(u32, &str, &ImportSymbol)> = Vec::new();
// Delay-load slots are bound eagerly too, so the title's own
// delay-load helper (which would ask the host) never runs.
for module in self.info.imports.iter().chain(&self.info.delay_imports) {
for entry in &module.entries {
match resolver.resolve(&module.dll, &entry.symbol) {
Resolution::Found {
address,
provenance,
} => {
match provenance {
Provenance::Hle => report.hle += 1,
Provenance::Host => report.host += 1,
}
slots.push((entry.iat_slot_rva, address));
}
Resolution::Missing => {
unresolved.push((entry.iat_slot_rva, &module.dll, &entry.symbol));
}
}
}
}
if !unresolved.is_empty() {
let mut block = ThunkBlock::new(unresolved.len())?;
for (slot, dll, symbol) in unresolved {
let site: &'static ImportSite = Box::leak(Box::new(ImportSite {
dll: dll.to_owned(),
symbol: symbol.to_string(),
policy,
calls: AtomicU64::new(0),
}));
slots.push((slot, block.emit(site)?));
report.missing.push(MissingImport {
dll: site.dll.clone(),
symbol: site.symbol.clone(),
});
}
block.seal()?;
}
self.write_slots(&slots)?;
tracing::info!(
hle = report.hle,
host = report.host,
missing = report.missing.len(),
"imports bound"
);
Ok(report)
}
/// Protects and restores each slot on its own: import tables can sit in
/// sections with different protections (delay-load tables in `.didat`).
fn write_slots(&self, slots: &[(u32, usize)]) -> Result<()> {
for &(rva, address) in slots {
let slot = (self.base() + rva as usize) as *mut u64;
let mut old = 0;
// SAFETY: the parser only yields slots inside the image.
if unsafe { VirtualProtect(slot as *const c_void, 8, PAGE_READWRITE, &mut old) } == 0 {
bail!(
"VirtualProtect(IAT slot {rva:#x}) failed: {}",
std::io::Error::last_os_error()
);
}
// SAFETY: inside the image, now writable, 8-byte aligned by the PE format.
unsafe { slot.write_volatile(address as u64) };
let mut ignored = 0;
// SAFETY: restoring the protection we just changed.
unsafe { VirtualProtect(slot as *const c_void, 8, old, &mut ignored) };
}
Ok(())
}
/// Calls the image's TLS callbacks with `reason` (e.g. `DLL_PROCESS_ATTACH`).
///
/// # Safety
/// Runs title code. Imports must be bound first.
pub unsafe fn run_tls_callbacks(&self, reason: u32) {
let Some(tls) = &self.info.tls else { return };
for &rva in &tls.callback_rvas {
type TlsCallback = unsafe extern "system" fn(*mut c_void, u32, *mut c_void);
// SAFETY: the RVA came from the image's own TLS directory.
let callback: TlsCallback = unsafe { std::mem::transmute(self.base() + rva as usize) };
// SAFETY: the caller guarantees imports are bound.
unsafe { callback(self.module, reason, std::ptr::null_mut()) };
}
}
/// Starts the title: on a new thread with the stack size from the image
/// header, runs the TLS callbacks (`DLL_PROCESS_ATTACH`), then the
/// original entry point. Returns the thread so the caller can join it.
///
/// # Safety
/// Runs title code. Imports must be bound first.
pub unsafe fn spawn_main(self: std::sync::Arc<Self>) -> Result<std::thread::JoinHandle<u32>> {
if self.info.entry_rva == 0 {
bail!("image has no entry point");
}
let stack = usize::try_from(self.info.stack_reserve)
.unwrap_or(usize::MAX)
.max(1 << 20);
std::thread::Builder::new()
.name("title-main".into())
.stack_size(stack)
.spawn(move || {
// SAFETY: forwarded from the caller of `spawn_main`.
unsafe { self.run_tls_callbacks(DLL_PROCESS_ATTACH) };
type Entry = unsafe extern "system" fn(*mut c_void) -> u32;
// SAFETY: the entry RVA came from the original image header.
let entry: Entry =
unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) };
// SAFETY: forwarded from the caller of `spawn_main`.
unsafe { entry(std::ptr::null_mut()) }
})
.context("spawning title main thread")
}
/// Unmaps the image.
///
/// # Safety
/// No title code may be running or run later, and no pointer into the
/// image may be used afterwards.
pub unsafe fn unload(self) {
// SAFETY: guaranteed by the caller.
unsafe { FreeLibrary(self.module) };
}
}
+155
View File
@@ -0,0 +1,155 @@
//! End-to-end: prepare, load, bind and call into a stand-in title
//! (tests/fixtures/hle-probe), without any game data.
#![cfg(windows)]
use std::ffi::CString;
use std::path::{Path, PathBuf};
use std::process::Command;
use victory_loader::{
ImportResolver, Provenance, Resolution, UnimplementedPolicy, prepare, unimplemented_call_count,
};
use victory_pe::ImportSymbol;
use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA};
fn workspace_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..")
}
/// Builds the fixture into its own target dir (the outer cargo holds the
/// lock on the main one while tests run).
fn build_probe() -> PathBuf {
let root = workspace_root();
let manifest = root.join("tests/fixtures/hle-probe/Cargo.toml");
let target = root.join("target/fixtures");
let status = Command::new(env!("CARGO"))
.args(["build", "--quiet", "--manifest-path"])
.arg(&manifest)
.arg("--target-dir")
.arg(&target)
.status()
.expect("running cargo");
assert!(status.success(), "building hle-probe failed");
target.join("debug").join("hle_probe.dll")
}
extern "system" fn fake_xgameruntime_initialize() -> i32 {
0x1234
}
extern "system" fn fake_get_tick_count() -> u32 {
777
}
extern "system" fn fake_delayed() -> u32 {
4242
}
struct TestResolver;
impl ImportResolver for TestResolver {
fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution {
let dll = dll.to_ascii_lowercase();
let ImportSymbol::Name { name, .. } = symbol else {
return Resolution::Missing;
};
let hle = match (dll.as_str(), name.as_str()) {
("xgameruntime.dll", "XGameRuntimeInitialize") => {
Some(fake_xgameruntime_initialize as *const () as usize)
}
("kernel32.dll", "GetTickCount") => Some(fake_get_tick_count as *const () as usize),
("victory-probe-delayed.dll", "VIctoryProbeDelayed") => {
Some(fake_delayed as *const () as usize)
}
_ => None,
};
if let Some(address) = hle {
return Resolution::Found {
address,
provenance: Provenance::Hle,
};
}
host(&dll, name)
.map(|address| Resolution::Found {
address,
provenance: Provenance::Host,
})
.unwrap_or(Resolution::Missing)
}
}
fn host(dll: &str, name: &str) -> Option<usize> {
let dll = CString::new(dll).ok()?;
let name = CString::new(name).ok()?;
// SAFETY: NUL-terminated strings; loading system DLLs into the test process.
unsafe {
let module = LoadLibraryA(dll.as_ptr().cast());
if module.is_null() {
return None;
}
GetProcAddress(module, name.as_ptr().cast()).map(|f| f as *const () as usize)
}
}
#[test]
fn loads_binds_and_calls_probe() {
let dll = build_probe();
let original = std::fs::read(&dll).unwrap();
let prepared = prepare(&original).unwrap();
let imports: Vec<_> = prepared
.info
.imports
.iter()
.map(|m| m.dll.to_ascii_lowercase())
.collect();
assert!(
imports.contains(&"xgameruntime.dll".to_owned()),
"{imports:?}"
);
assert!(
imports.contains(&"victory-probe-missing.dll".to_owned()),
"{imports:?}"
);
assert!(
prepared
.info
.delay_imports
.iter()
.any(|m| m.dll.eq_ignore_ascii_case("victory-probe-delayed.dll")),
"fixture must delay-load victory-probe-delayed.dll"
);
let dir = tempfile::tempdir().unwrap();
let image = victory_loader::load(&prepared, dir.path()).unwrap();
let report = image
.bind_imports(&TestResolver, UnimplementedPolicy::ReturnZero)
.unwrap();
assert_eq!(report.hle, 3);
assert!(report.host > 0);
assert_eq!(report.missing.len(), 1);
assert_eq!(report.missing[0].symbol, "VIctoryProbeNotImplemented");
let call = |name: &str| -> usize { image.export(name).unwrap_or_else(|| panic!("{name}")) };
// SAFETY: the exports have the signatures declared in the fixture and
// every import they use has been bound.
unsafe {
let f: extern "system" fn() -> i32 = std::mem::transmute(call("probe_xgameruntime_init"));
assert_eq!(f(), 0x1234, "console API must reach our implementation");
let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_tick"));
assert_eq!(f(), 777, "host API must be overridable");
let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_pid"));
assert_eq!(f(), std::process::id(), "host API must pass through");
let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_delayed"));
assert_eq!(f(), 4242, "delay-loaded API must be bound");
let before = unimplemented_call_count();
let f: extern "system" fn() -> u64 = std::mem::transmute(call("probe_missing"));
assert_eq!(f(), 0);
assert_eq!(unimplemented_call_count(), before + 1);
image.unload();
}
}