Run Minecraft: runtime HLE, D3D12.X device on the host GPU, shader IR

Loader: map title-shipped DLLs, patch static TLS loads to slot 0, crash
reporter, title paths for GetModuleFileName*.

HLE: task queue and async, XUser (one offline user), system ids,
title id, features, invites, game events, persistent local storage,
GameInput with no devices, xmem, console audio hardware queues, life
cycle (close suspends, then terminates), and a file layer with virtual
drives rewritten in path-taking imports.

GPU: D3D12.X device, DXGI chain, heaps, resources, fences, queues and
command lists translated onto a host D3D12 device; clears, barriers,
copies, resolves and PresentX into the title's window.

Shaders: SGD5 reader and `victory translate`; SSA IR with node
splitting for irreducible flow; structurisation removing EXEC.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MarvisandClaude Opus 5.5 committed 2026-11-23 14:42:21 +01:00
1 parent 12caefe804
commit 754619f30e
61 files changed
+12775 -88

No files matched your search

+1
View File
@@ -19,6 +19,7 @@ blake3.workspace = true
windows-sys = { workspace = true, features = [
"Win32_Foundation",
"Win32_System_Diagnostics_Debug",
"Win32_System_Kernel",
"Win32_System_LibraryLoader",
"Win32_System_Memory",
"Win32_System_Threading",
+101
View File
@@ -0,0 +1,101 @@
//! Names the faulting code when title code crashes.
//!
//! A vectored handler sees every exception first, so it only logs the kinds
//! that end a process (access violations and the like) and leaves handling
//! to the title's own handlers.
use windows_sys::Win32::Foundation::{
EXCEPTION_ACCESS_VIOLATION, EXCEPTION_ILLEGAL_INSTRUCTION, EXCEPTION_INT_DIVIDE_BY_ZERO,
EXCEPTION_PRIV_INSTRUCTION, EXCEPTION_STACK_OVERFLOW, HMODULE,
};
use windows_sys::Win32::System::Diagnostics::Debug::{
AddVectoredExceptionHandler, EXCEPTION_POINTERS,
};
use windows_sys::Win32::System::LibraryLoader::{
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
GetModuleFileNameW, GetModuleHandleExW,
};
const EXCEPTION_CONTINUE_SEARCH: i32 = 0;
/// Stack slots scanned for return addresses into a module.
const STACK_SCAN: usize = 64;
/// Installs the handler; call once before running title code.
pub fn report_crashes() {
// SAFETY: registers a handler that only reads the exception it is given.
unsafe { AddVectoredExceptionHandler(0, Some(handler)) };
}
unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 {
// SAFETY: the system passes valid exception pointers.
let (record, context) = unsafe { (&*(*info).ExceptionRecord, &*(*info).ContextRecord) };
let code = record.ExceptionCode;
if ![
EXCEPTION_ACCESS_VIOLATION,
EXCEPTION_ILLEGAL_INSTRUCTION,
EXCEPTION_PRIV_INSTRUCTION,
EXCEPTION_INT_DIVIDE_BY_ZERO,
EXCEPTION_STACK_OVERFLOW,
]
.contains(&code)
{
return EXCEPTION_CONTINUE_SEARCH;
}
let at = record.ExceptionAddress as usize;
let access = if code == EXCEPTION_ACCESS_VIOLATION {
let kind = match record.ExceptionInformation[0] {
0 => "read",
1 => "write",
_ => "execute",
};
format!(" ({kind} {:#x})", record.ExceptionInformation[1])
} else {
String::new()
};
eprintln!(
"VIctory: exception {:#010x} at {}{access}",
code as u32,
locate(at)
);
eprintln!(
" rax {:#x} rbx {:#x} rcx {:#x} rdx {:#x} rsi {:#x} rdi {:#x} rsp {:#x}",
context.Rax, context.Rbx, context.Rcx, context.Rdx, context.Rsi, context.Rdi, context.Rsp
);
// shortcut: a stack scan, not an unwind; it lists stale return
// addresses too. Use RtlVirtualUnwind if this misleads.
let stack = context.Rsp as *const usize;
for i in 0..STACK_SCAN {
// SAFETY: slots just above the faulting RSP are committed stack.
let value = unsafe { stack.add(i).read_unaligned() };
if let Some(name) = module_of(value) {
eprintln!(" [rsp+{:#x}] {name}", i * 8);
}
}
EXCEPTION_CONTINUE_SEARCH
}
/// `module+rva`, or the bare address.
pub fn locate(address: usize) -> String {
module_of(address).unwrap_or_else(|| format!("{address:#x}"))
}
fn module_of(address: usize) -> Option<String> {
let mut module: HMODULE = std::ptr::null_mut();
// SAFETY: looks up the module containing `address`; no reference taken.
let found = unsafe {
GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
address as *const u16,
&mut module,
)
};
if found == 0 {
return None;
}
let mut path = [0u16; 260];
// SAFETY: `module` is a loaded module; the buffer length is passed.
let len = unsafe { GetModuleFileNameW(module, path.as_mut_ptr(), path.len() as u32) };
let path = String::from_utf16_lossy(&path[..len as usize]);
let name = path.rsplit('\\').next().unwrap_or(&path);
Some(format!("{name}+{:#x}", address - module as usize))
}
+15 -6
View File
@@ -11,25 +11,34 @@
//! 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.
//! 3. map the DLLs the title ships beside it the same way
//! (`load_title_dlls`);
//! 4. bind every import ourselves through an [`ImportResolver`], our
//! runtime (`victory-hle`), the host or the title's DLLs, and route
//! anything unresolved to a generated stub that reports exactly what
//! was called;
//! 5. initialise the title's DLLs, then run TLS callbacks and the entry
//! point on a thread with the stack size the image asks for.
#[cfg(windows)]
mod crash;
pub mod prepare;
pub mod resolve;
#[cfg(windows)]
mod thunks;
#[cfg(windows)]
mod tls;
#[cfg(windows)]
mod windows;
#[cfg(windows)]
pub use crash::{locate, report_crashes};
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};
pub use windows::{BindReport, LoadedImage, MissingImport, WithTitleDlls, load, load_title_dlls};
/// `DLL_PROCESS_ATTACH`, for TLS callbacks.
pub const DLL_PROCESS_ATTACH: u32 = 1;
+2
View File
@@ -10,6 +10,8 @@ pub enum Provenance {
/// The host's own implementation (e.g. Windows API sets that behave the
/// same on console and PC).
Host,
/// A DLL the title ships, mapped like the executable.
Title,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+218
View File
@@ -0,0 +1,218 @@
//! Static TLS of an executable mapped as a DLL.
//!
//! An exe always gets TLS index 0, so title code reaches its thread-local
//! block as `mov r64, gs:[0x58]` (the thread's TLS array) followed by
//! `[r64]`, without reading `_tls_index`. Mapped as a DLL, the image gets
//! another index. Every such load is turned into a call to a thunk that
//! yields `&array[index]` instead, and the image's `_tls_index` (which CRT
//! code does read, and adds to the array pointer) is set to 0.
use std::ffi::c_void;
use anyhow::{Result, bail};
use victory_pe::ImageInfo;
use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache;
use windows_sys::Win32::System::Memory::{
MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_READWRITE,
VirtualAlloc, VirtualProtect,
};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
const SCN_MEM_EXECUTE: u32 = 0x2000_0000;
const TLS64_ADDRESS_OF_INDEX: usize = 16;
/// `mov r64, gs:[0x58]` is `65 REX 8B ModRM 25 58 00 00 00`.
const LOAD_LEN: usize = 9;
const THUNK_SIZE: usize = 32;
/// Redirects the image's TLS-array loads if the OS gave it an index other
/// than 0. Returns the number of loads patched.
///
/// # Safety
/// `base` is the image `info` describes, mapped and not yet running.
pub(crate) unsafe fn redirect(base: usize, info: &ImageInfo) -> Result<usize> {
let Some(tls) = &info.tls else { return Ok(0) };
// SAFETY: the TLS directory and the index it points to are in the image;
// the OS relocated the pointer and wrote the index.
let index_at = unsafe {
((base + tls.directory_rva as usize + TLS64_ADDRESS_OF_INDEX) as *const usize).read()
} as *mut u32;
// SAFETY: as above.
let index = unsafe { index_at.read() };
if index == 0 {
return Ok(0);
}
let thunks = thunks(near(base, info.size_of_image as usize)?, index)?;
let mut patched = 0;
for section in info
.sections
.iter()
.filter(|s| s.characteristics & SCN_MEM_EXECUTE != 0)
{
let start = base + section.rva as usize;
let len = section.virtual_size as usize;
let mut old = 0;
// SAFETY: the section is part of the mapped image.
if unsafe { VirtualProtect(start as _, len, PAGE_EXECUTE_READWRITE, &mut old) } == 0 {
bail!(
"VirtualProtect(code) failed: {}",
std::io::Error::last_os_error()
);
}
// SAFETY: writable now, and no title code runs yet.
let code = unsafe { std::slice::from_raw_parts_mut(start as *mut u8, len) };
patched += patch(code, start, thunks);
// SAFETY: restoring the protection we changed; flushing our own code.
unsafe {
VirtualProtect(start as _, len, old, &mut old);
FlushInstructionCache(GetCurrentProcess(), start as _, len);
}
}
// SAFETY: see `index_at`; `.data` is writable.
unsafe { index_at.write(0) };
tracing::info!(index, patched, "static TLS redirected");
Ok(patched)
}
/// Rewrites each `mov r64, gs:[0x58]` in `code` (at address `at`) as
/// `call thunks[r]; nop4`. `thunks` must be within 2 GiB of `code`.
fn patch(code: &mut [u8], at: usize, thunks: usize) -> usize {
let mut count = 0;
let mut i = 0;
while i + LOAD_LEN <= code.len() {
let c = &code[i..i + LOAD_LEN];
let rex = c[1];
let reg = usize::from((c[3] >> 3) & 7) | if rex & 4 != 0 { 8 } else { 0 };
// shortcut: a byte match, not a decode; a false hit inside other
// bytes is unlikely at 9 specific bytes. Decode .text if one shows.
if c[0] == 0x65
&& (rex == 0x48 || rex == 0x4C)
&& c[2] == 0x8B
&& c[3] & 0xC7 == 0x04
&& c[4..] == [0x25, 0x58, 0, 0, 0]
&& reg != 4
{
let rel = (thunks + reg * THUNK_SIZE) as i64 - (at + i + 5) as i64;
code[i] = 0xE8;
code[i + 1..i + 5].copy_from_slice(&(rel as i32).to_le_bytes());
code[i + 5..i + 9].copy_from_slice(&[0x0F, 0x1F, 0x40, 0x00]);
count += 1;
i += LOAD_LEN;
} else {
i += 1;
}
}
count
}
/// Fills `block` with one thunk per register: `mov r, gs:[0x58];
/// lea r, [r + index * 8]; ret` (flags untouched, like the load it replaces).
fn thunks(block: *mut u8, index: u32) -> Result<usize> {
let disp = (index * 8).to_le_bytes();
for reg in 0..16u8 {
let (r, low) = (reg >> 3, reg & 7);
let mut code = vec![0x65, 0x48 | r << 2, 0x8B, low << 3 | 4, 0x25, 0x58, 0, 0, 0];
code.extend([0x48 | r << 2 | r, 0x8D, 0x80 | low << 3 | low]);
if low == 4 {
code.push(0x24); // SIB: [r12 + disp32]
}
code.extend(disp);
code.push(0xC3);
// SAFETY: `block` holds 16 thunks and is still writable.
unsafe {
std::ptr::copy_nonoverlapping(
code.as_ptr(),
block.add(usize::from(reg) * THUNK_SIZE),
code.len(),
)
};
}
let mut old = 0;
// SAFETY: `block` is our allocation of one page.
if unsafe { VirtualProtect(block as _, 4096, PAGE_EXECUTE_READ, &mut old) } == 0 {
bail!(
"VirtualProtect(TLS thunks) failed: {}",
std::io::Error::last_os_error()
);
}
Ok(block as usize)
}
/// One writable page within `rel32` reach of `[base, base + size)`. Leaked:
/// title code calls into it for the life of the process.
fn near(base: usize, size: usize) -> Result<*mut u8> {
const GRANULE: usize = 0x1_0000;
// The search spans 1 GiB each side, so every call site stays in reach.
if size >= 1 << 30 {
bail!("image too large for TLS thunks within rel32 reach");
}
let above = (base + size).next_multiple_of(GRANULE);
for k in 0..(1usize << 14) {
for hint in [
base.checked_sub((k + 1) * GRANULE),
Some(above + k * GRANULE),
] {
let Some(hint) = hint else { continue };
// SAFETY: a fresh allocation at a free address, or null.
let p = unsafe {
VirtualAlloc(
hint as *const c_void,
4096,
MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE,
)
};
if !p.is_null() {
return Ok(p.cast());
}
}
}
bail!("no free page near the image for TLS thunks")
}
#[cfg(test)]
mod tests {
use super::*;
/// Reads the thread's TLS array pointer the way title code does.
fn tls_array() -> usize {
let array: usize;
// SAFETY: reads TEB.ThreadLocalStoragePointer.
unsafe { std::arch::asm!("mov {}, gs:[0x58]", out(reg) array) };
array
}
#[test]
fn loads_become_calls_that_yield_the_title_slot() {
let page = near(tls_array as *const () as usize, 0).unwrap();
let thunks = thunks(near(page as usize, 4096).unwrap(), 3).unwrap();
// (before the load, REX, ModRM, after the load): each case returns
// the loaded register in rax; r12 is saved, being callee-saved.
let cases: [(&[u8], u8, u8, &[u8]); 3] = [
(&[], 0x48, 0x04, &[0xC3]), // rax
(&[], 0x4C, 0x04, &[0x4C, 0x89, 0xC0, 0xC3]), // r8
(
&[0x41, 0x54],
0x4C,
0x24,
&[0x4C, 0x89, 0xE0, 0x41, 0x5C, 0xC3],
), // r12
];
for (before, rex, modrm, after) in cases {
let mut code = before.to_vec();
code.extend([0x65, rex, 0x8B, modrm, 0x25, 0x58, 0, 0, 0]);
code.extend(after);
// SAFETY: the page is ours and writable.
let bytes = unsafe { std::slice::from_raw_parts_mut(page, code.len()) };
bytes.copy_from_slice(&code);
assert_eq!(patch(bytes, page as usize, thunks), 1);
let mut old = 0;
// SAFETY: our page, made executable to run the patched code.
unsafe { VirtualProtect(page as _, 4096, PAGE_EXECUTE_READ, &mut old) };
// SAFETY: the page holds the patched load and a return.
let f: extern "system" fn() -> usize = unsafe { std::mem::transmute(page) };
assert_eq!(f(), tls_array() + 3 * 8, "REX {rex:#x} ModRM {modrm:#x}");
// SAFETY: our page again.
unsafe { VirtualProtect(page as _, 4096, PAGE_READWRITE, &mut old) };
}
}
}
+118 -7
View File
@@ -1,8 +1,10 @@
//! Loading a prepared image as a real Windows module and binding it.
use std::collections::HashSet;
use std::ffi::{CString, c_void};
use std::os::windows::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use anyhow::{Context, Result, bail};
@@ -12,7 +14,7 @@ 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};
use crate::{DLL_PROCESS_ATTACH, ImportResolver, PreparedImage, Provenance, Resolution, prepare};
/// A title image mapped into this process.
#[derive(Debug)]
@@ -39,6 +41,7 @@ pub struct MissingImport {
pub struct BindReport {
pub hle: usize,
pub host: usize,
pub title: usize,
pub missing: Vec<MissingImport>,
}
@@ -72,6 +75,11 @@ pub fn load(prepared: &PreparedImage, dir: &Path) -> Result<LoadedImage> {
path,
info: prepared.info.clone(),
};
// A DLL indexes its TLS properly; only an exe assumes index 0.
if !loaded.info.is_dll() {
// SAFETY: just mapped, and no title code has run.
unsafe { crate::tls::redirect(loaded.base(), &loaded.info) }?;
}
tracing::info!(
base = format_args!("{:#x}", loaded.base()),
preferred = format_args!("{:#x}", loaded.info.image_base),
@@ -81,6 +89,67 @@ pub fn load(prepared: &PreparedImage, dir: &Path) -> Result<LoadedImage> {
Ok(loaded)
}
/// Maps the DLLs the title ships in `title_dir` that `main` imports,
/// directly or through each other, in initialisation order (dependencies
/// first). Only DLL names `wanted` accepts are considered, so DLLs the host
/// or our runtime provide stay with them. Imports are not bound.
pub fn load_title_dlls(
main: &ImageInfo,
title_dir: &Path,
cache_dir: &Path,
wanted: &dyn Fn(&str) -> bool,
) -> Result<Vec<(String, LoadedImage)>> {
fn visit(
info: &ImageInfo,
dirs: (&Path, &Path),
wanted: &dyn Fn(&str) -> bool,
seen: &mut HashSet<String>,
loaded: &mut Vec<(String, LoadedImage)>,
) -> Result<()> {
for module in info.imports.iter().chain(&info.delay_imports) {
let name = module.dll.to_ascii_lowercase();
let path = dirs.0.join(&name);
if !seen.insert(name.clone()) || !wanted(&name) || !path.is_file() {
continue;
}
let original =
std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?;
let image = load(&prepare(&original)?, dirs.1)
.with_context(|| format!("loading {}", path.display()))?;
visit(&image.info, dirs, wanted, seen, loaded)?;
loaded.push((name, image));
}
Ok(())
}
let mut loaded = Vec::new();
let dirs = (title_dir, cache_dir);
visit(main, dirs, wanted, &mut HashSet::new(), &mut loaded)?;
Ok(loaded)
}
/// Resolves through `inner`, then through the exports of the title's DLLs.
pub struct WithTitleDlls<'a> {
pub inner: &'a dyn ImportResolver,
pub dlls: &'a [(String, LoadedImage)],
}
impl ImportResolver for WithTitleDlls<'_> {
fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution {
let found = self.inner.resolve(dll, symbol);
if found != Resolution::Missing {
return found;
}
self.dlls
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case(dll))
.and_then(|(_, image)| image.export_symbol(symbol))
.map_or(Resolution::Missing, |address| Resolution::Found {
address,
provenance: Provenance::Title,
})
}
}
fn write_if_changed(path: &Path, bytes: &[u8]) -> Result<()> {
if std::fs::read(path).is_ok_and(|existing| existing == bytes) {
return Ok(());
@@ -109,6 +178,16 @@ impl LoadedImage {
.map(|f| f as *const () as usize)
}
/// Address of an export, by name or ordinal.
pub fn export_symbol(&self, symbol: &ImportSymbol) -> Option<usize> {
match symbol {
ImportSymbol::Name { name, .. } => self.export(name),
// SAFETY: MAKEINTRESOURCE-style ordinal lookup on a valid module.
ImportSymbol::Ordinal(o) => unsafe { GetProcAddress(self.module, *o as usize as _) }
.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
@@ -134,6 +213,7 @@ impl LoadedImage {
match provenance {
Provenance::Hle => report.hle += 1,
Provenance::Host => report.host += 1,
Provenance::Title => report.title += 1,
}
slots.push((entry.iat_slot_rva, address));
}
@@ -209,13 +289,40 @@ impl LoadedImage {
}
}
/// 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.
/// Initialises a DLL as the Windows loader would: its TLS callbacks,
/// then `DllMain(DLL_PROCESS_ATTACH)`.
///
/// # Safety
/// Runs title code. Imports must be bound first.
pub unsafe fn spawn_main(self: std::sync::Arc<Self>) -> Result<std::thread::JoinHandle<u32>> {
/// Runs title code. Imports must be bound first, and the DLLs this one
/// depends on attached.
pub unsafe fn attach(&self) -> Result<()> {
// SAFETY: forwarded from the caller.
unsafe { self.run_tls_callbacks(DLL_PROCESS_ATTACH) };
if self.info.entry_rva == 0 {
return Ok(());
}
type DllMain = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32;
// SAFETY: the entry RVA came from the original image header.
let main: DllMain =
unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) };
// SAFETY: forwarded from the caller.
if unsafe { main(self.module, DLL_PROCESS_ATTACH, std::ptr::null_mut()) } == 0 {
bail!("DllMain returned FALSE");
}
Ok(())
}
/// Starts the title: on a new thread with the stack size from the image
/// header, attaches `dlls` in order (see [`Self::attach`]), runs the
/// image's TLS callbacks (`DLL_PROCESS_ATTACH`), then its original entry
/// point. Returns the thread so the caller can join it.
///
/// # Safety
/// Runs title code. Imports of the image and of `dlls` must be bound.
pub unsafe fn spawn_main(
self: Arc<Self>,
dlls: Vec<(String, LoadedImage)>,
) -> Result<std::thread::JoinHandle<Result<u32>>> {
if self.info.entry_rva == 0 {
bail!("image has no entry point");
}
@@ -226,6 +333,10 @@ impl LoadedImage {
.name("title-main".into())
.stack_size(stack)
.spawn(move || {
for (name, dll) in &dlls {
// SAFETY: forwarded from the caller of `spawn_main`.
unsafe { dll.attach() }.with_context(|| format!("attaching {name}"))?;
}
// 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;
@@ -233,7 +344,7 @@ impl LoadedImage {
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()) }
Ok(unsafe { entry(std::ptr::null_mut()) })
})
.context("spawning title main thread")
}
+30 -2
View File
@@ -7,7 +7,8 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use victory_loader::{
ImportResolver, Provenance, Resolution, UnimplementedPolicy, prepare, unimplemented_call_count,
ImportResolver, Provenance, Resolution, UnimplementedPolicy, WithTitleDlls, prepare,
unimplemented_call_count,
};
use victory_pe::ImportSymbol;
use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA};
@@ -120,9 +121,33 @@ fn loads_binds_and_calls_probe() {
let dir = tempfile::tempdir().unwrap();
let image = victory_loader::load(&prepared, dir.path()).unwrap();
// The "title" ships victory-probe-title.dll: any real DLL will do.
let title_dir = tempfile::tempdir().unwrap();
std::fs::copy(
r"C:\Windows\System32\version.dll",
title_dir.path().join("victory-probe-title.dll"),
)
.unwrap();
let dlls =
victory_loader::load_title_dlls(image.info(), title_dir.path(), dir.path(), &|_| true)
.unwrap();
let names: Vec<_> = dlls.iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(names, ["victory-probe-title.dll"]);
let resolver = WithTitleDlls {
inner: &TestResolver,
dlls: &dlls,
};
for (_, dll) in &dlls {
dll.bind_imports(&resolver, UnimplementedPolicy::ReturnZero)
.unwrap();
// SAFETY: its imports are bound, and it depends on no other title DLL.
unsafe { dll.attach() }.unwrap();
}
let report = image
.bind_imports(&TestResolver, UnimplementedPolicy::ReturnZero)
.bind_imports(&resolver, UnimplementedPolicy::ReturnZero)
.unwrap();
assert_eq!(report.title, 1);
assert_eq!(report.hle, 3);
assert!(report.host > 0);
@@ -142,6 +167,9 @@ fn loads_binds_and_calls_probe() {
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_title"));
assert_ne!(f(), 0, "title DLL export must be bound");
let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_delayed"));
assert_eq!(f(), 4242, "delay-loaded API must be bound");