| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334 |
- //! 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::{Context, Result};
- use victory_hle::{HleResolver, HostPolicy};
- use victory_loader::Provenance;
- use victory_pe::{ImageInfo, ImportSymbol};
- #[derive(PartialEq, Eq, PartialOrd, Ord)]
- enum FunctionKey {
- Name(String),
- Ordinal(u16),
- }
- impl From<&ImportSymbol> for FunctionKey {
- fn from(symbol: &ImportSymbol) -> Self {
- match symbol {
- ImportSymbol::Name { name, .. } => Self::Name(name.clone()),
- ImportSymbol::Ordinal(ordinal) => Self::Ordinal(*ordinal),
- }
- }
- }
- #[derive(Default)]
- struct DllStats {
- functions: BTreeSet<FunctionKey>,
- 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 seen = BTreeSet::new();
- 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) {
- let entry = match entry {
- Ok(entry) => entry,
- Err(error) if error.depth() == 0 => {
- return Err(error).context("cannot scan census input");
- }
- Err(error) => {
- failed.push(error.to_string());
- continue;
- }
- };
- let path = entry.path();
- if !entry.file_type().is_file() || !looks_like_pe(path) {
- continue;
- }
- // Use the resolved path for deduplication and keep the original for output.
- let identity = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
- if !seen.insert(identity) {
- 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(format!("{}: {e}", path.display()));
- continue;
- }
- };
- images += 1;
- tally_image(path, &info, &resolver, &mut dlls, &mut missing);
- }
- }
- println!("{images} images scanned, {} unreadable", failed.len());
- for error in &failed {
- println!(" skipped {error}");
- }
- 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"
- }
- fn tally_image(
- path: &Path,
- info: &ImageInfo,
- resolver: &HleResolver,
- dlls: &mut BTreeMap<String, DllStats>,
- missing: &mut BTreeMap<(String, String), BTreeSet<PathBuf>>,
- ) {
- 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(FunctionKey::from(&e.symbol)) {
- 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,
- }
- }
- }
- }
- }
- #[cfg(test)]
- mod tests {
- use super::*;
- use victory_pe::{ImportEntry, ImportModule};
- fn entry(symbol: ImportSymbol) -> ImportEntry {
- ImportEntry {
- symbol,
- iat_slot_rva: 0,
- }
- }
- fn named(hint: u16, name: &str) -> ImportEntry {
- entry(ImportSymbol::Name {
- hint,
- name: name.into(),
- })
- }
- fn ordinal(ord: u16) -> ImportEntry {
- entry(ImportSymbol::Ordinal(ord))
- }
- fn synthetic_image(imports: Vec<ImportModule>, delay_imports: Vec<ImportModule>) -> ImageInfo {
- ImageInfo {
- machine: 0,
- characteristics: 0,
- timestamp: 0,
- subsystem: 0,
- dll_characteristics: 0,
- image_base: 0,
- size_of_image: 0,
- entry_rva: 0,
- stack_reserve: 0,
- stack_commit: 0,
- sections: Vec::new(),
- imports,
- delay_imports,
- exports: Vec::new(),
- tls: None,
- has_relocations: false,
- has_exception_table: false,
- has_load_config: false,
- codeview: None,
- }
- }
- #[test]
- fn deduplicates_imports_ignoring_hint_across_images_and_delay_imports() {
- let resolver = HleResolver::new(HostPolicy::none());
- let mut dlls: BTreeMap<String, DllStats> = BTreeMap::new();
- let mut missing: BTreeMap<(String, String), BTreeSet<PathBuf>> = BTreeMap::new();
- let image_a = synthetic_image(
- vec![ImportModule {
- dll: "XGameRuntime.dll".into(),
- entries: vec![
- named(1, "XGameRuntimeInitialize"),
- named(10, "SyntheticMissingApi"),
- ordinal(42),
- ],
- }],
- vec![ImportModule {
- dll: "XGameRuntime.dll".into(),
- entries: vec![
- named(2, "XGameRuntimeInitialize"),
- named(20, "SyntheticMissingApi"),
- ],
- }],
- );
- let image_b = synthetic_image(
- vec![ImportModule {
- dll: "xgameruntime.dll".into(),
- entries: vec![
- named(99, "XGameRuntimeInitialize"),
- named(200, "SyntheticMissingApi"),
- ordinal(42),
- ],
- }],
- vec![ImportModule {
- dll: "XGameRuntime.dll".into(),
- entries: vec![named(300, "SyntheticMissingApi"), ordinal(42)],
- }],
- );
- tally_image(
- Path::new("image_a.exe"),
- &image_a,
- &resolver,
- &mut dlls,
- &mut missing,
- );
- tally_image(
- Path::new("image_b.dll"),
- &image_b,
- &resolver,
- &mut dlls,
- &mut missing,
- );
- assert_eq!(dlls.len(), 1);
- let stats = &dlls["xgameruntime.dll"];
- assert_eq!(stats.functions.len(), 3);
- assert_eq!(stats.hle, 1);
- assert_eq!(stats.host, 0);
- assert_eq!(stats.missing, 2);
- assert_eq!(stats.images.len(), 2);
- assert_eq!(
- dlls.values().map(|s| s.missing).sum::<usize>(),
- missing.len()
- );
- assert_eq!(
- missing[&("xgameruntime.dll".into(), "SyntheticMissingApi".into())].len(),
- 2
- );
- assert_eq!(missing[&("xgameruntime.dll".into(), "#42".into())].len(), 2);
- }
- #[test]
- fn counts_distinct_symbols_and_dlls_separately() {
- let resolver = HleResolver::new(HostPolicy::none());
- let mut dlls: BTreeMap<String, DllStats> = BTreeMap::new();
- let mut missing: BTreeMap<(String, String), BTreeSet<PathBuf>> = BTreeMap::new();
- let image = synthetic_image(
- vec![
- ImportModule {
- dll: "XGameRuntime.dll".into(),
- entries: vec![
- named(0, "XGameRuntimeInitialize"),
- named(0, "SyntheticMissingA"),
- named(0, "SyntheticMissingB"),
- ordinal(7),
- ordinal(8),
- ],
- },
- ImportModule {
- dll: "SyntheticExtra.dll".into(),
- entries: vec![named(0, "SyntheticMissingA"), ordinal(7)],
- },
- ],
- Vec::new(),
- );
- tally_image(
- Path::new("single.exe"),
- &image,
- &resolver,
- &mut dlls,
- &mut missing,
- );
- assert_eq!(dlls.len(), 2);
- let xgr = &dlls["xgameruntime.dll"];
- assert_eq!(xgr.functions.len(), 5);
- assert_eq!(xgr.hle, 1);
- assert_eq!(xgr.missing, 4);
- assert_eq!(xgr.images.len(), 1);
- let extra = &dlls["syntheticextra.dll"];
- assert_eq!(extra.functions.len(), 2);
- assert_eq!(extra.hle, 0);
- assert_eq!(extra.missing, 2);
- assert_eq!(extra.images.len(), 1);
- assert_eq!(
- dlls.values().map(|s| s.missing).sum::<usize>(),
- missing.len()
- );
- }
- }
|