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

+24
View File
@@ -0,0 +1,24 @@
[package]
name = "victory"
description = "Command-line front end: inspect, census, convert, run."
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
victory-loader.workspace = true
victory-hle.workspace = true
victory-shader.workspace = true
victory-game.workspace = true
anyhow.workspace = true
blake3.workspace = true
memchr.workspace = true
clap.workspace = true
walkdir.workspace = true
[lints]
workspace = true
+123
View File
@@ -0,0 +1,123 @@
//! Which imports do titles need, and which do we cover?
use std::collections::{BTreeMap, BTreeSet};
use std::io::Read;
use std::path::{Path, PathBuf};
use anyhow::Result;
use victory_hle::{HleResolver, HostPolicy};
use victory_loader::Provenance;
use victory_pe::{ImageInfo, ImportSymbol};
#[derive(Default)]
struct DllStats {
functions: BTreeSet<ImportSymbol>,
hle: usize,
host: usize,
missing: usize,
images: BTreeSet<PathBuf>,
}
pub fn run(paths: Vec<PathBuf>, strict: bool, list_missing: bool) -> Result<()> {
let paths = crate::default_paths(paths)?;
let resolver = HleResolver::new(if strict {
HostPolicy::none()
} else {
HostPolicy::default()
});
let mut images = 0usize;
let mut failed = Vec::new();
let mut dlls: BTreeMap<String, DllStats> = BTreeMap::new();
let mut missing: BTreeMap<(String, String), BTreeSet<PathBuf>> = BTreeMap::new();
for root in &paths {
for entry in walkdir::WalkDir::new(root)
.into_iter()
.filter_map(Result::ok)
{
let path = entry.path();
if !entry.file_type().is_file() || !looks_like_pe(path) {
continue;
}
let info = match std::fs::read(path)
.map_err(anyhow::Error::from)
.and_then(|d| ImageInfo::parse(&d).map_err(anyhow::Error::from))
{
Ok(info) => info,
Err(e) => {
failed.push((path.to_path_buf(), e.to_string()));
continue;
}
};
images += 1;
for module in info.imports.iter().chain(&info.delay_imports) {
let key = module.dll.to_ascii_lowercase();
let stats = dlls.entry(key.clone()).or_default();
stats.images.insert(path.to_path_buf());
for e in &module.entries {
let class = resolver.classify(&module.dll, &e.symbol);
if class.is_none() {
missing
.entry((key.clone(), e.symbol.to_string()))
.or_default()
.insert(path.to_path_buf());
}
// Count each dll!function once across all images.
if stats.functions.insert(e.symbol.clone()) {
match class {
Some(Provenance::Hle) => stats.hle += 1,
Some(Provenance::Host) => stats.host += 1,
None => stats.missing += 1,
}
}
}
}
}
}
println!("{images} images scanned, {} unreadable", failed.len());
for (p, e) in &failed {
println!(" skipped {}: {e}", p.display());
}
println!(
"\n{:<56} {:>6} {:>6} {:>6} {:>8} {:>7}",
"dll", "funcs", "hle", "host", "missing", "images"
);
let (mut f, mut h, mut o, mut m) = (0, 0, 0, 0);
for (dll, s) in &dlls {
println!(
"{dll:<56} {:>6} {:>6} {:>6} {:>8} {:>7}",
s.functions.len(),
s.hle,
s.host,
s.missing,
s.images.len()
);
f += s.functions.len();
h += s.hle;
o += s.host;
m += s.missing;
}
println!("{:<56} {f:>6} {h:>6} {o:>6} {m:>8}", "TOTAL");
if list_missing {
let mut rows: Vec<_> = missing.into_iter().collect();
rows.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then_with(|| a.0.cmp(&b.0)));
println!("\nmissing (by number of images using it)");
for ((dll, sym), users) in rows {
println!(" {:>4} {dll}!{sym}", users.len());
}
}
Ok(())
}
/// Cheap pre-filter: an `MZ` header, regardless of extension (console
/// packages do not always use .exe/.dll).
fn looks_like_pe(path: &Path) -> bool {
let mut magic = [0u8; 2];
std::fs::File::open(path)
.and_then(|mut f| f.read_exact(&mut magic))
.is_ok()
&& &magic == b"MZ"
}
+153
View File
@@ -0,0 +1,153 @@
use std::collections::BTreeMap;
use std::path::Path;
use anyhow::{Context, Result};
use victory_pe::implib::ImportLibrary;
use victory_pe::{ImageInfo, layout};
pub fn run(file: &Path, list_imports: bool, list_exports: bool) -> Result<()> {
let data = std::fs::read(file).with_context(|| format!("reading {}", file.display()))?;
let info = ImageInfo::parse(&data).with_context(|| format!("parsing {}", file.display()))?;
println!("file {}", file.display());
println!("blake3 {}", blake3::hash(&data).to_hex());
if let Some(cv) = &info.codeview {
println!("pdb {} (key {})", cv.pdb_path, cv.symbol_key());
}
println!(
"kind {}",
if info.is_dll() { "dll" } else { "exe" }
);
println!(
"subsystem {} ({})",
info.subsystem,
info.subsystem_name()
);
println!(
"image base {:#x} size {:#x}",
info.image_base, info.size_of_image
);
println!("entry rva {:#x}", info.entry_rva);
println!(
"stack reserve {:#x} commit {:#x}",
info.stack_reserve, info.stack_commit
);
println!(
"dll flags {:#06x}{}",
info.dll_characteristics,
dll_flags(info.dll_characteristics)
);
println!(
"relocations {} exception table {} load config {}",
yes(info.has_relocations),
yes(info.has_exception_table),
yes(info.has_load_config)
);
if let Some(tls) = &info.tls {
println!("tls {} callback(s)", tls.callback_rvas.len());
}
println!("\nsections");
for s in &info.sections {
println!(
" {:<8} rva {:#010x} vsize {:#010x} raw {:#010x} flags {:#010x}",
s.name.trim_end_matches('\0'),
s.rva,
s.virtual_size,
s.file_size,
s.characteristics
);
}
println!(
"\nimports {} functions from {} DLLs",
info.import_count(),
info.imports.len()
);
for m in &info.imports {
println!(" {:<48} {:>5}", m.dll, m.entries.len());
if list_imports {
for e in &m.entries {
println!(" {}", e.symbol);
}
}
}
if !info.delay_imports.is_empty() {
println!("\ndelay-load imports");
for m in &info.delay_imports {
println!(" {:<48} {:>5}", m.dll, m.entries.len());
if list_imports {
for e in &m.entries {
println!(" {}", e.symbol);
}
}
}
}
println!("\nexports {}", info.exports.len());
if list_exports {
for e in &info.exports {
let name = e.name.as_deref().unwrap_or("(by ordinal)");
match (&e.rva, &e.forward) {
(_, Some(fwd)) => println!(" {:>5} {name} -> {fwd}", e.ordinal),
(Some(rva), _) => println!(" {:>5} {name} {rva:#x}", e.ordinal),
_ => println!(" {:>5} {name}", e.ordinal),
}
}
}
Ok(())
}
pub fn lib_exports(lib: &Path, list: bool) -> Result<()> {
let data = std::fs::read(lib).with_context(|| format!("reading {}", lib.display()))?;
let parsed =
ImportLibrary::parse(&data).with_context(|| format!("parsing {}", lib.display()))?;
let mut by_dll: BTreeMap<String, Vec<String>> = BTreeMap::new();
for i in &parsed.imports {
by_dll
.entry(i.dll.to_ascii_lowercase())
.or_default()
.push(i.export.to_string());
}
println!(
"{} exports from {} DLLs ({} other members)",
parsed.imports.len(),
by_dll.len(),
parsed.other_members
);
for (dll, names) in &by_dll {
println!("{dll:<60} {:>5}", names.len());
if list {
for n in names {
println!(" {n}");
}
}
}
Ok(())
}
fn yes(b: bool) -> &'static str {
if b { "yes" } else { "no" }
}
fn dll_flags(v: u16) -> String {
use layout::dll_flags::*;
let names = [
(HIGH_ENTROPY_VA, "high-entropy-va"),
(DYNAMIC_BASE, "dynamic-base"),
(FORCE_INTEGRITY, "force-integrity"),
(NX_COMPAT, "nx"),
(APPCONTAINER, "appcontainer"),
(GUARD_CF, "cfg"),
];
let set: Vec<_> = names
.iter()
.filter(|(f, _)| v & f != 0)
.map(|(_, n)| *n)
.collect();
if set.is_empty() {
String::new()
} else {
format!(" ({})", set.join(", "))
}
}
+165
View File
@@ -0,0 +1,165 @@
//! `victory`: the command-line front end.
//!
//! Every command reads the user's own files and writes only to stdout or to
//! the user's cache directory (outside the repository).
mod census;
mod inspect;
mod run;
mod shader;
use std::path::PathBuf;
use anyhow::Result;
use clap::{Parser, Subcommand, ValueEnum};
#[derive(Parser)]
#[command(
name = "victory",
version,
about = "Run an Xbox Series title natively on Windows"
)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
/// Summarise one PE image: headers, sections, imports, TLS, build id.
Inspect {
file: PathBuf,
/// List every imported function.
#[arg(long)]
imports: bool,
/// List every exported function.
#[arg(long)]
exports: bool,
},
/// Aggregate the imports of every PE image under the given paths and
/// show which ones our runtime covers. Defaults to the configured
/// game and test-title directories.
Census {
paths: Vec<PathBuf>,
/// Do not count host pass-through as covered.
#[arg(long)]
strict: bool,
/// List every missing `dll!function`, most used first.
#[arg(long)]
missing: bool,
},
/// List the `dll!export` pairs an import library describes.
LibExports {
lib: PathBuf,
/// List every export, not just per-DLL counts.
#[arg(long)]
list: bool,
},
/// Find shader containers in files or directories (also inside engine
/// archives, if uncompressed) and report their layout.
ShaderInfo {
paths: Vec<PathBuf>,
/// Print one line per container found.
#[arg(long)]
verbose: bool,
/// Also list the decoded native instructions (implies --verbose).
#[arg(long)]
disasm: bool,
},
/// Prepare, map and bind a title executable; with --execute, run it.
Run {
exe: PathBuf,
/// What unimplemented imports do when called.
#[arg(long, value_enum, default_value_t = Unimplemented::Trap)]
unimplemented: Unimplemented,
/// Disable host pass-through (everything must be implemented by us).
#[arg(long)]
strict: bool,
/// Actually start the title. Without it, stop after binding.
#[arg(long)]
execute: bool,
},
/// Show the resolved configuration and check it.
Config,
}
#[derive(Clone, Copy, ValueEnum)]
enum Unimplemented {
Trap,
Zero,
}
fn main() -> Result<()> {
victory_core::logging::init("info");
let cli = Cli::parse();
match cli.command {
Command::Inspect {
file,
imports,
exports,
} => inspect::run(&file, imports, exports),
Command::Census {
paths,
strict,
missing,
} => census::run(paths, strict, missing),
Command::LibExports { lib, list } => inspect::lib_exports(&lib, list),
Command::ShaderInfo {
paths,
verbose,
disasm,
} => shader::run(paths, verbose || disasm, disasm),
Command::Run {
exe,
unimplemented,
strict,
execute,
} => run::run(&exe, unimplemented, strict, execute),
Command::Config => show_config(),
}
}
fn show_config() -> Result<()> {
let cfg = victory_core::Config::load()?;
let status = |p: &Option<PathBuf>| match p {
Some(p) if p.exists() => format!("{}", p.display()),
Some(p) => format!("{} (does not exist)", p.display()),
None => "(not set)".to_owned(),
};
println!(
"config file : {}",
cfg.source
.as_ref()
.map_or("(none)".into(), |p| p.display().to_string())
);
println!("game_dir : {}", status(&cfg.game_dir));
println!("cache_dir : {}", cfg.cache_dir.display());
for t in &cfg.test_titles {
println!("test_title : {}", status(&Some(t.clone())));
}
for p in cfg
.game_dir
.iter()
.chain(&cfg.test_titles)
.chain([&cfg.cache_dir])
{
if let Err(e) = victory_core::ensure_outside_repo(p) {
println!("POLICY VIOLATION: {e}");
}
}
Ok(())
}
/// Paths given on the command line, or the configured game + test titles.
pub(crate) fn default_paths(paths: Vec<PathBuf>) -> Result<Vec<PathBuf>> {
if !paths.is_empty() {
return Ok(paths);
}
let cfg = victory_core::Config::load()?;
let all: Vec<PathBuf> = cfg.game_dir.into_iter().chain(cfg.test_titles).collect();
anyhow::ensure!(
!all.is_empty(),
"no paths given and none configured (see victory.example.toml)"
);
Ok(all)
}
+64
View File
@@ -0,0 +1,64 @@
use std::path::Path;
use anyhow::{Context, Result};
use crate::Unimplemented;
#[cfg(windows)]
pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool) -> Result<()> {
use std::sync::Arc;
use victory_hle::{HleResolver, HostPolicy};
use victory_loader::UnimplementedPolicy;
let cfg = victory_core::Config::load()?;
let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?;
let prepared = victory_loader::prepare(&original)?;
let hash = prepared.original_hash.to_hex();
match victory_game::identify(&hash) {
Some(build) => println!("build {} ({hash})", build.label),
None => println!("build unknown ({hash})"),
}
let image = victory_loader::load(&prepared, &cfg.cache_subdir("images")?)?;
victory_hle::runtime::set_main_image(image.base());
let resolver = HleResolver::new(if strict {
HostPolicy::none()
} else {
HostPolicy::default()
});
let policy = match unimplemented {
Unimplemented::Trap => UnimplementedPolicy::Trap,
Unimplemented::Zero => UnimplementedPolicy::ReturnZero,
};
let report = image.bind_imports(&resolver, policy)?;
println!(
"mapped at {:#x} (preferred {:#x})",
image.base(),
image.info().image_base
);
println!(
"bound {} hle, {} host, {} missing",
report.hle,
report.host,
report.missing.len()
);
for m in &report.missing {
println!(" missing {}!{}", m.dll, m.symbol);
}
if !execute {
println!("not executing (pass --execute to start the title)");
return Ok(());
}
// SAFETY: imports are bound; from here on we run title code.
let main = unsafe { Arc::new(image).spawn_main()? };
let code = main
.join()
.map_err(|_| anyhow::anyhow!("title main thread panicked"))?;
println!("title exited with {code}");
Ok(())
}
#[cfg(not(windows))]
pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool) -> Result<()> {
anyhow::bail!("running titles requires Windows")
}
+176
View File
@@ -0,0 +1,176 @@
//! Survey shader containers: bitcode, console additions and native code.
use std::collections::BTreeMap;
use std::path::PathBuf;
use anyhow::Result;
use victory_shader::gfx10::{self, Instruction};
use victory_shader::{Container, DxilProgram, FourCC, HwStage, ShaderError, native_programs};
/// Files above this size are skipped (read whole into memory for now).
const MAX_FILE: u64 = 2 << 30;
#[derive(Default)]
struct Totals {
containers: usize,
with_dxil_part: usize,
with_bitcode: usize,
standard_layout: usize,
xdat: usize,
xbop: usize,
kinds: BTreeMap<String, usize>,
with_native: usize,
native_stages: BTreeMap<HwStage, usize>,
native_errors: BTreeMap<String, usize>,
decoded: usize,
instructions: usize,
unnamed: BTreeMap<String, usize>,
decode_errors: BTreeMap<&'static str, usize>,
files_with_shaders: usize,
}
pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> {
let paths = crate::default_paths(paths)?;
let mut t = Totals::default();
for root in &paths {
for entry in walkdir::WalkDir::new(root)
.into_iter()
.filter_map(Result::ok)
{
if !entry.file_type().is_file() {
continue;
}
let path = entry.path();
if entry.metadata().map(|m| m.len()).unwrap_or(0) > MAX_FILE {
eprintln!("skipping large file {}", path.display());
continue;
}
let Ok(data) = std::fs::read(path) else {
continue;
};
let mut found_here = 0;
for offset in memchr::memmem::find_iter(&data, b"DXBC") {
let Ok(container) = Container::parse(&data[offset..]) else {
continue;
};
found_here += 1;
t.containers += 1;
let dxil = container.part(FourCC::DXIL);
t.with_dxil_part += usize::from(dxil.is_some());
let program = dxil.and_then(|p| DxilProgram::parse(p.data).ok());
let mut listing = Vec::new();
// Independent of the bitcode: titles may strip it.
let native = match dxil.map(|p| native_programs(p.data)) {
Some(Ok(programs)) if !programs.is_empty() => {
t.with_native += 1;
let mut list = Vec::new();
for n in &programs {
*t.native_stages.entry(n.stage).or_default() += 1;
list.push(format!("{:?} {} B", n.stage, n.code.len()));
match gfx10::decode(&n.code) {
Ok(insts) => {
t.decoded += 1;
t.instructions += insts.len();
for i in insts.iter().filter(|i| i.name().is_none()) {
let key = format!("{:?} {:#x}", i.encoding, i.opcode);
*t.unnamed.entry(key).or_default() += 1;
}
if disasm {
listing.extend(insts.iter().map(format_instruction));
}
}
Err(e) => {
let reason = match e {
ShaderError::Isa { reason, .. } => reason,
_ => "other",
};
*t.decode_errors.entry(reason).or_default() += 1;
list.push(format!("({e})"));
}
}
}
format!(", native {}", list.join(" "))
}
Some(Err(e)) => {
*t.native_errors.entry(e.to_string()).or_default() += 1;
format!(", native: {e}")
}
_ => String::new(),
};
let line = match &program {
Some(p) => {
t.with_bitcode += 1;
let x = p.xbox_extras();
t.standard_layout += usize::from(p.is_standard_layout());
t.xdat += usize::from(x.xdat);
t.xbop += usize::from(x.xbop);
*t.kinds.entry(format!("{:?}", p.kind)).or_default() += 1;
format!(
"{:?} sm{}.{} bitcode {} B, xdat {}, xbop {}",
p.kind,
p.shader_model.0,
p.shader_model.1,
p.bitcode.len(),
x.xdat,
x.xbop
)
}
None => "no parsable DXIL program".to_owned(),
} + &native;
if verbose {
println!("{}@{offset:#x}: {line}", path.display());
for l in &listing {
println!("{l}");
}
}
}
t.files_with_shaders += usize::from(found_here > 0);
}
}
println!(
"containers found {} (in {} files)",
t.containers, t.files_with_shaders
);
println!(" with DXIL part {}", t.with_dxil_part);
println!(" with LLVM bitcode {}", t.with_bitcode);
println!(" PC-standard layout {}", t.standard_layout);
println!(" XDAT prefix {}", t.xdat);
println!(" xbop trailer {}", t.xbop);
for (k, n) in &t.kinds {
println!(" {k:<20} {n}");
}
println!(" with native code {}", t.with_native);
for (stage, n) in &t.native_stages {
println!(" {:<18} {n}", format!("{stage:?}"));
}
for (e, n) in &t.native_errors {
println!(" native unreadable {n}: {e}");
}
if t.with_native > 0 {
println!(
" decoded programs {} ({} instructions)",
t.decoded, t.instructions
);
for (e, n) in &t.decode_errors {
println!(" decode failed {n}: {e}");
}
let mut unnamed: Vec<_> = t.unnamed.iter().collect();
unnamed.sort_by_key(|&(_, n)| std::cmp::Reverse(*n));
for (op, n) in unnamed.iter().take(10) {
println!(" opcode not in table {op} x{n}");
}
}
if t.containers == 0 {
println!("(none found: shaders may sit in compressed or encrypted archives)");
}
Ok(())
}
fn format_instruction(i: &Instruction) -> String {
let words: Vec<_> = i.words.iter().map(|w| format!("{w:08X}")).collect();
let name = match i.name() {
Some(n) => n.to_owned(),
None => format!("<{:?} {:#x}>", i.encoding, i.opcode),
};
format!(" {:06x}: {:<44} {name}", i.offset, words.join(" "))
}