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

+21
View File
@@ -0,0 +1,21 @@
[package]
name = "victory-core"
description = "Shared plumbing: configuration, paths, the asset-policy guard, logging."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
anyhow.workspace = true
thiserror.workspace = true
serde.workspace = true
toml.workspace = true
tracing-subscriber.workspace = true
[dev-dependencies]
tempfile.workspace = true
[lints]
workspace = true
+166
View File
@@ -0,0 +1,166 @@
//! Where the user's files live.
//!
//! Resolution order for each value: environment variable, then the config
//! file (`VICTORY_CONFIG`, else `./victory.toml`), then the default.
//! See `victory.example.toml` at the repository root.
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use serde::Deserialize;
use crate::policy::ensure_outside_repo;
#[derive(Debug, Default, Clone)]
pub struct Config {
/// The user's dump of Grand Theft Auto VI.
pub game_dir: Option<PathBuf>,
/// Root for all derived data. Always outside the repository.
pub cache_dir: PathBuf,
/// Other titles used to exercise platform-level code.
pub test_titles: Vec<PathBuf>,
/// The config file that was read, if any.
pub source: Option<PathBuf>,
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct FileConfig {
#[serde(default)]
paths: FilePaths,
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct FilePaths {
game_dir: Option<PathBuf>,
cache_dir: Option<PathBuf>,
#[serde(default)]
test_titles: Vec<PathBuf>,
}
impl Config {
/// Loads configuration from the environment and the config file.
pub fn load() -> Result<Self> {
let explicit = std::env::var_os("VICTORY_CONFIG").map(PathBuf::from);
let path = explicit
.clone()
.unwrap_or_else(|| PathBuf::from("victory.toml"));
let file = if path.is_file() {
let text = std::fs::read_to_string(&path)
.with_context(|| format!("reading {}", path.display()))?;
Some((path, text))
} else if let Some(p) = explicit {
anyhow::bail!(
"VICTORY_CONFIG points at {}, which does not exist",
p.display()
);
} else {
None
};
let (source, parsed) = match file {
Some((path, text)) => {
let parsed: FileConfig =
toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?;
(Some(path), parsed)
}
None => (None, FileConfig::default()),
};
Self::resolve(parsed.paths, source, |k| std::env::var_os(k))
}
fn resolve(
file: FilePaths,
source: Option<PathBuf>,
env: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> Result<Self> {
let env_path = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from);
let test_titles = match env("VICTORY_TEST_TITLES") {
Some(v) => std::env::split_paths(&v)
.filter(|p| !p.as_os_str().is_empty())
.collect(),
None => file.test_titles,
};
let cache_dir = env_path("VICTORY_CACHE_DIR")
.or(file.cache_dir)
.map_or_else(default_cache_dir, Ok)?;
Ok(Config {
game_dir: env_path("VICTORY_GAME_DIR").or(file.game_dir),
cache_dir,
test_titles,
source,
})
}
/// The game directory, or a helpful error if it is not configured.
pub fn require_game_dir(&self) -> Result<&Path> {
self.game_dir.as_deref().context(
"no game directory configured: set VICTORY_GAME_DIR or [paths].game_dir in \
victory.toml (see victory.example.toml)",
)
}
/// Returns `<cache>/<sub>`, creating it, after checking the asset policy.
pub fn cache_subdir(&self, sub: &str) -> Result<PathBuf> {
let dir = self.cache_dir.join(sub);
ensure_outside_repo(&dir)?;
std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
Ok(dir)
}
}
fn default_cache_dir() -> Result<PathBuf> {
let base = std::env::var_os("LOCALAPPDATA")
.or_else(|| std::env::var_os("XDG_CACHE_HOME"))
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))
.context("cannot determine a cache directory; set VICTORY_CACHE_DIR")?;
Ok(base.join("victory").join("cache"))
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::OsString;
#[test]
fn environment_overrides_file() {
let file = FilePaths {
game_dir: Some("from-file".into()),
cache_dir: Some("cache-from-file".into()),
..Default::default()
};
let env = |k: &str| (k == "VICTORY_GAME_DIR").then(|| OsString::from("from-env"));
let cfg = Config::resolve(file, None, env).unwrap();
assert_eq!(cfg.game_dir.unwrap(), PathBuf::from("from-env"));
assert_eq!(cfg.cache_dir, PathBuf::from("cache-from-file"));
}
#[test]
fn empty_env_values_are_ignored() {
let file = FilePaths {
game_dir: Some("from-file".into()),
..Default::default()
};
let env = |k: &str| (k == "VICTORY_GAME_DIR").then(OsString::new);
let cfg = Config::resolve(file, None, env).unwrap();
assert_eq!(cfg.game_dir.unwrap(), PathBuf::from("from-file"));
}
#[test]
fn example_config_parses() {
let text = include_str!("../../../victory.example.toml");
let parsed: FileConfig = toml::from_str(text).unwrap();
assert!(parsed.paths.game_dir.is_some());
}
#[test]
fn cache_inside_repo_is_refused() {
let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("cache");
let cfg = Config {
cache_dir: inside,
..Default::default()
};
assert!(cfg.cache_subdir("x").is_err());
}
}
+13
View File
@@ -0,0 +1,13 @@
//! Shared plumbing for every VIctory crate and tool.
//!
//! * [`config`]: where the user's files live (never inside the repository).
//! * [`policy`]: the runtime half of rule #1, refusing to write
//! game-derived data into the source tree.
//! * [`logging`]: one tracing setup for all binaries.
pub mod config;
pub mod logging;
pub mod policy;
pub use config::Config;
pub use policy::{PolicyError, ensure_outside_repo};
+19
View File
@@ -0,0 +1,19 @@
//! One tracing setup for every binary.
//!
//! Filter with `VICTORY_LOG` (falls back to `RUST_LOG`), e.g.
//! `VICTORY_LOG=victory_loader=trace,info`.
use tracing_subscriber::EnvFilter;
pub fn init(default_level: &str) {
let filter = std::env::var("VICTORY_LOG")
.or_else(|_| std::env::var("RUST_LOG"))
.ok()
.and_then(|v| EnvFilter::try_new(v).ok())
.unwrap_or_else(|| EnvFilter::new(default_level));
let _ = tracing_subscriber::fmt()
.with_env_filter(filter)
.with_target(true)
.with_writer(std::io::stderr)
.try_init();
}
+159
View File
@@ -0,0 +1,159 @@
//! Rule #1, enforced at runtime: game-derived data never lands in the repo.
//!
//! Everything VIctory produces from the user's files (converted assets,
//! prepared images, shader caches, crash dumps) is as much "from the game"
//! as the files themselves. Every tool that writes such output must call
//! [`ensure_outside_repo`] on the destination first. The static half of the
//! rule is `cargo xtask policy`, which checks what git tracks.
use std::path::{Component, Path, PathBuf};
/// Marker file at the root of the source tree.
pub const ROOT_MARKER: &str = ".victory-root";
/// The source tree this binary was compiled from.
fn compiled_workspace_root() -> PathBuf {
// crates/victory-core -> workspace root
Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..")
}
#[derive(Debug, thiserror::Error)]
pub enum PolicyError {
#[error(
"refusing to use {path} for game-derived data: it is inside the VIctory source tree \
({root}). Keep game files, caches and outputs outside the repository \
(see docs/asset-policy.md)"
)]
InsideRepo { path: PathBuf, root: PathBuf },
#[error("cannot resolve {path}: {source}")]
Io {
path: PathBuf,
source: std::io::Error,
},
}
/// Returns `Ok` only if `path` is outside every VIctory source tree.
///
/// `path` does not have to exist yet. Two checks are made:
/// 1. it is not below the source tree this binary was built from;
/// 2. none of its ancestors contains the [`ROOT_MARKER`] file (catches
/// other clones/copies of the repository).
pub fn ensure_outside_repo(path: &Path) -> Result<(), PolicyError> {
let resolved = resolve(path)?;
if let Ok(root) = std::fs::canonicalize(compiled_workspace_root())
&& root.join(ROOT_MARKER).is_file()
&& resolved.starts_with(&root)
{
return Err(PolicyError::InsideRepo {
path: path.to_path_buf(),
root,
});
}
for ancestor in resolved.ancestors() {
if ancestor.join(ROOT_MARKER).is_file() {
return Err(PolicyError::InsideRepo {
path: path.to_path_buf(),
root: ancestor.to_path_buf(),
});
}
}
Ok(())
}
/// Canonicalizes the longest existing prefix of `path` and re-appends the
/// rest, so that paths which do not exist yet can still be compared.
fn resolve(path: &Path) -> Result<PathBuf, PolicyError> {
let absolute = if path.is_absolute() {
path.to_path_buf()
} else {
std::env::current_dir()
.map_err(|source| PolicyError::Io {
path: path.to_path_buf(),
source,
})?
.join(path)
};
let mut existing = absolute.as_path();
let mut rest = Vec::new();
loop {
match std::fs::canonicalize(existing) {
Ok(canon) => {
let mut out = canon;
for component in rest.iter().rev() {
out.push(component);
}
return Ok(normalize(&out));
}
Err(source) => match (existing.parent(), existing.file_name()) {
(Some(parent), Some(name)) => {
rest.push(name.to_os_string());
existing = parent;
}
_ => {
return Err(PolicyError::Io {
path: path.to_path_buf(),
source,
});
}
},
}
}
}
/// Removes `.` and resolves `..` lexically (only used on the non-existing tail).
fn normalize(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
c => out.push(c),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_paths_inside_this_repo() {
let inside = compiled_workspace_root().join("cache").join("textures");
assert!(matches!(
ensure_outside_repo(&inside),
Err(PolicyError::InsideRepo { .. })
));
let sneaky = std::env::temp_dir().join("..").join("x"); // sanity: no panic
let _ = ensure_outside_repo(&sneaky);
}
#[test]
fn rejects_dotdot_escapes_back_into_repo() {
let root = compiled_workspace_root();
let path = root
.join("crates")
.join("..")
.join("not-yet-created")
.join("out");
assert!(ensure_outside_repo(&path).is_err());
}
#[test]
fn rejects_other_clones_via_marker() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join(ROOT_MARKER), "").unwrap();
assert!(ensure_outside_repo(&tmp.path().join("cache")).is_err());
}
#[test]
fn accepts_unrelated_directories() {
let tmp = tempfile::tempdir().unwrap();
ensure_outside_repo(&tmp.path().join("does").join("not").join("exist")).unwrap();
}
}
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "victory-formats"
description = "Platform-level data formats: texture layouts, compressed textures, audio codecs."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
[lints]
workspace = true
+6
View File
@@ -0,0 +1,6 @@
//! Platform-level data formats, shared by every Xbox Series title.
//!
//! Planned modules, each pure (bytes in, bytes out, no I/O): texture
//! layouts (RDNA2 swizzle modes to linear), BCPack textures, audio codecs
//! (XMA2, Opus), and the zlib streams used by hardware decompression.
//! Which come first depends on what Grand Theft Auto VI's assets contain.
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "victory-game"
description = "Everything specific to Grand Theft Auto VI: its containers, build identities, patches."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
[lints]
workspace = true
+23
View File
@@ -0,0 +1,23 @@
//! Everything specific to Grand Theft Auto VI: its container formats, build
//! identities, and the hooks we place in its code (located by per-build
//! offsets or byte-pattern signatures). What may and may not be stored here
//! is defined in docs/asset-policy.md.
/// A specific build of the Grand Theft Auto VI executable we know how to run.
#[derive(Debug, Clone, Copy)]
pub struct KnownBuild {
/// Our own label, e.g. "1.0.0 retail".
pub label: &'static str,
/// BLAKE3 of the original executable, hex.
pub blake3: &'static str,
}
/// Builds we support. Empty until the executable is available.
pub const KNOWN_BUILDS: &[KnownBuild] = &[];
/// Looks up a build by the BLAKE3 hash of its executable.
pub fn identify(blake3_hex: &str) -> Option<&'static KnownBuild> {
KNOWN_BUILDS
.iter()
.find(|b| b.blake3.eq_ignore_ascii_case(blake3_hex))
}
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "victory-gpu"
description = "D3D12.X command streams and GPU memory, translated onto host D3D12."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
[lints]
workspace = true
+12
View File
@@ -0,0 +1,12 @@
//! D3D12.X on host D3D12.
//!
//! D3D12.X records many commands by writing command-processor packets into
//! command lists from code inlined into the title itself, so no import-level
//! hook sees them. This crate decodes those packet streams at
//! `ExecuteCommandLists` time and replays them on host D3D12, and maps the
//! title's GPU virtual addresses (console memory is unified) to host
//! resources.
//!
//! Planned modules: `packets` (stream decoder), `memory` (title GPU
//! addresses to host heaps), `pipeline` (PSOs from `victory-shader` output),
//! `present` (swap chain, frame pacing).
+25
View File
@@ -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
+123
View File
@@ -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
}
}
+120
View File
@@ -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)
);
}
}
+65
View File
@@ -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()
}
}
+19
View File
@@ -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),
],
}
}
+94
View File
@@ -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] {
&REGISTRY
}
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"));
}
}
+18
View File
@@ -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");
}
+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();
}
}
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "victory-pe"
description = "Read-only analysis of PE32+ images and COFF import libraries."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
object.workspace = true
thiserror.workspace = true
[lints]
workspace = true
+472
View File
@@ -0,0 +1,472 @@
use object::LittleEndian as LE;
use object::Object;
use object::pe::{self, ImageNtHeaders64};
use object::read::pe::{
ExportTarget, ImageNtHeaders, ImageOptionalHeader, Import, ImportTable, ImportThunkList,
PeFile64,
};
use crate::layout::{self, dir};
use crate::{MACHINE_AMD64, PeError};
/// Everything we need to know about a PE32+ image, extracted in one pass.
#[derive(Debug, Clone)]
pub struct ImageInfo {
pub machine: u16,
/// `IMAGE_FILE_HEADER::Characteristics`.
pub characteristics: u16,
pub timestamp: u32,
pub subsystem: u16,
/// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics`.
pub dll_characteristics: u16,
pub image_base: u64,
pub size_of_image: u32,
pub entry_rva: u32,
pub stack_reserve: u64,
pub stack_commit: u64,
pub sections: Vec<SectionInfo>,
pub imports: Vec<ImportModule>,
pub delay_imports: Vec<ImportModule>,
pub exports: Vec<ExportInfo>,
pub tls: Option<TlsInfo>,
pub has_relocations: bool,
pub has_exception_table: bool,
pub has_load_config: bool,
pub codeview: Option<CodeViewInfo>,
}
#[derive(Debug, Clone)]
pub struct SectionInfo {
pub name: String,
pub rva: u32,
pub virtual_size: u32,
pub file_offset: u32,
pub file_size: u32,
pub characteristics: u32,
}
/// One imported DLL and the functions taken from it.
#[derive(Debug, Clone)]
pub struct ImportModule {
/// DLL name exactly as written in the image (case preserved).
pub dll: String,
pub entries: Vec<ImportEntry>,
}
#[derive(Debug, Clone)]
pub struct ImportEntry {
pub symbol: ImportSymbol,
/// RVA of the 8-byte IAT slot the loader must fill in.
pub iat_slot_rva: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum ImportSymbol {
Name { hint: u16, name: String },
Ordinal(u16),
}
impl std::fmt::Display for ImportSymbol {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ImportSymbol::Name { name, .. } => f.write_str(name),
ImportSymbol::Ordinal(o) => write!(f, "#{o}"),
}
}
}
#[derive(Debug, Clone)]
pub struct ExportInfo {
pub name: Option<String>,
pub ordinal: u16,
/// `None` for forwarded exports.
pub rva: Option<u32>,
/// `"dll.name"` or `"dll.#ordinal"` for forwarded exports.
pub forward: Option<String>,
}
#[derive(Debug, Clone)]
pub struct TlsInfo {
/// RVA of `IMAGE_TLS_DIRECTORY64`.
pub directory_rva: u32,
/// VA (at the preferred base) of the callback array, 0 if none.
pub callbacks_va: u64,
/// Callback RVAs, in call order.
pub callback_rvas: Vec<u32>,
}
/// CodeView (RSDS) record: identifies the exact build that produced an image.
#[derive(Debug, Clone)]
pub struct CodeViewInfo {
pub pdb_path: String,
pub guid: [u8; 16],
pub age: u32,
}
impl CodeViewInfo {
/// The key symbol servers use: GUID (Windows byte order) + age.
pub fn symbol_key(&self) -> String {
let g = &self.guid;
let d1 = u32::from_le_bytes([g[0], g[1], g[2], g[3]]);
let d2 = u16::from_le_bytes([g[4], g[5]]);
let d3 = u16::from_le_bytes([g[6], g[7]]);
let mut s = format!("{d1:08X}{d2:04X}{d3:04X}");
for b in &g[8..] {
s.push_str(&format!("{b:02X}"));
}
s.push_str(&format!("{:X}", self.age));
s
}
}
/// Upper bound on TLS callbacks we are willing to walk (defends against garbage).
const MAX_TLS_CALLBACKS: usize = 1024;
impl ImageInfo {
/// Parses a complete PE32+ x86-64 image from its file bytes.
pub fn parse(data: &[u8]) -> Result<Self, PeError> {
let kind = object::FileKind::parse(data)?;
if kind != object::FileKind::Pe64 {
return Err(PeError::Unsupported(format!(
"expected PE32+, found {kind:?}"
)));
}
let file = PeFile64::parse(data)?;
let nt = file.nt_headers();
let fh = nt.file_header();
let opt = nt.optional_header();
let machine = fh.machine.get(LE).0;
if machine != MACHINE_AMD64 {
return Err(PeError::Unsupported(format!(
"machine 0x{machine:04x} is not AMD64"
)));
}
let sections = file
.section_table()
.iter()
.map(|s| SectionInfo {
name: String::from_utf8_lossy(s.raw_name()).into_owned(),
rva: s.virtual_address.get(LE),
virtual_size: s.virtual_size.get(LE),
file_offset: s.pointer_to_raw_data.get(LE),
file_size: s.size_of_raw_data.get(LE),
characteristics: s.characteristics.get(LE).0,
})
.collect();
let dir_present = |index: usize| {
file.data_directory(index)
.is_some_and(|d| d.virtual_address.get(LE) != 0 && d.size.get(LE) != 0)
};
let imports = match file.import_table()? {
Some(table) => parse_imports(&table, opt.size_of_image())?,
None => Vec::new(),
};
let delay_imports = parse_delay_imports(&file, opt.size_of_image())?;
let exports = parse_exports(&file)?;
let tls = parse_tls(&file, data, opt.image_base())?;
let codeview = file.pdb_info()?.map(|cv| CodeViewInfo {
pdb_path: String::from_utf8_lossy(cv.path()).into_owned(),
guid: cv.guid(),
age: cv.age(),
});
Ok(ImageInfo {
machine,
characteristics: fh.characteristics.get(LE).0,
timestamp: fh.time_date_stamp.get(LE),
subsystem: opt.subsystem().0,
dll_characteristics: opt.dll_characteristics().0,
image_base: opt.image_base(),
size_of_image: opt.size_of_image(),
entry_rva: opt.address_of_entry_point(),
stack_reserve: opt.size_of_stack_reserve(),
stack_commit: opt.size_of_stack_commit(),
sections,
imports,
delay_imports,
exports,
tls,
has_relocations: dir_present(dir::BASERELOC)
&& !has_flag(
fh.characteristics.get(LE).0,
layout::file_flags::RELOCS_STRIPPED,
),
has_exception_table: dir_present(dir::EXCEPTION),
has_load_config: dir_present(dir::LOAD_CONFIG),
codeview,
})
}
pub fn is_dll(&self) -> bool {
has_flag(self.characteristics, layout::file_flags::DLL)
}
/// Maps an RVA to an offset in the file, if it is backed by file data.
pub fn rva_to_file_offset(&self, rva: u32) -> Option<u32> {
self.sections.iter().find_map(|s| {
let delta = rva.checked_sub(s.rva)?;
// Raw data may be padded past the virtual size; that padding is
// not part of the section in memory.
let backed = match s.virtual_size {
0 => s.file_size,
vs => vs.min(s.file_size),
};
(delta < backed).then(|| s.file_offset + delta)
})
}
pub fn import_count(&self) -> usize {
self.imports.iter().map(|m| m.entries.len()).sum()
}
pub fn subsystem_name(&self) -> &'static str {
use layout::subsystem::*;
match self.subsystem {
WINDOWS_GUI => "windows-gui",
WINDOWS_CUI => "windows-cui",
XBOX => "xbox",
XBOX_CODE_CATALOG => "xbox-code-catalog",
_ => "other",
}
}
}
fn has_flag(value: u16, flag: u16) -> bool {
value & flag != 0
}
fn utf8(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).into_owned()
}
fn convert_import(import: Import<'_>) -> ImportSymbol {
match import {
Import::Ordinal(o) => ImportSymbol::Ordinal(o),
Import::Name(hint, name) => ImportSymbol::Name {
hint,
name: utf8(name),
},
}
}
fn parse_imports(
table: &ImportTable<'_>,
size_of_image: u32,
) -> Result<Vec<ImportModule>, PeError> {
let mut modules = Vec::new();
let mut descriptors = table.descriptors()?;
while let Some(desc) = descriptors.next()? {
let iat_rva = desc.first_thunk.get(LE);
// Prefer the unbound name table; fall back to the IAT for old linkers.
let int_rva = match desc.original_first_thunk.get(LE) {
0 => iat_rva,
rva => rva,
};
modules.push(ImportModule {
dll: utf8(table.name(desc.name.get(LE))?),
entries: entries(table.thunks(int_rva)?, iat_rva, size_of_image, |t| {
table.import::<ImageNtHeaders64>(t)
})?,
});
}
Ok(modules)
}
fn parse_delay_imports(
file: &PeFile64<'_>,
size_of_image: u32,
) -> Result<Vec<ImportModule>, PeError> {
let Some(table) = file.delay_load_import_table()? else {
return Ok(Vec::new());
};
let mut modules = Vec::new();
let mut descriptors = table.descriptors()?;
while let Some(desc) = descriptors.next()? {
modules.push(ImportModule {
dll: utf8(table.name(desc.dll_name_rva.get(LE))?),
entries: entries(
table.thunks(desc.import_name_table_rva.get(LE))?,
desc.import_address_table_rva.get(LE),
size_of_image,
|t| table.import::<ImageNtHeaders64>(t),
)?,
});
}
Ok(modules)
}
/// Pairs each name-table entry with its IAT slot. The IAT RVA is not checked
/// by `object`, so every slot is checked to lie inside the image here.
fn entries<'data>(
mut thunks: ImportThunkList<'data>,
iat_rva: u32,
size_of_image: u32,
import: impl Fn(pe::ImageThunkData64) -> object::read::Result<Import<'data>>,
) -> Result<Vec<ImportEntry>, PeError> {
let mut entries = Vec::new();
while let Some(thunk) = thunks.next::<ImageNtHeaders64>()? {
let iat_slot_rva = u32::try_from(entries.len() * 8)
.ok()
.and_then(|offset| iat_rva.checked_add(offset))
.filter(|&rva| rva.checked_add(8).is_some_and(|end| end <= size_of_image))
.ok_or_else(|| {
PeError::Malformed(format!("IAT at {iat_rva:#x} runs outside the image"))
})?;
entries.push(ImportEntry {
symbol: convert_import(import(thunk)?),
iat_slot_rva,
});
}
Ok(entries)
}
fn parse_exports(file: &PeFile64<'_>) -> Result<Vec<ExportInfo>, PeError> {
let Some(table) = file.export_table()? else {
return Ok(Vec::new());
};
Ok(table
.exports()?
.into_iter()
.map(|e| {
let (rva, forward) = match e.target {
ExportTarget::Address(rva) => (Some(rva), None),
ExportTarget::ForwardByName(d, n) => {
(None, Some(format!("{}.{}", utf8(d), utf8(n))))
}
ExportTarget::ForwardByOrdinal(d, o) => {
(None, Some(format!("{}.#{}", utf8(d), o.0)))
}
};
ExportInfo {
name: e.name.map(utf8),
ordinal: e.ordinal.0,
rva,
forward,
}
})
.collect())
}
fn parse_tls(
file: &PeFile64<'_>,
data: &[u8],
image_base: u64,
) -> Result<Option<TlsInfo>, PeError> {
let Some(dd) = file.data_directory(pe::IMAGE_DIRECTORY_ENTRY_TLS) else {
return Ok(None);
};
let directory_rva = dd.virtual_address.get(LE);
if directory_rva == 0 {
return Ok(None);
}
let sections = file.section_table();
let tls = sections
.pe_data_at(data, directory_rva)
.ok_or_else(|| PeError::Malformed("TLS directory outside of sections".into()))?;
let callbacks_va = layout::read_u64(tls, layout::TLS64_ADDRESS_OF_CALLBACKS)
.ok_or_else(|| PeError::Malformed("truncated TLS directory".into()))?;
let mut callback_rvas = Vec::new();
if callbacks_va != 0 {
let array_rva = va_to_rva(callbacks_va, image_base)?;
let array = sections
.pe_data_at(data, array_rva)
.ok_or_else(|| PeError::Malformed("TLS callback array outside of sections".into()))?;
for slot in array.as_chunks::<8>().0.iter().take(MAX_TLS_CALLBACKS) {
let va = u64::from_le_bytes(*slot);
if va == 0 {
break;
}
callback_rvas.push(va_to_rva(va, image_base)?);
}
}
Ok(Some(TlsInfo {
directory_rva,
callbacks_va,
callback_rvas,
}))
}
fn va_to_rva(va: u64, image_base: u64) -> Result<u32, PeError> {
va.checked_sub(image_base)
.and_then(|rva| u32::try_from(rva).ok())
.ok_or_else(|| PeError::Malformed(format!("VA 0x{va:x} is outside the image")))
}
#[cfg(test)]
mod tests {
use super::*;
/// The test binary itself is a real MSVC-linked PE32+ image.
fn own_image() -> Vec<u8> {
std::fs::read(std::env::current_exe().unwrap()).unwrap()
}
#[test]
fn parses_own_test_binary() {
let info = ImageInfo::parse(&own_image()).unwrap();
assert_eq!(info.machine, MACHINE_AMD64);
assert!(!info.is_dll());
assert!(info.entry_rva != 0);
assert!(info.has_exception_table, "x64 images always carry .pdata");
assert!(info.sections.iter().any(|s| s.name.starts_with(".text")));
let kernel32 = info
.imports
.iter()
.find(|m| m.dll.eq_ignore_ascii_case("kernel32.dll"))
.expect("Rust std imports kernel32");
assert!(kernel32.entries.iter().all(|e| e.iat_slot_rva != 0));
// Rust std uses static TLS, so a TLS directory must be present (its
// callback array may legitimately be empty).
assert!(info.tls.is_some());
}
#[test]
fn rva_to_file_offset_maps_entry_point() {
let data = own_image();
let info = ImageInfo::parse(&data).unwrap();
let off = info.rva_to_file_offset(info.entry_rva).unwrap() as usize;
assert!(off < data.len());
}
#[test]
fn rejects_garbage_without_panicking() {
assert!(ImageInfo::parse(b"").is_err());
assert!(ImageInfo::parse(b"MZ not really").is_err());
let mut truncated = own_image();
truncated.truncate(0x200);
assert!(ImageInfo::parse(&truncated).is_err());
}
#[test]
fn rejects_iat_outside_image() {
let mut data = own_image();
let dd = layout::data_directory_offset(&data, dir::IMPORT).unwrap();
let import_rva = layout::read_u32(&data, dd).unwrap();
let desc = ImageInfo::parse(&data)
.unwrap()
.rva_to_file_offset(import_rva)
.unwrap() as usize;
// First descriptor's FirstThunk, at the 4 GiB limit: used to overflow.
data[desc + 16..desc + 20].copy_from_slice(&0xFFFF_FFF8u32.to_le_bytes());
assert!(matches!(
ImageInfo::parse(&data),
Err(PeError::Malformed(_))
));
}
}
#[cfg(test)]
mod dbg_tls {
#[test]
fn dump_tls() {
let data = std::fs::read(std::env::current_exe().unwrap()).unwrap();
let info = super::ImageInfo::parse(&data).unwrap();
eprintln!("TLS = {:?}", info.tls);
eprintln!("image_base = {:x}", info.image_base);
}
}
+66
View File
@@ -0,0 +1,66 @@
//! COFF import libraries (`.lib`).
//!
//! An umbrella import library tells us which DLL provides each API that a
//! console title may link against. That is the map the runtime needs to
//! decide which of our implementations answers which import.
use object::read::archive::ArchiveFile;
use object::read::coff::{ImportFile, ImportName, ImportType};
use crate::{ImportSymbol, PeError};
/// One `dll!export` pair described by an import library.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct LibImport {
pub dll: String,
pub export: ImportSymbol,
pub kind: LibImportKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum LibImportKind {
Code,
Data,
Const,
}
/// Result of reading an import library.
#[derive(Debug, Default)]
pub struct ImportLibrary {
pub imports: Vec<LibImport>,
/// Members that are not short-format import objects (regular objects,
/// long-format import descriptors). Reported so nothing is silently lost.
pub other_members: usize,
}
impl ImportLibrary {
pub fn parse(data: &[u8]) -> Result<Self, PeError> {
let archive = ArchiveFile::parse(data)?;
let mut lib = ImportLibrary::default();
for member in archive.members() {
let member = member?;
let bytes = member.data(data)?;
match ImportFile::parse(bytes) {
Ok(import) => lib.imports.push(LibImport {
dll: String::from_utf8_lossy(import.dll()).into_owned(),
export: match import.import() {
ImportName::Name(name) => ImportSymbol::Name {
hint: 0,
name: String::from_utf8_lossy(name).into_owned(),
},
ImportName::Ordinal(o) => ImportSymbol::Ordinal(o),
},
kind: match import.import_type() {
ImportType::Code => LibImportKind::Code,
ImportType::Data => LibImportKind::Data,
ImportType::Const => LibImportKind::Const,
},
}),
Err(_) => lib.other_members += 1,
}
}
lib.imports.sort();
lib.imports.dedup();
Ok(lib)
}
}
+91
View File
@@ -0,0 +1,91 @@
//! Raw byte offsets of PE32+ header fields, for code that patches images.
//!
//! All offsets are relative to the start of the structure named in the
//! constant's prefix. They follow the published PE/COFF specification.
/// Offset of `e_lfanew` (u32) in the DOS header.
pub const DOS_E_LFANEW: usize = 0x3C;
/// Size of the `PE\0\0` signature that precedes the file header.
pub const NT_SIGNATURE_SIZE: usize = 4;
/// Size of `IMAGE_FILE_HEADER`.
pub const FILE_HEADER_SIZE: usize = 20;
/// `IMAGE_FILE_HEADER::Characteristics` (u16).
pub const FILE_HEADER_CHARACTERISTICS: usize = 18;
/// `IMAGE_OPTIONAL_HEADER64::AddressOfEntryPoint` (u32).
pub const OPT_ADDRESS_OF_ENTRY_POINT: usize = 16;
/// `IMAGE_OPTIONAL_HEADER64::CheckSum` (u32).
pub const OPT_CHECKSUM: usize = 64;
/// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics` (u16).
pub const OPT_DLL_CHARACTERISTICS: usize = 70;
/// `IMAGE_OPTIONAL_HEADER64::NumberOfRvaAndSizes` (u32).
pub const OPT_NUMBER_OF_RVA_AND_SIZES: usize = 108;
/// First `IMAGE_DATA_DIRECTORY` entry (each is `{ rva: u32, size: u32 }`).
pub const OPT_DATA_DIRECTORY: usize = 112;
/// Size of one `IMAGE_DATA_DIRECTORY`.
pub const DATA_DIRECTORY_SIZE: usize = 8;
/// `IMAGE_TLS_DIRECTORY64::AddressOfCallBacks` (u64 VA).
pub const TLS64_ADDRESS_OF_CALLBACKS: usize = 24;
/// Data directory indices.
pub mod dir {
pub const IMPORT: usize = 1;
pub const EXCEPTION: usize = 3;
pub const BASERELOC: usize = 5;
pub const LOAD_CONFIG: usize = 10;
pub const BOUND_IMPORT: usize = 11;
}
/// `IMAGE_FILE_HEADER::Characteristics` flags.
pub mod file_flags {
pub const RELOCS_STRIPPED: u16 = 0x0001;
pub const DLL: u16 = 0x2000;
}
/// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics` flags.
pub mod dll_flags {
pub const HIGH_ENTROPY_VA: u16 = 0x0020;
pub const DYNAMIC_BASE: u16 = 0x0040;
pub const FORCE_INTEGRITY: u16 = 0x0080;
pub const NX_COMPAT: u16 = 0x0100;
pub const APPCONTAINER: u16 = 0x1000;
pub const GUARD_CF: u16 = 0x4000;
}
/// `IMAGE_OPTIONAL_HEADER64::Subsystem` values.
pub mod subsystem {
pub const WINDOWS_GUI: u16 = 2;
pub const WINDOWS_CUI: u16 = 3;
pub const XBOX: u16 = 14;
pub const XBOX_CODE_CATALOG: u16 = 17;
}
/// Offset of the optional header from the start of the file.
pub fn optional_header_offset(data: &[u8]) -> Option<usize> {
let lfanew = read_u32(data, DOS_E_LFANEW)? as usize;
Some(lfanew + NT_SIGNATURE_SIZE + FILE_HEADER_SIZE)
}
/// Offset of the file header from the start of the file.
pub fn file_header_offset(data: &[u8]) -> Option<usize> {
let lfanew = read_u32(data, DOS_E_LFANEW)? as usize;
Some(lfanew + NT_SIGNATURE_SIZE)
}
/// Offset of data directory `index` from the start of the file.
pub fn data_directory_offset(data: &[u8], index: usize) -> Option<usize> {
let opt = optional_header_offset(data)?;
let count = read_u32(data, opt + OPT_NUMBER_OF_RVA_AND_SIZES)? as usize;
(index < count).then_some(opt + OPT_DATA_DIRECTORY + index * DATA_DIRECTORY_SIZE)
}
pub fn read_u32(data: &[u8], at: usize) -> Option<u32> {
Some(u32::from_le_bytes(data.get(at..at + 4)?.try_into().ok()?))
}
pub fn read_u64(data: &[u8], at: usize) -> Option<u64> {
Some(u64::from_le_bytes(data.get(at..at + 8)?.try_into().ok()?))
}
+35
View File
@@ -0,0 +1,35 @@
//! Read-only analysis of PE32+ (x86-64) images and COFF import libraries.
//!
//! Xbox Series X|S titles are ordinary x86-64 PE32+ images (the console CPU
//! is a Zen 2), so the same parser serves titles, console system DLLs and
//! host binaries alike. This crate never modifies anything; patching lives in
//! `victory-loader`, which uses the raw offsets exported from [`layout`].
mod image;
pub mod implib;
pub mod layout;
pub use image::{
CodeViewInfo, ExportInfo, ImageInfo, ImportEntry, ImportModule, ImportSymbol, SectionInfo,
TlsInfo,
};
/// Errors produced while parsing an image or import library.
#[derive(Debug, thiserror::Error)]
pub enum PeError {
/// The file is a valid PE but not one we handle (e.g. 32-bit or ARM64).
#[error("unsupported image: {0}")]
Unsupported(String),
/// The file is truncated or internally inconsistent.
#[error("malformed image: {0}")]
Malformed(String),
}
impl From<object::read::Error> for PeError {
fn from(e: object::read::Error) -> Self {
PeError::Malformed(e.to_string())
}
}
/// `IMAGE_FILE_MACHINE_AMD64`.
pub const MACHINE_AMD64: u16 = 0x8664;
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "victory-pipeline"
description = "Offline conversion of user-supplied game data into host formats, with a content-addressed cache."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
victory-core.workspace = true
anyhow.workspace = true
blake3.workspace = true
tracing.workspace = true
[dev-dependencies]
tempfile.workspace = true
[lints]
workspace = true
+130
View File
@@ -0,0 +1,130 @@
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use crate::Converter;
/// Identifies one conversion result.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CacheKey(blake3::Hash);
impl CacheKey {
pub fn new(converter: &dyn Converter, input: &[u8]) -> Self {
let mut h = blake3::Hasher::new();
h.update(converter.id().as_bytes());
h.update(&[0]);
h.update(&converter.version().to_le_bytes());
h.update(input);
CacheKey(h.finalize())
}
pub fn to_hex(&self) -> String {
self.0.to_hex().to_string()
}
}
/// Content-addressed store under the user's cache directory.
#[derive(Debug, Clone)]
pub struct Cache {
root: PathBuf,
}
impl Cache {
/// Opens (creating) a cache at `root`. Refuses locations inside the repo.
pub fn open(root: impl Into<PathBuf>) -> Result<Self> {
let root = root.into();
victory_core::ensure_outside_repo(&root)?;
std::fs::create_dir_all(&root).with_context(|| format!("creating {}", root.display()))?;
Ok(Cache { root })
}
pub fn path_for(&self, key: &CacheKey) -> PathBuf {
let hex = key.to_hex();
self.root.join(&hex[..2]).join(&hex[2..])
}
/// Returns the cached output for `input`, converting it first if needed.
pub fn get_or_convert(&self, converter: &dyn Converter, input: &[u8]) -> Result<PathBuf> {
let key = CacheKey::new(converter, input);
let path = self.path_for(&key);
if path.is_file() {
tracing::trace!(converter = converter.id(), key = %key.to_hex(), "cache hit");
return Ok(path);
}
let output = converter
.convert(input)
.with_context(|| format!("converter {} v{}", converter.id(), converter.version()))?;
let dir = path.parent().expect("hashed path has a parent");
std::fs::create_dir_all(dir)?;
// Write-then-rename so readers never see partial output.
let tmp = tempfile_in(dir);
std::fs::write(&tmp, &output)?;
std::fs::rename(&tmp, &path)?;
Ok(path)
}
}
fn tempfile_in(dir: &Path) -> PathBuf {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
dir.join(format!(".tmp-{}-{n}", std::process::id()))
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
struct Upper {
version: u32,
runs: AtomicUsize,
}
impl Converter for Upper {
fn id(&self) -> &'static str {
"test.upper"
}
fn version(&self) -> u32 {
self.version
}
fn convert(&self, input: &[u8]) -> Result<Vec<u8>> {
self.runs.fetch_add(1, Ordering::Relaxed);
Ok(input.to_ascii_uppercase())
}
}
#[test]
fn converts_once_then_hits() {
let tmp = tempfile::tempdir().unwrap();
let cache = Cache::open(tmp.path().join("cache")).unwrap();
let conv = Upper {
version: 1,
runs: AtomicUsize::new(0),
};
let a = cache.get_or_convert(&conv, b"abc").unwrap();
let b = cache.get_or_convert(&conv, b"abc").unwrap();
assert_eq!(a, b);
assert_eq!(std::fs::read(&a).unwrap(), b"ABC");
assert_eq!(conv.runs.load(Ordering::Relaxed), 1);
}
#[test]
fn version_bump_invalidates() {
let v1 = Upper {
version: 1,
runs: AtomicUsize::new(0),
};
let v2 = Upper {
version: 2,
runs: AtomicUsize::new(0),
};
assert_ne!(CacheKey::new(&v1, b"x"), CacheKey::new(&v2, b"x"));
}
#[test]
fn refuses_cache_inside_repo() {
let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("cache");
assert!(Cache::open(inside).is_err());
}
}
+23
View File
@@ -0,0 +1,23 @@
//! Offline conversion of the user's game data into host formats.
//!
//! Everything here runs on the user's machine, reads the user's files and
//! writes into the user's cache. Nothing produced here is ever committed:
//! derived data is still game data (docs/asset-policy.md).
//!
//! The unit of work is a [`Converter`]: bytes in, bytes out, deterministic.
//! Results are stored in a content-addressed [`Cache`] keyed by converter
//! id, converter version and input bytes, so re-running the pipeline after
//! a game update or a converter fix only redoes what changed.
mod cache;
pub use cache::{Cache, CacheKey};
/// A deterministic transformation of one input into one output.
pub trait Converter: Send + Sync {
/// Stable identifier, e.g. `"texture.detile"`. Part of the cache key.
fn id(&self) -> &'static str;
/// Bump whenever the output for a given input changes.
fn version(&self) -> u32;
fn convert(&self, input: &[u8]) -> anyhow::Result<Vec<u8>>;
}
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "victory-shader"
description = "Xbox shader containers (DXBC/DXIL + precompiled GFX10) to host shaders."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
thiserror.workspace = true
miniz_oxide.workspace = true
[lints]
workspace = true
+179
View File
@@ -0,0 +1,179 @@
//! The DXBC container: a header, then a table of FourCC-tagged parts.
//!
//! ```text
//! 0x00 "DXBC"
//! 0x04 digest[16]
//! 0x14 version major u16, minor u16
//! 0x18 total size u32
//! 0x1C part count u32
//! 0x20 part offsets u32[count]
//! part: fourcc[4], size u32, data[size]
//! ```
use crate::ShaderError;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct FourCC(pub [u8; 4]);
impl FourCC {
pub const DXIL: FourCC = FourCC(*b"DXIL");
pub const STAT: FourCC = FourCC(*b"STAT");
pub const RTS0: FourCC = FourCC(*b"RTS0");
pub const PSV0: FourCC = FourCC(*b"PSV0");
pub const ISG1: FourCC = FourCC(*b"ISG1");
pub const OSG1: FourCC = FourCC(*b"OSG1");
pub const SFI0: FourCC = FourCC(*b"SFI0");
pub const HASH: FourCC = FourCC(*b"HASH");
pub const ILDB: FourCC = FourCC(*b"ILDB");
pub const ILDN: FourCC = FourCC(*b"ILDN");
}
impl std::fmt::Debug for FourCC {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self)
}
}
impl std::fmt::Display for FourCC {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for &b in &self.0 {
let c = if b.is_ascii_graphic() { b as char } else { '.' };
write!(f, "{c}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
pub struct Part<'a> {
pub fourcc: FourCC,
/// Offset of the part header within the container.
pub offset: usize,
pub data: &'a [u8],
}
#[derive(Debug, Clone)]
pub struct Container<'a> {
pub digest: [u8; 16],
pub version: (u16, u16),
pub parts: Vec<Part<'a>>,
}
const HEADER_SIZE: usize = 0x20;
const MAX_PARTS: usize = 256;
impl<'a> Container<'a> {
pub fn parse(data: &'a [u8]) -> Result<Self, ShaderError> {
if data.len() < HEADER_SIZE || &data[0..4] != b"DXBC" {
return Err(ShaderError::NotDxbc);
}
let digest = data[4..20].try_into().expect("16 bytes");
let version = (u16_at(data, 0x14)?, u16_at(data, 0x16)?);
let total = u32_at(data, 0x18)? as usize;
if total > data.len() || total < HEADER_SIZE {
return Err(ShaderError::Malformed("container size disagrees with data"));
}
let data = &data[..total];
let count = u32_at(data, 0x1C)? as usize;
if count > MAX_PARTS {
return Err(ShaderError::Malformed("implausible part count"));
}
let mut parts = Vec::with_capacity(count);
for i in 0..count {
let offset = u32_at(data, HEADER_SIZE + 4 * i)? as usize;
let fourcc = FourCC(
data.get(offset..offset + 4)
.ok_or(ShaderError::Malformed("part header out of bounds"))?
.try_into()
.expect("4 bytes"),
);
let size = u32_at(data, offset + 4)? as usize;
let body = data
.get(offset + 8..offset + 8 + size)
.ok_or(ShaderError::Malformed("part data out of bounds"))?;
parts.push(Part {
fourcc,
offset,
data: body,
});
}
Ok(Container {
digest,
version,
parts,
})
}
pub fn part(&self, fourcc: FourCC) -> Option<&Part<'a>> {
self.parts.iter().find(|p| p.fourcc == fourcc)
}
}
pub(crate) fn u16_at(data: &[u8], at: usize) -> Result<u16, ShaderError> {
data.get(at..at + 2)
.map(|b| u16::from_le_bytes(b.try_into().expect("2 bytes")))
.ok_or(ShaderError::Malformed("truncated"))
}
pub(crate) fn u32_at(data: &[u8], at: usize) -> Result<u32, ShaderError> {
data.get(at..at + 4)
.map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")))
.ok_or(ShaderError::Malformed("truncated"))
}
pub(crate) fn u64_at(data: &[u8], at: usize) -> Result<u64, ShaderError> {
data.get(at..at + 8)
.map(|b| u64::from_le_bytes(b.try_into().expect("8 bytes")))
.ok_or(ShaderError::Malformed("truncated"))
}
/// Builds a container from parts (test helper).
#[cfg(test)]
pub fn build(parts: &[(FourCC, &[u8])]) -> Vec<u8> {
let table = HEADER_SIZE + 4 * parts.len();
let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>();
let mut out = Vec::with_capacity(total);
out.extend_from_slice(b"DXBC");
out.extend_from_slice(&[0; 16]);
out.extend_from_slice(&1u16.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(&(total as u32).to_le_bytes());
out.extend_from_slice(&(parts.len() as u32).to_le_bytes());
let mut offset = table;
for (_, d) in parts {
out.extend_from_slice(&(offset as u32).to_le_bytes());
offset += 8 + d.len();
}
for (fourcc, d) in parts {
out.extend_from_slice(&fourcc.0);
out.extend_from_slice(&(d.len() as u32).to_le_bytes());
out.extend_from_slice(d);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_parts() {
let bytes = build(&[(FourCC::SFI0, &[1, 2, 3, 4]), (FourCC::HASH, &[9; 20])]);
let c = Container::parse(&bytes).unwrap();
assert_eq!(c.parts.len(), 2);
assert_eq!(c.part(FourCC::SFI0).unwrap().data, &[1, 2, 3, 4]);
assert_eq!(c.part(FourCC::HASH).unwrap().data.len(), 20);
assert!(c.part(FourCC::DXIL).is_none());
}
#[test]
fn rejects_bad_input() {
assert_eq!(Container::parse(b"nope").unwrap_err(), ShaderError::NotDxbc);
let mut bytes = build(&[(FourCC::SFI0, &[0; 8])]);
let last = bytes.len() - 1;
bytes[0x20] = 0xFF; // corrupt the first part offset
assert!(Container::parse(&bytes).is_err());
bytes.truncate(last);
assert!(Container::parse(&bytes).is_err());
}
}
+211
View File
@@ -0,0 +1,211 @@
//! The DXIL program inside a container's `DXIL` (or `STAT`) part.
//!
//! ```text
//! 0x00 program version u32 (kind << 16 | major << 4 | minor)
//! 0x04 size in dwords u32
//! 0x08 "DXIL" <- bitcode offset is relative to here
//! 0x0C dxil version u32
//! 0x10 bitcode offset u32 (16 in standard PC DXIL)
//! 0x14 bitcode size u32
//! ```
use crate::ShaderError;
use crate::dxbc::u32_at;
const LLVM_BITCODE_MAGIC: [u8; 4] = [0x42, 0x43, 0xC0, 0xDE];
#[cfg(test)]
const STANDARD_BITCODE_OFFSET: u32 = 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShaderKind {
Pixel,
Vertex,
Geometry,
Hull,
Domain,
Compute,
Library,
RayGeneration,
Intersection,
AnyHit,
ClosestHit,
Miss,
Callable,
Mesh,
Amplification,
Node,
Unknown(u16),
}
impl ShaderKind {
fn from_raw(v: u16) -> Self {
use ShaderKind::*;
match v {
0 => Pixel,
1 => Vertex,
2 => Geometry,
3 => Hull,
4 => Domain,
5 => Compute,
6 => Library,
7 => RayGeneration,
8 => Intersection,
9 => AnyHit,
10 => ClosestHit,
11 => Miss,
12 => Callable,
13 => Mesh,
14 => Amplification,
15 => Node,
other => Unknown(other),
}
}
}
#[derive(Debug, Clone)]
pub struct DxilProgram<'a> {
pub kind: ShaderKind,
pub shader_model: (u8, u8),
pub dxil_version: u32,
/// LLVM bitcode (starts with `BC C0 DE`).
pub bitcode: &'a [u8],
/// Bytes between the bitcode header and the bitcode. Empty on PC.
pub prefix: &'a [u8],
/// Bytes after the bitcode, up to the program size. Empty on PC.
pub trailer: &'a [u8],
}
/// Xbox additions recognised around the bitcode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct XboxExtras {
/// The prefix starts with an `XDAT` table.
pub xdat: bool,
/// The trailer contains an `xbop` blob (compiler options).
pub xbop: bool,
}
impl<'a> DxilProgram<'a> {
pub fn parse(part: &'a [u8]) -> Result<Self, ShaderError> {
let version = u32_at(part, 0)?;
let size = (u32_at(part, 4)? as usize)
.checked_mul(4)
.filter(|&s| s <= part.len() && s >= 24)
.ok_or(ShaderError::Malformed(
"program size disagrees with part size",
))?;
let part = &part[..size];
if part.get(8..12) != Some(b"DXIL") {
return Err(ShaderError::Malformed("missing DXIL magic"));
}
let dxil_version = u32_at(part, 12)?;
let offset = u32_at(part, 16)?;
let len = u32_at(part, 20)? as usize;
let start = 8 + offset as usize;
let bitcode = part
.get(start..start + len)
.ok_or(ShaderError::Malformed("bitcode out of bounds"))?;
if bitcode.get(0..4) != Some(&LLVM_BITCODE_MAGIC) {
return Err(ShaderError::Malformed("bitcode lacks LLVM magic"));
}
let prefix = part
.get(24..start)
.ok_or(ShaderError::Malformed("bitcode offset too small"))?;
Ok(DxilProgram {
kind: ShaderKind::from_raw((version >> 16) as u16),
shader_model: (((version >> 4) & 0xF) as u8, (version & 0xF) as u8),
dxil_version,
bitcode,
prefix,
trailer: &part[start + len..],
})
}
/// True for a program laid out exactly like PC DXIL.
pub fn is_standard_layout(&self) -> bool {
self.prefix.is_empty() && self.trailer.is_empty()
}
pub fn xbox_extras(&self) -> XboxExtras {
XboxExtras {
xdat: self.prefix.starts_with(b"XDAT"),
xbop: self.trailer.windows(4).any(|w| w == b"xbop"),
}
}
}
/// Builds a standard PC-layout program around `bitcode` (test helper).
#[cfg(test)]
pub fn build_standard(kind: u16, sm: (u8, u8), dxil_version: u32, bitcode: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let version = (u32::from(kind) << 16) | (u32::from(sm.0) << 4) | u32::from(sm.1);
let padded = bitcode.len().next_multiple_of(4);
let size_dwords = (24 + padded) / 4;
out.extend_from_slice(&version.to_le_bytes());
out.extend_from_slice(&(size_dwords as u32).to_le_bytes());
out.extend_from_slice(b"DXIL");
out.extend_from_slice(&dxil_version.to_le_bytes());
out.extend_from_slice(&STANDARD_BITCODE_OFFSET.to_le_bytes());
out.extend_from_slice(&(bitcode.len() as u32).to_le_bytes());
out.extend_from_slice(bitcode);
out.resize(24 + padded, 0);
out
}
#[cfg(test)]
mod tests {
use super::*;
fn fake_bitcode() -> Vec<u8> {
let mut b = LLVM_BITCODE_MAGIC.to_vec();
b.extend_from_slice(&[0xAA; 12]);
b
}
#[test]
fn parses_standard_layout() {
let bytes = build_standard(0, (6, 0), 0x100, &fake_bitcode());
let p = DxilProgram::parse(&bytes).unwrap();
assert_eq!(p.kind, ShaderKind::Pixel);
assert_eq!(p.shader_model, (6, 0));
assert!(p.is_standard_layout());
assert_eq!(p.xbox_extras(), XboxExtras::default());
}
#[test]
fn detects_xbox_layout() {
// Xbox layout: XDAT table before the bitcode, xbop blob after it.
let bitcode = fake_bitcode();
let xdat = b"XDAT\x01\x00\x00\x00";
let trailer = b"xbop\x02\x00\x00\x00";
let mut bytes = Vec::new();
let size = 24 + xdat.len() + bitcode.len() + trailer.len();
bytes.extend_from_slice(&((5u32 << 16) | 0x65).to_le_bytes()); // cs_6_5
bytes.extend_from_slice(&((size / 4) as u32).to_le_bytes());
bytes.extend_from_slice(b"DXIL");
bytes.extend_from_slice(&0x105u32.to_le_bytes());
bytes.extend_from_slice(&(16 + xdat.len() as u32).to_le_bytes());
bytes.extend_from_slice(&(bitcode.len() as u32).to_le_bytes());
bytes.extend_from_slice(xdat);
bytes.extend_from_slice(&bitcode);
bytes.extend_from_slice(trailer);
let p = DxilProgram::parse(&bytes).unwrap();
assert_eq!(p.kind, ShaderKind::Compute);
assert_eq!(p.shader_model, (6, 5));
assert!(!p.is_standard_layout());
assert_eq!(
p.xbox_extras(),
XboxExtras {
xdat: true,
xbop: true
}
);
assert_eq!(p.bitcode, &bitcode[..]);
}
#[test]
fn rejects_missing_bitcode_magic() {
let bytes = build_standard(0, (6, 0), 0x100, &[0u8; 16]);
assert!(DxilProgram::parse(&bytes).is_err());
}
}
+447
View File
@@ -0,0 +1,447 @@
//! GFX10 machine code: instruction boundaries, encodings and opcodes.
//!
//! Instructions are found by following control flow from offset 0, not by a
//! linear sweep: compilers place data (constant tables) in the code region
//! after the end of the program. Operand fields are not decoded yet; each
//! instruction keeps its raw dwords.
//!
//! Encodings by the top bits of the first dword:
//!
//! ```text
//! 0xxxxxxx VOP2; 0111111 VOP1; 0111110 VOPC
//! 10 SOP2; 1011 SOPK; 101111101 SOP1; 101111110 SOPC; 101111111 SOPP
//! 110010 VINTRP 110011 VOP3P 110101 VOP3 110110 DS 110111 FLAT/GLOBAL/SCRATCH
//! 111000 MUBUF 111010 MTBUF 111100 MIMG 111101 SMEM 111110 EXP
//! ```
mod opcodes;
use std::collections::BTreeMap;
use crate::ShaderError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Encoding {
Sop2,
Sopk,
Sop1,
Sopc,
Sopp,
Smem,
Vop2,
Vop1,
Vopc,
Vop3,
Vop3p,
Vintrp,
Ds,
Mubuf,
Mtbuf,
Mimg,
Exp,
Flat,
Global,
Scratch,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Instruction {
/// Byte offset in the program.
pub offset: usize,
pub encoding: Encoding,
pub opcode: u16,
/// Every dword of the instruction, including literals and extra dwords.
pub words: Vec<u32>,
}
impl Instruction {
/// AMD's name for the opcode, if it is in our table.
pub fn name(&self) -> Option<&'static str> {
name(self.encoding, self.opcode)
}
}
/// Decodes every instruction reachable from offset 0, sorted by offset.
pub fn decode(code: &[u8]) -> Result<Vec<Instruction>, ShaderError> {
if !code.len().is_multiple_of(4) {
return Err(isa(code.len(), "code size is not a multiple of 4"));
}
let mut found = BTreeMap::new();
let mut pending = vec![0usize];
while let Some(mut offset) = pending.pop() {
while !found.contains_key(&offset) {
let inst = instruction(code, offset)?;
let next = offset + 4 * inst.words.len();
let flow = match flow(&inst, next, code.len())? {
Flow::Stop if inst.name() == Some("s_setpc_b64") => {
far_jump(&found, &inst, code.len())?.map_or(Flow::Stop, Flow::Jump)
}
flow => flow,
};
found.insert(offset, inst);
match flow {
Flow::Next => offset = next,
Flow::Stop => break,
Flow::Jump(target) => offset = target,
Flow::Branch(target) => {
pending.push(target);
offset = next;
}
}
}
}
let list: Vec<Instruction> = found.into_values().collect();
if let Some(w) = list
.windows(2)
.find(|w| w[0].offset + 4 * w[0].words.len() > w[1].offset)
{
return Err(isa(w[1].offset, "a branch lands inside an instruction"));
}
Ok(list)
}
enum Flow {
Next,
Stop,
Jump(usize),
Branch(usize),
}
fn flow(inst: &Instruction, next: usize, len: usize) -> Result<Flow, ShaderError> {
let target = || {
let delta = 4 * i64::from(inst.words[0] as u16 as i16);
usize::try_from(next as i64 + delta)
.ok()
.filter(|&t| t < len)
.ok_or(isa(inst.offset, "branch target outside the code"))
};
Ok(match (inst.encoding, inst.name().unwrap_or("")) {
(
Encoding::Sopp,
"s_endpgm" | "s_endpgm_saved" | "s_endpgm_ordered_ps_done" | "s_code_end",
) => Flow::Stop,
(Encoding::Sopp, "s_branch") => Flow::Jump(target()?),
(Encoding::Sopp, name) if name.starts_with("s_cbranch_") => Flow::Branch(target()?),
(Encoding::Sopk, "s_call_b64") => Flow::Branch(target()?),
// Indirect jump; `decode` resolves the compiler's far-jump form.
(Encoding::Sop1, "s_setpc_b64") => Flow::Stop,
_ => Flow::Next,
})
}
/// Resolves the far jump compilers emit beyond the reach of a branch offset:
/// `s_getpc_b64 s[n:n+1]`, `s_add_u32|s_sub_u32 sn, sn, literal`, a carry
/// into s(n+1), `s_setpc_b64 s[n:n+1]`, looking back over the straight-line
/// run just decoded. Any other `s_setpc_b64` (e.g. a handover to the next
/// merged stage through registers) gives `None`.
fn far_jump(
found: &BTreeMap<usize, Instruction>,
setpc: &Instruction,
len: usize,
) -> Result<Option<usize>, ShaderError> {
let n = setpc.words[0] & 0xFF;
let mut delta = None;
let mut at = setpc.offset;
for _ in 0..4 {
let Some((_, prev)) = found.range(..at).next_back() else {
break;
};
if prev.offset + 4 * prev.words.len() != at {
break;
}
let w = prev.words[0];
let (sdst, ssrc0, ssrc1) = ((w >> 16) & 0x7F, w & 0xFF, (w >> 8) & 0xFF);
match (prev.encoding, prev.name()) {
(Encoding::Sop2, Some(op @ ("s_add_u32" | "s_sub_u32")))
if sdst == n && ssrc0 == n && ssrc1 == 0xFF && delta.is_none() =>
{
let literal = i64::from(prev.words[1]);
delta = Some(if op == "s_add_u32" { literal } else { -literal });
}
(Encoding::Sop1, Some("s_getpc_b64")) if sdst == n => {
let Some(delta) = delta else { break };
// s_getpc_b64 yields the address of the instruction after it.
return usize::try_from(prev.offset as i64 + 4 + delta)
.ok()
.filter(|&t| t < len)
.map(Some)
.ok_or(isa(setpc.offset, "far jump target outside the code"));
}
_ => {}
}
at = prev.offset;
}
Ok(None)
}
fn instruction(code: &[u8], offset: usize) -> Result<Instruction, ShaderError> {
let word = |i: usize| {
code.get(offset + 4 * i..offset + 4 * i + 4)
.map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")))
.ok_or(isa(offset, "instruction runs past the end of the code"))
};
let w = word(0)?;
let (encoding, opcode, len) = if w >> 31 == 0 {
let src0 = w & 0x1FF;
// Literal constant, SDWA, DPP16, DPP8, DPP8 with fetch-inactive.
let extra = usize::from(matches!(src0, 0xFF | 0xF9 | 0xFA | 0xE9 | 0xEA));
match w >> 25 {
0x3F => (Encoding::Vop1, (w >> 9) & 0xFF, 1 + extra),
0x3E => (Encoding::Vopc, (w >> 17) & 0xFF, 1 + extra),
op => {
let mk_ak = name(Encoding::Vop2, op as u16).is_some_and(|n| {
matches!(
n,
"v_madmk_f32"
| "v_madak_f32"
| "v_fmamk_f32"
| "v_fmaak_f32"
| "v_madmk_f16"
| "v_madak_f16"
| "v_fmamk_f16"
| "v_fmaak_f16"
)
});
(Encoding::Vop2, op, 1 + extra.max(usize::from(mk_ak)))
}
}
} else if w >> 30 == 0b10 {
let literal = |srcs: &[u32]| 1 + usize::from(srcs.contains(&0xFF));
match w >> 23 {
0x17D => (Encoding::Sop1, (w >> 8) & 0xFF, literal(&[w & 0xFF])),
0x17E => (
Encoding::Sopc,
(w >> 16) & 0x7F,
literal(&[w & 0xFF, (w >> 8) & 0xFF]),
),
0x17F => (Encoding::Sopp, (w >> 16) & 0x7F, 1),
_ if w >> 28 == 0b1011 => {
let op = (w >> 23) & 0x1F;
let imm32 = name(Encoding::Sopk, op as u16) == Some("s_setreg_imm32_b32");
(Encoding::Sopk, op, 1 + usize::from(imm32))
}
_ => (
Encoding::Sop2,
(w >> 23) & 0x7F,
literal(&[w & 0xFF, (w >> 8) & 0xFF]),
),
}
} else {
let vop3 =
|w1: u32| 2 + usize::from([w1, w1 >> 9, w1 >> 18].iter().any(|s| s & 0x1FF == 0xFF));
match w >> 26 {
0x32 => (Encoding::Vintrp, (w >> 16) & 0x3, 1),
0x33 => (Encoding::Vop3p, (w >> 16) & 0x7F, vop3(word(1)?)),
0x35 => (Encoding::Vop3, (w >> 16) & 0x3FF, vop3(word(1)?)),
0x36 => (Encoding::Ds, (w >> 18) & 0xFF, 2),
0x37 => {
let encoding = match (w >> 14) & 3 {
0 => Encoding::Flat,
1 => Encoding::Scratch,
2 => Encoding::Global,
_ => return Err(isa(offset, "reserved FLAT segment")),
};
(encoding, (w >> 18) & 0x7F, 2)
}
0x38 => (Encoding::Mubuf, (w >> 18) & 0x7F | (w >> 25 & 1) << 7, 2),
0x3A => (
Encoding::Mtbuf,
(w >> 16) & 0x7 | (word(1)? >> 21 & 1) << 3,
2,
),
// Bits 2:1 count extra dwords of non-sequential address registers.
0x3C => (
Encoding::Mimg,
(w >> 18) & 0x7F | (w & 1) << 7,
2 + (w as usize >> 1 & 3),
),
0x3D => (Encoding::Smem, (w >> 18) & 0xFF, 2),
0x3E => (Encoding::Exp, 0, 2),
_ => return Err(isa(offset, "unknown encoding")),
}
};
Ok(Instruction {
offset,
encoding,
opcode: opcode as u16,
words: (0..len).map(word).collect::<Result<_, _>>()?,
})
}
fn name(encoding: Encoding, opcode: u16) -> Option<&'static str> {
use opcodes as t;
let (table, op) = match encoding {
Encoding::Sop2 => (t::SOP2, opcode),
Encoding::Sopk => (t::SOPK, opcode),
Encoding::Sop1 => (t::SOP1, opcode),
Encoding::Sopc => (t::SOPC, opcode),
Encoding::Sopp => (t::SOPP, opcode),
Encoding::Smem => (t::SMEM, opcode),
Encoding::Vop2 => (t::VOP2, opcode),
Encoding::Vop1 => (t::VOP1, opcode),
Encoding::Vopc => (t::VOPC, opcode),
// VOP3 also encodes the VOPC, VOP2 and VOP1 opcodes at fixed bases.
Encoding::Vop3 => match opcode {
0x000..0x100 => (t::VOPC, opcode),
0x100..0x140 => (t::VOP2, opcode - 0x100),
0x180..0x200 => (t::VOP1, opcode - 0x180),
_ => (t::VOP3, opcode),
},
Encoding::Vop3p => (t::VOP3P, opcode),
Encoding::Vintrp => (t::VINTRP, opcode),
Encoding::Ds => (t::DS, opcode),
Encoding::Mubuf => (t::MUBUF, opcode),
Encoding::Mtbuf => (t::MTBUF, opcode),
Encoding::Mimg => (t::MIMG, opcode),
Encoding::Exp => return Some("exp"),
Encoding::Flat => (t::FLAT, opcode),
Encoding::Global => (t::GLOBAL, opcode),
Encoding::Scratch => (t::SCRATCH, opcode),
};
table
.binary_search_by_key(&op, |&(o, _)| o)
.ok()
.map(|i| table[i].1)
}
fn isa(offset: usize, reason: &'static str) -> ShaderError {
ShaderError::Isa { offset, reason }
}
#[cfg(test)]
mod tests {
use super::*;
const S_ENDPGM: u32 = 0xBF81_0000;
/// s_branch / s_cbranch_scc0 with a dword offset relative to the next instruction.
const fn sopp(op: u32, simm16: i16) -> u32 {
0xBF80_0000 | op << 16 | simm16 as u16 as u32
}
fn bytes(words: &[u32]) -> Vec<u8> {
words.iter().flat_map(|w| w.to_le_bytes()).collect()
}
fn summary(code: &[u32]) -> Vec<(usize, usize, &'static str)> {
decode(&bytes(code))
.unwrap()
.iter()
.map(|i| (i.offset, i.words.len(), i.name().unwrap_or("?")))
.collect()
}
#[test]
fn tables_are_sorted() {
for t in [
opcodes::SOP2,
opcodes::SOPK,
opcodes::SOP1,
opcodes::SOPC,
opcodes::SOPP,
opcodes::SMEM,
opcodes::VOP2,
opcodes::VOP1,
opcodes::VOPC,
opcodes::VOP3,
opcodes::VOP3P,
opcodes::VINTRP,
opcodes::DS,
opcodes::MUBUF,
opcodes::MTBUF,
opcodes::MIMG,
opcodes::FLAT,
opcodes::GLOBAL,
opcodes::SCRATCH,
] {
assert!(t.windows(2).all(|w| w[0].0 < w[1].0));
}
}
#[test]
fn lengths_and_names() {
let code = [
0xBE80_03FF,
0x3F80_0000, // s_mov_b32 s0, literal
0x0600_0000, // v_add_f32 v0, s0, v0
0xD54B_0000,
0x03FE_0000,
0x4000_0000, // v_fma_f32 with a literal src2
0xF080_0F0A,
0,
0, // image_sample (2D) with one extra address dword
0xF800_080F,
0, // exp
S_ENDPGM,
];
assert_eq!(
summary(&code),
[
(0, 2, "s_mov_b32"),
(8, 1, "v_add_f32"),
(12, 3, "v_fma_f32"),
(24, 3, "image_sample"),
(36, 2, "exp"),
(44, 1, "s_endpgm"),
]
);
}
#[test]
fn follows_branches_and_skips_data() {
let code = [
sopp(0x04, 1), // s_cbranch_scc0 -> 8
sopp(0x02, 1), // s_branch -> 12
S_ENDPGM,
S_ENDPGM,
S_ENDPGM, // data follows the program end
0xFFFF_FFFF,
];
let found: Vec<_> = summary(&code).iter().map(|i| i.0).collect();
assert_eq!(found, [0, 4, 8, 12]);
}
#[test]
fn follows_far_jumps() {
let code = [
0xBE88_1F00, // s_getpc_b64 s[8:9]
0x8008_FF08,
20, // s_add_u32 s8, s8, 20 -> 4 + 20 = 24
0x8209_8009, // s_addc_u32 s9, s9, 0
0xBE80_2008, // s_setpc_b64 s[8:9]
0xFFFF_FFFF, // not code
S_ENDPGM,
];
let found: Vec<_> = summary(&code).iter().map(|i| (i.0, i.2)).collect();
assert_eq!(
found,
[
(0, "s_getpc_b64"),
(4, "s_add_u32"),
(12, "s_addc_u32"),
(16, "s_setpc_b64"),
(24, "s_endpgm"),
]
);
// Through other registers (a handover to another stage): the path ends.
assert_eq!(summary(&[0xBE80_2018, S_ENDPGM]).len(), 1);
}
#[test]
fn rejects_bad_code() {
assert!(decode(&[0; 3]).is_err(), "size not a multiple of 4");
assert!(
decode(&bytes(&[sopp(0x02, 100)])).is_err(),
"branch out of range"
);
assert!(
decode(&bytes(&[0xBE80_03FF])).is_err(),
"literal past the end"
);
assert!(
decode(&bytes(&[0xE400_0000, 0])).is_err(),
"unknown encoding"
);
// s_cbranch_scc0 into the literal of the s_mov_b32 at 4.
assert!(decode(&bytes(&[sopp(0x04, 1), 0xBE80_03FF, S_ENDPGM, S_ENDPGM])).is_err());
}
}
File diff suppressed because it is too large. Load diff
+26
View File
@@ -0,0 +1,26 @@
//! Xbox Series shaders to host shaders.
//!
//! An Xbox Series shader is a standard DXBC container ([`dxbc`]). Its `DXIL`
//! part ([`dxil`]) may carry Xbox additions around the LLVM bitcode: an
//! `XDAT` table before it indexing blobs after it, among them `xbop`
//! (compiler options) and the zlib-compressed GFX10 code. The bitcode may use
//! console-only intrinsics, so the GFX10 code is translated in general.
pub mod dxbc;
pub mod dxil;
pub mod gfx10;
pub mod native;
pub use dxbc::{Container, FourCC, Part};
pub use dxil::{DxilProgram, ShaderKind, XboxExtras};
pub use native::{HwStage, NativeProgram, native_programs};
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ShaderError {
#[error("not a DXBC container")]
NotDxbc,
#[error("malformed shader: {0}")]
Malformed(&'static str),
#[error("GFX10 code at {offset:#x}: {reason}")]
Isa { offset: usize, reason: &'static str },
}
+288
View File
@@ -0,0 +1,288 @@
//! Native GFX10 programs that the console compiler stores in a `DXIL` part.
//!
//! An `XDAT` index after the program header lists blobs stored around the
//! bitcode; one or more of them hold native programs, zlib-packed (a vertex
//! shader can carry two: compiled for use with and without a geometry
//! shader). Layout as observed in shipped titles (index offsets are relative
//! to the part data):
//!
//! ```text
//! +0x18 "XDAT" u32 entry count, u32 (0x24 seen), then per entry:
//! u32 kind, u32 offset, u32 size
//! kind 0x0d "XBCH" u32 version (3), u64 packed size, u64 unpacked size,
//! zlib stream
//! unpacked "FSSM" u32 version (0x101), u64 payload size, payload
//! payload +0x00 u64 graphics slot count (6)
//! +0x08 u64 record offsets: LS HS ES GS VS PS (0x08..0x30),
//! mesh 0x48, compute 0x60; unused ones are 0xDEADBEEF_DEADBEEF
//! record +0x00 u64 code offset, +0x08 u64 code size (payload-relative)
//! ```
//!
//! Other kinds seen: 0x07 program header + bitcode (or a stub when stripped),
//! 0x0a `xbop` (compiler options), 0x0e a table not decoded yet, 0x10 and
//! 0x12 16-byte blobs (0x10 is the shader hash).
//! Unknown versions are rejected so a format change shows up as an error.
use crate::ShaderError::{self, Malformed};
use crate::dxbc::{u32_at, u64_at};
const XDAT_OFFSET: usize = 0x18;
const MAX_XDAT_ENTRIES: usize = 64;
const KIND_NATIVE: u32 = 0x0d;
const XBCH_VERSION: u32 = 3;
const XBCH_HEADER: usize = 0x18;
const FSSM_VERSION: u32 = 0x101;
const FSSM_HEADER: usize = 0x10;
const GRAPHICS_SLOT_COUNT: u64 = 6;
/// Where each stage's record offset sits in the FSSM payload.
const SLOTS: [(HwStage, usize); 8] = [
(HwStage::Ls, 0x08),
(HwStage::Hs, 0x10),
(HwStage::Es, 0x18),
(HwStage::Gs, 0x20),
(HwStage::Vs, 0x28),
(HwStage::Ps, 0x30),
(HwStage::Ms, 0x48),
(HwStage::Cs, 0x60),
];
const ABSENT: u64 = 0xDEAD_BEEF_DEAD_BEEF;
/// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes.
const MAX_UNPACKED: u64 = 16 << 20;
/// Hardware shader stage a native program runs as.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum HwStage {
Ls,
Hs,
Es,
Gs,
Vs,
Ps,
/// Mesh shader.
Ms,
Cs,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeProgram {
pub stage: HwStage,
/// GFX10 machine code.
pub code: Vec<u8>,
}
/// The native programs in a `DXIL` part's data; empty for the PC layout.
pub fn native_programs(part: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> {
if part.get(XDAT_OFFSET..XDAT_OFFSET + 4) != Some(b"XDAT") {
return Ok(Vec::new());
}
let count = u32_at(part, XDAT_OFFSET + 4)? as usize;
if count > MAX_XDAT_ENTRIES {
return Err(Malformed("implausible XDAT entry count"));
}
let mut out = Vec::new();
for i in 0..count {
let at = XDAT_OFFSET + 12 + 12 * i;
if u32_at(part, at)? != KIND_NATIVE {
continue;
}
let offset = u32_at(part, at + 4)?.into();
let size = u32_at(part, at + 8)?.into();
let blob = bytes(part, offset, size).ok_or(Malformed("XDAT entry out of bounds"))?;
out.extend(programs(&unpack(blob)?)?);
}
Ok(out)
}
fn unpack(blob: &[u8]) -> Result<Vec<u8>, ShaderError> {
if blob.get(0..4) != Some(b"XBCH") {
return Err(Malformed("native blob lacks XBCH magic"));
}
if u32_at(blob, 4)? != XBCH_VERSION {
return Err(Malformed("unknown XBCH version"));
}
let packed = u64_at(blob, 8)?;
let unpacked = u64_at(blob, 16)?;
if unpacked > MAX_UNPACKED {
return Err(Malformed("implausible XBCH unpacked size"));
}
let stream =
bytes(blob, XBCH_HEADER as u64, packed).ok_or(Malformed("XBCH stream out of bounds"))?;
let out = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(stream, unpacked as usize)
.map_err(|_| Malformed("XBCH stream does not inflate to its stated size"))?;
if out.len() as u64 != unpacked {
return Err(Malformed("XBCH stream does not inflate to its stated size"));
}
Ok(out)
}
fn programs(fssm: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> {
if fssm.get(0..4) != Some(b"FSSM") {
return Err(Malformed("native blob lacks FSSM magic"));
}
if u32_at(fssm, 4)? != FSSM_VERSION {
return Err(Malformed("unknown FSSM version"));
}
let payload = &fssm[FSSM_HEADER.min(fssm.len())..];
if u64_at(fssm, 8)? != payload.len() as u64 {
return Err(Malformed("FSSM payload size disagrees"));
}
if u64_at(payload, 0)? != GRAPHICS_SLOT_COUNT {
return Err(Malformed("unexpected FSSM slot count"));
}
let mut out = Vec::new();
for (stage, at) in SLOTS {
let record = u64_at(payload, at)?;
if record == ABSENT {
continue;
}
let record = bytes(payload, record, 16).ok_or(Malformed("FSSM record out of bounds"))?;
let code = bytes(payload, u64_at(record, 0)?, u64_at(record, 8)?)
.ok_or(Malformed("native code out of bounds"))?;
out.push(NativeProgram {
stage,
code: code.to_vec(),
});
}
Ok(out)
}
/// `data[offset..offset + len]` with untrusted 64-bit bounds.
fn bytes(data: &[u8], offset: u64, len: u64) -> Option<&[u8]> {
let start = usize::try_from(offset).ok()?;
data.get(start..start.checked_add(usize::try_from(len).ok()?)?)
}
#[cfg(test)]
mod tests {
use super::*;
const VS_CODE: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
const PS_CODE: [u8; 4] = [9, 10, 11, 12];
fn slot(stage: HwStage) -> usize {
SLOTS.iter().find(|s| s.0 == stage).unwrap().1
}
/// FSSM blob with `programs` as (stage, code) pairs.
fn fssm(programs: &[(HwStage, &[u8])]) -> Vec<u8> {
let mut payload = GRAPHICS_SLOT_COUNT.to_le_bytes().to_vec();
payload.resize(slot(HwStage::Cs) + 8, 0);
for (_, at) in SLOTS {
payload[at..at + 8].copy_from_slice(&ABSENT.to_le_bytes());
}
for &(stage, code) in programs {
let slot = slot(stage);
let record = payload.len() as u64;
payload[slot..slot + 8].copy_from_slice(&record.to_le_bytes());
payload.extend_from_slice(&(record + 16).to_le_bytes());
payload.extend_from_slice(&(code.len() as u64).to_le_bytes());
payload.extend_from_slice(code);
}
let mut out = b"FSSM".to_vec();
out.extend_from_slice(&FSSM_VERSION.to_le_bytes());
out.extend_from_slice(&(payload.len() as u64).to_le_bytes());
out.extend_from_slice(&payload);
out
}
fn xbch(unpacked: &[u8]) -> Vec<u8> {
let stream = miniz_oxide::deflate::compress_to_vec_zlib(unpacked, 6);
let mut out = b"XBCH".to_vec();
out.extend_from_slice(&XBCH_VERSION.to_le_bytes());
out.extend_from_slice(&(stream.len() as u64).to_le_bytes());
out.extend_from_slice(&(unpacked.len() as u64).to_le_bytes());
out.extend_from_slice(&stream);
out
}
/// `DXIL` part data: program header, XDAT index, then the blobs.
fn part(blobs: &[(u32, &[u8])]) -> Vec<u8> {
let mut out = vec![0u8; XDAT_OFFSET];
out.extend_from_slice(b"XDAT");
out.extend_from_slice(&(blobs.len() as u32).to_le_bytes());
out.extend_from_slice(&0x24u32.to_le_bytes());
let mut offset = out.len() + 12 * blobs.len();
for (kind, blob) in blobs {
for v in [*kind, offset as u32, blob.len() as u32] {
out.extend_from_slice(&v.to_le_bytes());
}
offset += blob.len();
}
for (_, blob) in blobs {
out.extend_from_slice(blob);
}
out
}
#[test]
fn finds_graphics_programs() {
let native = xbch(&fssm(&[(HwStage::Vs, &VS_CODE), (HwStage::Ps, &PS_CODE)]));
let data = part(&[(0x0a, b"xbop"), (KIND_NATIVE, &native)]);
let found = native_programs(&data).unwrap();
assert_eq!(
found,
[
NativeProgram {
stage: HwStage::Vs,
code: VS_CODE.to_vec()
},
NativeProgram {
stage: HwStage::Ps,
code: PS_CODE.to_vec()
},
]
);
}
#[test]
fn finds_mesh_and_compute_programs() {
for stage in [HwStage::Ms, HwStage::Cs] {
let data = part(&[(KIND_NATIVE, &xbch(&fssm(&[(stage, &VS_CODE)])))]);
let found = native_programs(&data).unwrap();
assert_eq!(found.len(), 1);
assert_eq!(found[0].stage, stage);
}
}
#[test]
fn reads_every_native_blob() {
let es = xbch(&fssm(&[(HwStage::Es, &VS_CODE)]));
let vs = xbch(&fssm(&[(HwStage::Vs, &VS_CODE)]));
let data = part(&[(0x12, &[0; 16]), (KIND_NATIVE, &es), (KIND_NATIVE, &vs)]);
let stages: Vec<_> = native_programs(&data)
.unwrap()
.iter()
.map(|p| p.stage)
.collect();
assert_eq!(stages, [HwStage::Es, HwStage::Vs]);
}
#[test]
fn pc_layout_has_none() {
assert!(native_programs(&[0u8; 64]).unwrap().is_empty());
assert!(
native_programs(&part(&[(0x0a, b"xbop")]))
.unwrap()
.is_empty()
);
}
#[test]
fn rejects_corrupt_blobs() {
let good = xbch(&fssm(&[(HwStage::Ls, &VS_CODE)]));
let corrupt = |at: usize, byte: u8| {
let mut blob = good.clone();
blob[at] = byte;
native_programs(&part(&[(KIND_NATIVE, &blob)]))
};
assert!(corrupt(4, 9).is_err(), "unknown version");
assert!(corrupt(16, 0xFF).is_err(), "stated size");
assert!(corrupt(XBCH_HEADER + 2, 0xFF).is_err(), "zlib stream");
assert!(native_programs(&part(&[(KIND_NATIVE, &good[..20])])).is_err());
let mut bad_record = fssm(&[(HwStage::Ls, &VS_CODE)]);
let at = FSSM_HEADER + slot(HwStage::Ls);
bad_record[at..at + 8].copy_from_slice(&u64::MAX.to_le_bytes());
assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&bad_record))])).is_err());
}
}