Run Minecraft: runtime HLE, D3D12.X device on the host GPU, shader IR
Loader: map title-shipped DLLs, patch static TLS loads to slot 0, crash reporter, title paths for GetModuleFileName*. HLE: task queue and async, XUser (one offline user), system ids, title id, features, invites, game events, persistent local storage, GameInput with no devices, xmem, console audio hardware queues, life cycle (close suspends, then terminates), and a file layer with virtual drives rewritten in path-taking imports. GPU: D3D12.X device, DXGI chain, heaps, resources, fences, queues and command lists translated onto a host D3D12 device; clears, barriers, copies, resolves and PresentX into the title's window. Shaders: SGD5 reader and `victory translate`; SSA IR with node splitting for irreducible flow; structurisation removing EXEC. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
12caefe804
commit
754619f30e
61 files changed
+12775
-88
No files matched your search
@@ -68,6 +68,7 @@ pub fn run(paths: Vec<PathBuf>, strict: bool, list_missing: bool) -> Result<()>
|
||||
match class {
|
||||
Some(Provenance::Hle) => stats.hle += 1,
|
||||
Some(Provenance::Host) => stats.host += 1,
|
||||
Some(Provenance::Title) => unreachable!("census maps no title DLLs"),
|
||||
None => stats.missing += 1,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ mod census;
|
||||
mod inspect;
|
||||
mod run;
|
||||
mod shader;
|
||||
mod translate;
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -66,6 +67,9 @@ enum Command {
|
||||
#[arg(long)]
|
||||
disasm: bool,
|
||||
},
|
||||
/// Run every shader found (containers, SGD5 files) through the
|
||||
/// translator and report what it cannot handle yet.
|
||||
Translate { paths: Vec<PathBuf> },
|
||||
/// Prepare, map and bind a title executable; with --execute, run it.
|
||||
Run {
|
||||
exe: PathBuf,
|
||||
@@ -109,6 +113,7 @@ fn main() -> Result<()> {
|
||||
verbose,
|
||||
disasm,
|
||||
} => shader::run(paths, verbose || disasm, disasm),
|
||||
Command::Translate { paths } => translate::run(paths),
|
||||
Command::Run {
|
||||
exe,
|
||||
unimplemented,
|
||||
|
||||
+57
-20
@@ -8,7 +8,7 @@ use crate::Unimplemented;
|
||||
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;
|
||||
use victory_loader::{BindReport, UnimplementedPolicy, WithTitleDlls};
|
||||
|
||||
let cfg = victory_core::Config::load()?;
|
||||
let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?;
|
||||
@@ -19,41 +19,78 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool
|
||||
None => println!("build unknown ({hash})"),
|
||||
}
|
||||
|
||||
let image = victory_loader::load(&prepared, &cfg.cache_subdir("images")?)?;
|
||||
let images = cfg.cache_subdir("images")?;
|
||||
let image = victory_loader::load(&prepared, &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)?;
|
||||
victory_hle::runtime::set_image_path(image.base(), exe);
|
||||
println!(
|
||||
"mapped at {:#x} (preferred {:#x})",
|
||||
image.base(),
|
||||
image.info().image_base
|
||||
);
|
||||
let resolver = HleResolver::new(if strict {
|
||||
HostPolicy::none()
|
||||
} else {
|
||||
HostPolicy::default()
|
||||
});
|
||||
// DLLs the host or our runtime provide are never taken from the title.
|
||||
let wanted = |dll: &str| {
|
||||
!resolver.host.allows(dll) && !victory_hle::registry().iter().any(|m| m.serves(dll))
|
||||
};
|
||||
let title_dir = exe.parent().unwrap_or(Path::new("."));
|
||||
// A missing manifest leaves id 0 and no storage quota.
|
||||
let manifest =
|
||||
std::fs::read_to_string(title_dir.join("MicrosoftGame.config")).unwrap_or_default();
|
||||
let title = victory_hle::runtime::Title::from_manifest(&manifest);
|
||||
let storage = cfg.data_subdir(&format!("{:08X}/storage", title.id))?;
|
||||
println!(
|
||||
"bound {} hle, {} host, {} missing",
|
||||
report.hle,
|
||||
report.host,
|
||||
report.missing.len()
|
||||
"title {:08X}, storage {} ({} MB)",
|
||||
title.id,
|
||||
storage.display(),
|
||||
title.storage_bytes >> 20
|
||||
);
|
||||
for m in &report.missing {
|
||||
println!(" missing {}!{}", m.dll, m.symbol);
|
||||
victory_hle::runtime::set_title(victory_hle::runtime::Title { storage, ..title });
|
||||
let dlls = victory_loader::load_title_dlls(image.info(), title_dir, &images, &wanted)?;
|
||||
for (name, dll) in &dlls {
|
||||
println!("title dll {name} at {:#x}", dll.base());
|
||||
victory_hle::runtime::set_image_path(dll.base(), &title_dir.join(name));
|
||||
}
|
||||
|
||||
let policy = match unimplemented {
|
||||
Unimplemented::Trap => UnimplementedPolicy::Trap,
|
||||
Unimplemented::Zero => UnimplementedPolicy::ReturnZero,
|
||||
};
|
||||
let with_dlls = WithTitleDlls {
|
||||
inner: &resolver,
|
||||
dlls: &dlls,
|
||||
};
|
||||
let show = |name: &str, report: BindReport| {
|
||||
println!(
|
||||
"bound {name}: {} hle, {} host, {} title, {} missing",
|
||||
report.hle,
|
||||
report.host,
|
||||
report.title,
|
||||
report.missing.len()
|
||||
);
|
||||
for m in &report.missing {
|
||||
println!(" missing {}!{}", m.dll, m.symbol);
|
||||
}
|
||||
};
|
||||
for (name, dll) in &dlls {
|
||||
show(name, dll.bind_imports(&with_dlls, policy)?);
|
||||
}
|
||||
let exe_name = exe.file_name().unwrap_or_default().to_string_lossy();
|
||||
show(&exe_name, image.bind_imports(&with_dlls, policy)?);
|
||||
if !execute {
|
||||
println!("not executing (pass --execute to start the title)");
|
||||
return Ok(());
|
||||
}
|
||||
victory_loader::report_crashes();
|
||||
// SAFETY: imports are bound; from here on we run title code.
|
||||
let main = unsafe { Arc::new(image).spawn_main()? };
|
||||
let main = unsafe { Arc::new(image).spawn_main(dlls)? };
|
||||
let code = main
|
||||
.join()
|
||||
.map_err(|_| anyhow::anyhow!("title main thread panicked"))?;
|
||||
.map_err(|_| anyhow::anyhow!("title main thread panicked"))??;
|
||||
println!("title exited with {code}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,14 +1,53 @@
|
||||
//! Survey shader containers: bitcode, console additions and native code.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Result;
|
||||
use victory_game::sgd5;
|
||||
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;
|
||||
pub(crate) const MAX_FILE: u64 = 2 << 30;
|
||||
|
||||
/// A shader container in a file: as is, or packed in an SGD5 record.
|
||||
pub(crate) enum Source<'a> {
|
||||
Raw { offset: usize, data: &'a [u8] },
|
||||
Packed(sgd5::Record<'a>),
|
||||
}
|
||||
|
||||
impl Source<'_> {
|
||||
/// The container bytes; `None` if a packed record is corrupt.
|
||||
pub(crate) fn bytes(&self) -> Option<Cow<'_, [u8]>> {
|
||||
match self {
|
||||
Source::Raw { data, .. } => Some(Cow::Borrowed(data)),
|
||||
Source::Packed(r) => r.unpack().map(Cow::Owned),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn label(&self) -> String {
|
||||
match self {
|
||||
Source::Raw { offset, .. } => format!("@{offset:#x}"),
|
||||
Source::Packed(r) => format!("@{:#x} {}", r.offset, r.name.unwrap_or("?")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The records of an SGD5 file, or else every container found by its magic.
|
||||
pub(crate) fn sources(data: &[u8]) -> Vec<Source<'_>> {
|
||||
if sgd5::is_sgd5(data) {
|
||||
return sgd5::records(data).map(Source::Packed).collect();
|
||||
}
|
||||
memchr::memmem::find_iter(data, b"DXBC")
|
||||
.filter(|&offset| Container::parse(&data[offset..]).is_ok())
|
||||
.map(|offset| Source::Raw {
|
||||
offset,
|
||||
data: &data[offset..],
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Totals {
|
||||
@@ -49,8 +88,12 @@ pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> {
|
||||
continue;
|
||||
};
|
||||
let mut found_here = 0;
|
||||
for offset in memchr::memmem::find_iter(&data, b"DXBC") {
|
||||
let Ok(container) = Container::parse(&data[offset..]) else {
|
||||
for source in sources(&data) {
|
||||
let Some(bytes) = source.bytes() else {
|
||||
eprintln!("corrupt record {}{}", path.display(), source.label());
|
||||
continue;
|
||||
};
|
||||
let Ok(container) = Container::parse(&bytes) else {
|
||||
continue;
|
||||
};
|
||||
found_here += 1;
|
||||
@@ -120,7 +163,7 @@ pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> {
|
||||
None => "no parsable DXIL program".to_owned(),
|
||||
} + &native;
|
||||
if verbose {
|
||||
println!("{}@{offset:#x}: {line}", path.display());
|
||||
println!("{}{}: {line}", path.display(), source.label());
|
||||
for l in &listing {
|
||||
println!("{l}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
//! The offline batch: every shader found goes through the translator, and
|
||||
//! what it cannot handle yet is tallied (decision 0003).
|
||||
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use anyhow::Result;
|
||||
use victory_shader::structure::{self, Atom, LaneExit};
|
||||
use victory_shader::{Container, FourCC, ShaderError, ir, native_programs};
|
||||
|
||||
use crate::shader::{MAX_FILE, Source, sources};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Tally {
|
||||
containers: usize,
|
||||
duplicates: usize,
|
||||
programs: usize,
|
||||
translated: usize,
|
||||
instructions: usize,
|
||||
structured: usize,
|
||||
vector: usize,
|
||||
guarded: usize,
|
||||
/// Guards that read a mask the pass cannot see into.
|
||||
opaque: usize,
|
||||
lane_branches: usize,
|
||||
uniform_branches: usize,
|
||||
/// Reason → programs stopped by it, and the first one.
|
||||
failed: BTreeMap<String, (usize, String)>,
|
||||
}
|
||||
|
||||
impl Tally {
|
||||
fn fail(&mut self, reason: String, example: impl FnOnce() -> String) {
|
||||
self.failed
|
||||
.entry(reason)
|
||||
.or_insert_with(|| (0, example()))
|
||||
.0 += 1;
|
||||
}
|
||||
|
||||
fn merge(&mut self, other: Tally) {
|
||||
self.containers += other.containers;
|
||||
self.duplicates += other.duplicates;
|
||||
self.programs += other.programs;
|
||||
self.translated += other.translated;
|
||||
self.instructions += other.instructions;
|
||||
self.structured += other.structured;
|
||||
self.vector += other.vector;
|
||||
self.guarded += other.guarded;
|
||||
self.opaque += other.opaque;
|
||||
self.lane_branches += other.lane_branches;
|
||||
self.uniform_branches += other.uniform_branches;
|
||||
for (reason, (n, example)) in other.failed {
|
||||
self.failed.entry(reason).or_insert((0, example)).0 += n;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(paths: Vec<PathBuf>) -> Result<()> {
|
||||
let paths = crate::default_paths(paths)?;
|
||||
let threads = std::thread::available_parallelism().map_or(4, |n| n.get());
|
||||
let seen = Mutex::new(HashSet::new());
|
||||
let total = Mutex::new(Tally::default());
|
||||
for root in &paths {
|
||||
for entry in walkdir::WalkDir::new(root)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE {
|
||||
continue;
|
||||
}
|
||||
let Ok(data) = std::fs::read(entry.path()) else {
|
||||
continue;
|
||||
};
|
||||
let jobs = sources(&data);
|
||||
let next = AtomicUsize::new(0);
|
||||
std::thread::scope(|s| {
|
||||
for _ in 0..threads.min(jobs.len()) {
|
||||
s.spawn(|| {
|
||||
let mut t = Tally::default();
|
||||
while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) {
|
||||
translate(job, entry.path(), &seen, &mut t);
|
||||
}
|
||||
lock(&total).merge(t);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
let t = total.into_inner().unwrap_or_else(|e| e.into_inner());
|
||||
println!(
|
||||
"containers {} ({} duplicates skipped)",
|
||||
t.containers, t.duplicates
|
||||
);
|
||||
println!(
|
||||
"programs {} translated of {} ({} IR instructions)",
|
||||
t.translated, t.programs, t.instructions
|
||||
);
|
||||
println!(
|
||||
"structured {} of {} ({} vector instructions, {} guarded, {} on opaque masks; \
|
||||
branches {} per lane, {} uniform)",
|
||||
t.structured,
|
||||
t.translated,
|
||||
t.vector,
|
||||
t.guarded,
|
||||
t.opaque,
|
||||
t.lane_branches,
|
||||
t.uniform_branches
|
||||
);
|
||||
let mut failed: Vec<_> = t.failed.into_iter().collect();
|
||||
failed.sort_by_key(|(_, (n, _))| std::cmp::Reverse(*n));
|
||||
for (reason, (n, example)) in failed {
|
||||
println!(" {n:>7} {reason} (e.g. {example})");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn translate(source: &Source, path: &Path, seen: &Mutex<HashSet<blake3::Hash>>, t: &mut Tally) {
|
||||
let example = || format!("{}{}", path.display(), source.label());
|
||||
let Some(bytes) = source.bytes() else {
|
||||
return t.fail("corrupt record".into(), example);
|
||||
};
|
||||
t.containers += 1;
|
||||
let Some(dxil) = Container::parse(&bytes)
|
||||
.ok()
|
||||
.and_then(|c| c.part(FourCC::DXIL).map(|p| p.data))
|
||||
else {
|
||||
return t.fail("no DXIL part (SM5 or older)".into(), example);
|
||||
};
|
||||
if !lock(seen).insert(blake3::hash(dxil)) {
|
||||
t.duplicates += 1;
|
||||
return;
|
||||
}
|
||||
let programs = match native_programs(dxil) {
|
||||
Ok(p) => p,
|
||||
Err(e) => return t.fail(e.to_string(), example),
|
||||
};
|
||||
for p in programs {
|
||||
t.programs += 1;
|
||||
match ir::build(&p.code, p.wave64, p.vgprs) {
|
||||
Ok(program) => {
|
||||
t.translated += 1;
|
||||
t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::<usize>();
|
||||
match structure::structure(&program) {
|
||||
Ok(s) => tally_structured(&program, &s, t),
|
||||
Err(e) => {
|
||||
let reason = match e {
|
||||
ShaderError::Unsupported { what, .. } => format!("structure: {what}"),
|
||||
ShaderError::Isa { reason, .. } => format!("structure: {reason}"),
|
||||
e => e.to_string(),
|
||||
};
|
||||
t.fail(reason, || format!("{} {:?}", example(), p.stage));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let reason = match e {
|
||||
ShaderError::Unsupported { what, .. } => format!("unsupported: {what}"),
|
||||
e => e.to_string(),
|
||||
};
|
||||
t.fail(reason, || format!("{} {:?}", example(), p.stage));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn tally_structured(program: &ir::Program, s: &structure::Structured, t: &mut Tally) {
|
||||
t.structured += 1;
|
||||
for (block, guards) in program.blocks.iter().zip(&s.guards) {
|
||||
t.vector += block
|
||||
.insts
|
||||
.iter()
|
||||
.filter(|i| i.read(ir::Reg::S(ir::EXEC)).is_some())
|
||||
.count();
|
||||
for &g in guards.iter().flatten() {
|
||||
t.guarded += 1;
|
||||
let support = s.bools.support(g);
|
||||
t.opaque += usize::from(support.iter().any(|a| matches!(a, Atom::Opaque(_))));
|
||||
}
|
||||
}
|
||||
for exit in &s.exits {
|
||||
if let LaneExit::Branch { when, .. } = *exit {
|
||||
if s.bools
|
||||
.support(when)
|
||||
.iter()
|
||||
.all(|a| matches!(a, Atom::Uniform(_)))
|
||||
{
|
||||
t.uniform_branches += 1;
|
||||
} else {
|
||||
t.lane_branches += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
Reference in new issue
Block a user