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:
commit
f4504f6413
69 files changed
+7952
No files matched your search
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "victory-hle"
|
||||
description = "Our implementation of the Xbox system API surface the title imports."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
victory-loader.workspace = true
|
||||
victory-pe.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { workspace = true, features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_System_LibraryLoader",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Pass-through to the host's own implementation of shared APIs.
|
||||
|
||||
use victory_pe::ImportSymbol;
|
||||
|
||||
/// Which DLLs may be satisfied by the host's own implementation.
|
||||
///
|
||||
/// Console titles link mostly against Windows API sets that behave the same
|
||||
/// on PC. Passing those through lets bring-up focus on what really differs.
|
||||
/// Anything whose semantics differ on console (memory, files, threads) is
|
||||
/// overridden in `modules`, which always wins over the host.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HostPolicy {
|
||||
/// Lower-case patterns; a trailing `*` matches a prefix.
|
||||
pub allow: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for HostPolicy {
|
||||
fn default() -> Self {
|
||||
let allow = [
|
||||
"api-ms-win-core-*",
|
||||
"api-ms-win-eventing-*",
|
||||
"api-ms-win-security-*",
|
||||
"api-ms-win-crt-*",
|
||||
"kernel32.dll",
|
||||
"kernelbase.dll",
|
||||
"ntdll.dll",
|
||||
"ucrtbase.dll",
|
||||
"vcruntime140*",
|
||||
"msvcp140*",
|
||||
"ws2_32.dll",
|
||||
"bcrypt.dll",
|
||||
"crypt32.dll",
|
||||
"ncrypt.dll",
|
||||
"winhttp.dll",
|
||||
"dnsapi.dll",
|
||||
"sspicli.dll",
|
||||
"cabinet.dll",
|
||||
"avrt.dll",
|
||||
];
|
||||
HostPolicy {
|
||||
allow: allow.iter().map(|s| s.to_string()).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HostPolicy {
|
||||
/// No pass-through at all: shows the full surface a title needs.
|
||||
pub fn none() -> Self {
|
||||
HostPolicy { allow: Vec::new() }
|
||||
}
|
||||
|
||||
pub fn allows(&self, dll: &str) -> bool {
|
||||
let dll = dll.to_ascii_lowercase();
|
||||
self.allow
|
||||
.iter()
|
||||
.any(|pattern| match pattern.strip_suffix('*') {
|
||||
Some(prefix) => dll.starts_with(prefix),
|
||||
None => dll == *pattern,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Option<usize> {
|
||||
if !self.allows(dll) {
|
||||
return None;
|
||||
}
|
||||
imp::resolve(dll, symbol)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::CString;
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
|
||||
use victory_pe::ImportSymbol;
|
||||
use windows_sys::Win32::System::LibraryLoader::{
|
||||
GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExA,
|
||||
};
|
||||
|
||||
/// Module handles by lower-case DLL name (stored as usize: Send + Sync).
|
||||
static MODULES: LazyLock<Mutex<HashMap<String, usize>>> = LazyLock::new(Default::default);
|
||||
|
||||
pub(super) fn resolve(dll: &str, symbol: &ImportSymbol) -> Option<usize> {
|
||||
let module = module(dll)?;
|
||||
let proc = match symbol {
|
||||
ImportSymbol::Name { name, .. } => {
|
||||
let name = CString::new(name.as_str()).ok()?;
|
||||
// SAFETY: valid module handle, NUL-terminated name.
|
||||
unsafe { GetProcAddress(module as _, name.as_ptr().cast()) }
|
||||
}
|
||||
// SAFETY: MAKEINTRESOURCE-style ordinal lookup on a valid module.
|
||||
ImportSymbol::Ordinal(o) => unsafe { GetProcAddress(module as _, *o as usize as _) },
|
||||
};
|
||||
proc.map(|f| f as *const () as usize)
|
||||
}
|
||||
|
||||
fn module(dll: &str) -> Option<usize> {
|
||||
let key = dll.to_ascii_lowercase();
|
||||
let mut cache = MODULES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(&m) = cache.get(&key) {
|
||||
return Some(m);
|
||||
}
|
||||
let name = CString::new(key.as_str()).ok()?;
|
||||
// System32 only: never pick up a same-named DLL from the current folder or PATH.
|
||||
// SAFETY: NUL-terminated DLL name; only allow-listed system DLLs get here.
|
||||
let handle = unsafe {
|
||||
LoadLibraryExA(
|
||||
name.as_ptr().cast(),
|
||||
std::ptr::null_mut(),
|
||||
LOAD_LIBRARY_SEARCH_SYSTEM32,
|
||||
)
|
||||
} as usize;
|
||||
(handle != 0).then(|| *cache.entry(key).or_insert(handle))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
mod imp {
|
||||
pub(super) fn resolve(_dll: &str, _symbol: &victory_pe::ImportSymbol) -> Option<usize> {
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
//! Our implementation of the Xbox system API surface.
|
||||
//!
|
||||
//! A title imports from three kinds of DLLs, and each gets its own policy:
|
||||
//!
|
||||
//! | kind | examples | handled by |
|
||||
//! |------|----------|------------|
|
||||
//! | Windows API sets the console shares with PC | `api-ms-win-core-synch-*`, `ws2_32.dll` | host pass-through, overridden here where console behaviour differs (paths, memory) |
|
||||
//! | console-only system APIs | `xgameruntime.dll`, `xmem.dll`, `d3d12_xs.dll` | implemented here, in [`modules`] |
|
||||
//! | anything else | | an unimplemented-import stub from the loader |
|
||||
//!
|
||||
//! Resolution order for every import: an implementation in [`modules`],
|
||||
//! then the host if [`HostPolicy`] allows that DLL, then `Missing`.
|
||||
|
||||
mod host;
|
||||
pub mod modules;
|
||||
mod registry;
|
||||
pub mod runtime;
|
||||
|
||||
pub use host::HostPolicy;
|
||||
pub use registry::{HleExport, HleModule, registry};
|
||||
|
||||
use victory_loader::{ImportResolver, Provenance, Resolution};
|
||||
use victory_pe::ImportSymbol;
|
||||
|
||||
/// Resolves a title's imports against our runtime and the host.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct HleResolver {
|
||||
pub host: HostPolicy,
|
||||
}
|
||||
|
||||
impl HleResolver {
|
||||
pub fn new(host: HostPolicy) -> Self {
|
||||
HleResolver { host }
|
||||
}
|
||||
|
||||
/// Where an import would come from, without binding anything.
|
||||
pub fn classify(&self, dll: &str, symbol: &ImportSymbol) -> Option<Provenance> {
|
||||
match self.resolve(dll, symbol) {
|
||||
Resolution::Found { provenance, .. } => Some(provenance),
|
||||
Resolution::Missing => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ImportResolver for HleResolver {
|
||||
fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution {
|
||||
if let ImportSymbol::Name { name, .. } = symbol
|
||||
&& let Some(address) = registry::lookup(dll, name)
|
||||
{
|
||||
return Resolution::Found {
|
||||
address,
|
||||
provenance: Provenance::Hle,
|
||||
};
|
||||
}
|
||||
match self.host.resolve(dll, symbol) {
|
||||
Some(address) => Resolution::Found {
|
||||
address,
|
||||
provenance: Provenance::Host,
|
||||
},
|
||||
None => Resolution::Missing,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The registry is code-only, so the "Missing" outcome can be checked on any
|
||||
// host; host pass-through itself needs Windows.
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn name(n: &str) -> ImportSymbol {
|
||||
ImportSymbol::Name {
|
||||
hint: 0,
|
||||
name: n.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn console_api_resolves_to_hle() {
|
||||
let r = HleResolver::new(HostPolicy::none());
|
||||
assert_eq!(
|
||||
r.classify("XGameRuntime.dll", &name("XGameRuntimeInitialize")),
|
||||
Some(Provenance::Hle)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_policy_reports_missing() {
|
||||
let r = HleResolver::new(HostPolicy::none());
|
||||
assert_eq!(
|
||||
r.classify("api-ms-win-core-synch-l1-1-0.dll", &name("Sleep")),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn shared_api_sets_pass_through_to_host() {
|
||||
let r = HleResolver::default();
|
||||
assert_eq!(
|
||||
r.classify("api-ms-win-core-synch-l1-2-0.dll", &name("Sleep")),
|
||||
Some(Provenance::Host)
|
||||
);
|
||||
// Console-only DLLs never pass through.
|
||||
assert_eq!(r.classify("xmem.dll", &name("XMemAllocDefault")), None);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn overrides_win_over_host() {
|
||||
let r = HleResolver::default();
|
||||
assert_eq!(
|
||||
r.classify(
|
||||
"api-ms-win-core-libraryloader-l1-2-0.dll",
|
||||
&name("GetModuleHandleW")
|
||||
),
|
||||
Some(Provenance::Hle)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//! Overrides of shared Windows APIs whose console meaning differs.
|
||||
//!
|
||||
//! Only the differences live here; everything else passes through to the
|
||||
//! host (see `HostPolicy`).
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
|
||||
use crate::{HleModule, hle_export, runtime};
|
||||
|
||||
/// `GetModuleHandleW(NULL)` must return the title's image, not our exe.
|
||||
pub extern "system" fn GetModuleHandleW(name: *const u16) -> *mut c_void {
|
||||
if name.is_null() {
|
||||
return runtime::main_image().unwrap_or(0) as *mut c_void;
|
||||
}
|
||||
host::get_module_handle_w(name)
|
||||
}
|
||||
|
||||
/// `GetModuleHandleA(NULL)` must return the title's image, not our exe.
|
||||
pub extern "system" fn GetModuleHandleA(name: *const u8) -> *mut c_void {
|
||||
if name.is_null() {
|
||||
return runtime::main_image().unwrap_or(0) as *mut c_void;
|
||||
}
|
||||
host::get_module_handle_a(name)
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "kernel",
|
||||
dlls: &[
|
||||
"kernel32.dll",
|
||||
"kernelbase.dll",
|
||||
"api-ms-win-core-libraryloader-*",
|
||||
],
|
||||
exports: vec![hle_export!(GetModuleHandleW), hle_export!(GetModuleHandleA)],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod host {
|
||||
use std::ffi::c_void;
|
||||
|
||||
pub(super) fn get_module_handle_w(name: *const u16) -> *mut c_void {
|
||||
// SAFETY: forwarding the title's own argument to the host API.
|
||||
unsafe { windows_sys::Win32::System::LibraryLoader::GetModuleHandleW(name) }
|
||||
}
|
||||
|
||||
pub(super) fn get_module_handle_a(name: *const u8) -> *mut c_void {
|
||||
// SAFETY: forwarding the title's own argument to the host API.
|
||||
unsafe { windows_sys::Win32::System::LibraryLoader::GetModuleHandleA(name) }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
mod host {
|
||||
use std::ffi::c_void;
|
||||
|
||||
pub(super) fn get_module_handle_w(_: *const u16) -> *mut c_void {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
|
||||
pub(super) fn get_module_handle_a(_: *const u8) -> *mut c_void {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//! Implementations, one module per area of the console API.
|
||||
//!
|
||||
//! Adding an API: write an `extern "system"` function named exactly like
|
||||
//! the import, then list it with `hle_export!` in the module's `module()`.
|
||||
//! Run `victory census` over your titles to see what is still missing.
|
||||
//!
|
||||
//! Planned areas (driven by census results, not by completeness):
|
||||
//! `xmem` (console memory types, GPU-visible allocations), `file` (package
|
||||
//! paths), `thread` (TLS callbacks for title threads), `d3d12x` (bridge to
|
||||
//! `victory-gpu`), `xaudio2`, `gameinput`, `xuser`/`xstore` stubs.
|
||||
|
||||
pub mod kernel;
|
||||
pub mod xgameruntime;
|
||||
|
||||
use crate::HleModule;
|
||||
|
||||
pub(crate) fn all() -> Vec<HleModule> {
|
||||
vec![kernel::module(), xgameruntime::module()]
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//! `xgameruntime.dll`: the console game runtime (XGame*, XUser*, XTaskQueue*...).
|
||||
//!
|
||||
//! The DLL names titles actually import these from are confirmed by running
|
||||
//! `victory census` on real titles; extend `dlls` accordingly.
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use crate::{HleModule, hle_export};
|
||||
|
||||
pub type HRESULT = i32;
|
||||
pub const S_OK: HRESULT = 0;
|
||||
|
||||
pub extern "system" fn XGameRuntimeInitialize() -> HRESULT {
|
||||
tracing::info!("XGameRuntimeInitialize");
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub extern "system" fn XGameRuntimeUninitialize() {
|
||||
tracing::info!("XGameRuntimeUninitialize");
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "xgameruntime",
|
||||
dlls: &["xgameruntime.dll"],
|
||||
exports: vec![
|
||||
hle_export!(XGameRuntimeInitialize),
|
||||
hle_export!(XGameRuntimeUninitialize),
|
||||
],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//! The table of everything we implement.
|
||||
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use crate::modules;
|
||||
|
||||
/// One function we implement, under the name the title imports.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct HleExport {
|
||||
pub name: &'static str,
|
||||
pub address: usize,
|
||||
}
|
||||
|
||||
/// A group of implementations and the DLL names they answer for.
|
||||
#[derive(Debug)]
|
||||
pub struct HleModule {
|
||||
/// Human-readable name, e.g. "kernel".
|
||||
pub name: &'static str,
|
||||
/// Lower-case DLL names served. A trailing `*` matches a prefix, which
|
||||
/// covers versioned API sets (`api-ms-win-core-libraryloader-l1-2-0.dll`).
|
||||
pub dlls: &'static [&'static str],
|
||||
pub exports: Vec<HleExport>,
|
||||
}
|
||||
|
||||
impl HleModule {
|
||||
pub fn serves(&self, dll: &str) -> bool {
|
||||
let dll = dll.to_ascii_lowercase();
|
||||
self.dlls
|
||||
.iter()
|
||||
.any(|pattern| match pattern.strip_suffix('*') {
|
||||
Some(prefix) => dll.starts_with(prefix),
|
||||
None => dll == *pattern,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Declares an export whose Rust name equals the imported name.
|
||||
#[macro_export]
|
||||
macro_rules! hle_export {
|
||||
($f:ident) => {
|
||||
$crate::HleExport {
|
||||
name: stringify!($f),
|
||||
address: $f as *const () as usize,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
static REGISTRY: LazyLock<Vec<HleModule>> = LazyLock::new(modules::all);
|
||||
|
||||
/// All modules we implement.
|
||||
pub fn registry() -> &'static [HleModule] {
|
||||
®ISTRY
|
||||
}
|
||||
|
||||
pub(crate) fn lookup(dll: &str, name: &str) -> Option<usize> {
|
||||
registry()
|
||||
.iter()
|
||||
.filter(|m| m.serves(dll))
|
||||
.flat_map(|m| m.exports.iter())
|
||||
.find(|e| e.name == name)
|
||||
.map(|e| e.address)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn export_names_are_unique_per_dll_pattern() {
|
||||
for module in registry() {
|
||||
let mut names: Vec<_> = module.exports.iter().map(|e| e.name).collect();
|
||||
names.sort_unstable();
|
||||
let before = names.len();
|
||||
names.dedup();
|
||||
assert_eq!(
|
||||
before,
|
||||
names.len(),
|
||||
"duplicate export in module {}",
|
||||
module.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_set_prefix_matching() {
|
||||
let m = HleModule {
|
||||
name: "t",
|
||||
dlls: &["api-ms-win-core-libraryloader-*"],
|
||||
exports: vec![],
|
||||
};
|
||||
assert!(m.serves("API-MS-WIN-CORE-LIBRARYLOADER-L1-2-0.dll"));
|
||||
assert!(!m.serves("api-ms-win-core-file-l1-1-0.dll"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//! Process-wide state the implementations need.
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
static MAIN_IMAGE_BASE: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// Records where the title's main image is mapped. The title expects
|
||||
/// `GetModuleHandle(NULL)` and friends to return this, not our own exe.
|
||||
pub fn set_main_image(base: usize) {
|
||||
MAIN_IMAGE_BASE.store(base, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn main_image() -> Option<usize> {
|
||||
match MAIN_IMAGE_BASE.load(Ordering::Acquire) {
|
||||
0 => None,
|
||||
base => Some(base),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//! Host pass-through must only load DLLs from System32, never from the
|
||||
//! current folder (e.g. a title's folder shipping its own `msvcp140_*.dll`).
|
||||
#![cfg(windows)]
|
||||
|
||||
use victory_hle::{HleResolver, HostPolicy};
|
||||
use victory_pe::ImportSymbol;
|
||||
|
||||
#[test]
|
||||
fn ignores_dlls_in_current_folder() {
|
||||
let name = "msvcp140_victorytest.dll";
|
||||
assert!(
|
||||
HostPolicy::default().allows(name),
|
||||
"test needs an allow-listed name"
|
||||
);
|
||||
assert!(HostPolicy::default().allows("vcruntime140_1.dll"));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
// Any loadable DLL will do.
|
||||
std::fs::copy(r"C:\Windows\System32\version.dll", dir.path().join(name)).unwrap();
|
||||
std::env::set_current_dir(dir.path()).unwrap();
|
||||
|
||||
let symbol = ImportSymbol::Name {
|
||||
hint: 0,
|
||||
name: "GetFileVersionInfoSizeW".into(),
|
||||
};
|
||||
let found = HleResolver::default().classify(name, &symbol);
|
||||
std::env::set_current_dir(env!("CARGO_MANIFEST_DIR")).unwrap();
|
||||
assert_eq!(found, None, "DLL was loaded from the current folder");
|
||||
}
|
||||
Reference in new issue
Block a user