diff --git a/apps/victory/src/census.rs b/apps/victory/src/census.rs index 93987197d0..407ea33580 100644 --- a/apps/victory/src/census.rs +++ b/apps/victory/src/census.rs @@ -7,17 +7,60 @@ use std::path::{Path, PathBuf}; use anyhow::Result; use victory_hle::{HleResolver, HostPolicy}; use victory_loader::Provenance; -use victory_pe::{ImageInfo, ImportSymbol}; +use victory_pe::{ExportInfo, ImageInfo, ImportSymbol}; #[derive(Default)] struct DllStats { functions: BTreeSet, hle: usize, host: usize, + title: usize, missing: usize, images: BTreeSet, } +/// What a scanned DLL exports, by name and by ordinal. +#[derive(Default)] +struct Exports { + names: BTreeSet, + ordinals: BTreeSet, +} + +impl Exports { + fn new(exports: &[ExportInfo]) -> Self { + Exports { + names: exports.iter().filter_map(|e| e.name.clone()).collect(), + ordinals: exports.iter().map(|e| e.ordinal).collect(), + } + } + + fn has(&self, symbol: &ImportSymbol) -> bool { + match symbol { + ImportSymbol::Name { name, .. } => self.names.contains(name), + ImportSymbol::Ordinal(o) => self.ordinals.contains(o), + } + } +} + +/// The scanned DLLs' exports, by folder and lower-case file name. +type TitleDlls = BTreeMap<(PathBuf, String), Exports>; + +/// Where `run` would bind an import of an image in `dir`: HLE or the host, +/// else (as `WithTitleDlls`) a title DLL of that name in the same folder. +fn classify( + resolver: &HleResolver, + title_dlls: &TitleDlls, + dir: &Path, + dll: &str, + symbol: &ImportSymbol, +) -> Option { + resolver.classify(dll, symbol).or_else(|| { + let exports = title_dlls.get(&(dir.to_path_buf(), dll.to_ascii_lowercase()))?; + (crate::run::title_dll(&resolver.host, dll) && exports.has(symbol)) + .then_some(Provenance::Title) + }) +} + pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> { let paths = crate::default_paths(paths)?; let resolver = HleResolver::new(if strict { @@ -26,7 +69,7 @@ pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> HostPolicy::default() }); - let mut images = 0usize; + let mut images = Vec::new(); let mut failed = Vec::new(); let mut dlls: BTreeMap = BTreeMap::new(); let mut missing: BTreeMap<(String, String), BTreeSet> = BTreeMap::new(); @@ -50,57 +93,77 @@ pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> 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, - Some(Provenance::Title) => unreachable!("census maps no title DLLs"), - None => stats.missing += 1, - } + images.push((path.to_path_buf(), info)); + } + } + + // The title's own DLLs, wherever the walk met them. + let title_dlls: TitleDlls = images + .iter() + .filter_map(|(path, info)| { + let dir = path.parent()?.to_path_buf(); + let name = path.file_name()?.to_str()?.to_ascii_lowercase(); + Some(((dir, name), Exports::new(&info.exports))) + }) + .collect(); + + for (path, info) in &images { + let dir = path.parent().unwrap_or(Path::new("")); + 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.clone()); + for e in &module.entries { + let class = classify(&resolver, &title_dlls, dir, &module.dll, &e.symbol); + if class.is_none() { + missing + .entry((key.clone(), e.symbol.to_string())) + .or_default() + .insert(path.clone()); + } + // 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, + Some(Provenance::Title) => stats.title += 1, + None => stats.missing += 1, } } } } } - println!("{images} images scanned, {} unreadable", failed.len()); + println!( + "{} images scanned, {} unreadable", + images.len(), + 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" + "\n{:<56} {:>6} {:>6} {:>6} {:>6} {:>8} {:>7}", + "dll", "funcs", "hle", "host", "title", "missing", "images" ); - let (mut f, mut h, mut o, mut m) = (0, 0, 0, 0); + let (mut f, mut h, mut o, mut t, mut m) = (0, 0, 0, 0, 0); for (dll, s) in &dlls { println!( - "{dll:<56} {:>6} {:>6} {:>6} {:>8} {:>7}", + "{dll:<56} {:>6} {:>6} {:>6} {:>6} {:>8} {:>7}", s.functions.len(), s.hle, s.host, + s.title, s.missing, s.images.len() ); f += s.functions.len(); h += s.hle; o += s.host; + t += s.title; m += s.missing; } - println!("{:<56} {f:>6} {h:>6} {o:>6} {m:>8}", "TOTAL"); + println!("{:<56} {f:>6} {h:>6} {o:>6} {t:>6} {m:>8}", "TOTAL"); if list_missing { let mut rows: Vec<_> = missing.into_iter().collect(); @@ -122,3 +185,65 @@ fn looks_like_pe(path: &Path) -> bool { .is_ok() && &magic == b"MZ" } + +#[cfg(test)] +mod tests { + use super::*; + + fn export(name: Option<&str>, ordinal: u16) -> ExportInfo { + ExportInfo { + name: name.map(Into::into), + ordinal, + rva: Some(0x1000), + forward: None, + } + } + + fn named(name: &str) -> ImportSymbol { + ImportSymbol::Name { + hint: 0, + name: name.into(), + } + } + + fn title_dlls(dir: &Path, dll: &str) -> TitleDlls { + let exports = [export(Some("TitleOnly"), 1), export(None, 7)]; + [((dir.to_path_buf(), dll.into()), Exports::new(&exports))].into() + } + + #[test] + fn imports_of_a_title_dll_in_the_same_folder_are_title() { + let r = HleResolver::default(); + let dir = Path::new("title"); + let dlls = title_dlls(dir, "victorytitle.dll"); + // Import names keep the case the importing image uses. + let dll = "VictoryTitle.dll"; + let title = Some(Provenance::Title); + assert_eq!(classify(&r, &dlls, dir, dll, &named("TitleOnly")), title); + assert_eq!( + classify(&r, &dlls, dir, dll, &ImportSymbol::Ordinal(7)), + title + ); + assert_eq!(classify(&r, &dlls, dir, dll, &named("Absent")), None); + assert_eq!( + classify(&r, &dlls, dir, dll, &ImportSymbol::Ordinal(2)), + None + ); + // The loader only maps title DLLs from the title's own folder. + let other = Path::new("elsewhere"); + assert_eq!(classify(&r, &dlls, other, dll, &named("TitleOnly")), None); + } + + #[test] + fn host_and_hle_dlls_are_never_taken_from_the_title() { + let r = HleResolver::default(); + let dir = Path::new("title"); + // A title folder shipping its own copy of a host-allowed DLL. + let dlls = title_dlls(dir, "kernel32.dll"); + assert!(!crate::run::title_dll(&r.host, "kernel32.dll")); + assert_eq!( + classify(&r, &dlls, dir, "kernel32.dll", &named("TitleOnly")), + None + ); + } +} diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 52131478d7..d8aee2732a 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -180,8 +180,7 @@ fn watch(base: usize, size: usize) { } /// DLLs the host or our runtime provide are never taken from the title. -#[cfg(windows)] -fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool { +pub(crate) fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool { !host.allows(dll) && !victory_hle::registry().iter().any(|m| m.serves(dll)) }