From 85a9af2f1e5fe1f580f65ba6d9bbb9e70f226e3e Mon Sep 17 00:00:00 2001 From: PrivacyOnion Date: Wed, 25 Nov 2026 18:15:46 +0100 Subject: [PATCH] app, docs: classify census imports as the loader binds --- README.md | 19 +- apps/xtp/src/census.rs | 489 ++++++++++++++++------- apps/xtp/src/main.rs | 9 +- apps/xtp/src/run.rs | 3 +- docs/architecture.md | 6 +- docs/contributing-without-a-gaming-pc.md | 4 +- 6 files changed, 372 insertions(+), 158 deletions(-) diff --git a/README.md b/README.md index f4e40500..6b4ecde1 100644 --- a/README.md +++ b/README.md @@ -142,10 +142,21 @@ fields `machine`, `image_base` and `entry_rva`, numeric fields `subsystem` and objects (`delay` is a boolean; `resolution` is `"hle"`, `"host"`, `"missing"`, with `"title"` reserved because static `inspect` does not map title-shipped DLLs, so those report as `"missing"`). `--json` ignores `--imports` and -`--exports`. `xtp census --json` emits `"format": "xtp-census 1"` with numeric -`images`, `unreadable`, `totals` (`{functions, hle, host, missing}`), a `dlls` -array (`{dll, functions, hle, host, missing, images}`), and always includes the -`missing` array (`{dll, symbol, images}`). The `format` version number +`--exports`. + +`xtp census` classifies imports as HLE, host, title DLL, table-stubbed, or +missing. Each folder is scanned independently, without subfolders. A file +is scanned as one image with no title DLLs available. With no paths, census +uses the configured game and test-title folders. When a pair has different +outcomes across inputs, the totals count it once under the last applicable +class in that order. `--strict` disables host pass-through. + +`xtp census --json` emits `"format": "xtp-census 1"` with numeric `images` and +`unreadable` fields, a `totals` object +(`{functions, hle, host, title, stubbed, missing}`), a `dlls` array +(`{dll, functions, hle, host, title, stubbed, missing, images}`), and +`missing` and `stubbed` arrays (each with `{dll, symbol, images}` rows). +Each array counts the images in its class. The `format` version number increments on any breaking schema change. The title sees an Xbox Series S unless `--console series-x` or diff --git a/apps/xtp/src/census.rs b/apps/xtp/src/census.rs index 8c9b2190..189d744d 100644 --- a/apps/xtp/src/census.rs +++ b/apps/xtp/src/census.rs @@ -1,212 +1,413 @@ -//! Which imports do titles need, and which do we cover? +//! Which imports do titles need, and where does the loader bind them? use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write; -use std::io::Read; use std::path::{Path, PathBuf}; use anyhow::Result; use xtp_hle::{HleResolver, HostPolicy}; -use xtp_loader::Provenance; -use xtp_pe::{ImageInfo, ImportSymbol}; +use xtp_loader::census::{Class, Counts}; +use xtp_loader::{Census, StubDb}; +use xtp_pe::ImageInfo; use crate::survey::quote; #[derive(Default)] struct DllStats { - functions: BTreeSet, - hle: usize, - host: usize, - missing: usize, + functions: BTreeMap, images: BTreeSet, } -pub fn run(paths: Vec, strict: bool, list_missing: bool, json: bool) -> Result<()> { - let paths = crate::default_paths(paths)?; - let resolver = HleResolver::new(if strict { - HostPolicy::none() - } else { - HostPolicy::default() - }); +type ImportList = BTreeMap<(String, String), BTreeSet>; + +#[derive(Default)] +struct Report { + images: usize, + unreadable: Vec<(PathBuf, String)>, + dlls: BTreeMap, + missing: ImportList, + stubbed: ImportList, +} - let mut images = 0usize; - let mut failed = Vec::new(); - let mut dlls: BTreeMap = BTreeMap::new(); - let mut missing: BTreeMap<(String, String), BTreeSet> = 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; +impl Report { + fn add(&mut self, dir: &Path, census: Census) { + self.images += census.images.len(); + self.unreadable.extend( + census + .unreadable + .into_iter() + .map(|(image, error)| (dir.join(image), error)), + ); + for import in census.imports { + let image = dir.join(import.image); + let dll = import.dll.to_ascii_lowercase(); + let stats = self.dlls.entry(dll.clone()).or_default(); + let class = stats + .functions + .entry(import.symbol.clone()) + .or_insert(import.class); + if binding_order(import.class) > binding_order(*class) { + *class = import.class; } - 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; - } + let list = match import.class { + Class::Missing => Some(&mut self.missing), + Class::Stubbed(_) => Some(&mut self.stubbed), + _ => None, }; - 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, - } - } - } + if let Some(list) = list { + list.entry((dll, import.symbol)) + .or_default() + .insert(image.clone()); } + stats.images.insert(image); } } +} - let (mut f, mut h, mut o, mut m) = (0, 0, 0, 0); - for s in dlls.values() { - f += s.functions.len(); - h += s.hle; - o += s.host; - m += s.missing; +/// Count a pair once, under its last binding outcome across the inputs. +fn binding_order(class: Class) -> u8 { + match class { + Class::Hle => 0, + Class::Host => 1, + Class::Title => 2, + Class::Stubbed(_) => 3, + Class::Missing => 4, } +} +fn counts<'a>(classes: impl Iterator) -> Counts { + let mut counts = Counts::default(); + for class in classes { + match class { + Class::Hle => counts.hle += 1, + Class::Host => counts.host += 1, + Class::Title => counts.title += 1, + Class::Stubbed(_) => counts.stubbed += 1, + Class::Missing => counts.missing += 1, + } + } + counts +} + +pub fn run(paths: Vec, strict: bool, list_missing: bool, json: bool) -> Result<()> { + let report = scan(crate::default_paths(paths)?, strict); if json { - print!( - "{}", - to_json(images, failed.len(), (f, h, o, m), &dlls, &missing) - ); - return Ok(()); + print!("{}", to_json(&report)); + } else { + print!("{}", to_text(&report, list_missing)); } + Ok(()) +} - println!("{images} images scanned, {} unreadable", failed.len()); - for (p, e) in &failed { - println!(" skipped {}: {e}", p.display()); +fn scan(paths: Vec, strict: bool) -> Report { + let resolver = HleResolver::new(if strict { + HostPolicy::none() + } else { + HostPolicy::default() + }); + let wanted = |dll: &str| crate::run::title_dll(&resolver.host, dll); + let stubs = StubDb::builtin(); + let mut report = Report::default(); + for path in paths { + let (dir, census) = if path.is_dir() { + ( + path.as_path(), + Census::of_folder(&path, &resolver, &wanted, stubs), + ) + } else { + let dir = path.parent().unwrap_or(Path::new("")); + (dir, of_file(&path, &resolver, stubs)) + }; + match census { + Ok(census) => report.add(dir, census), + Err(error) => report.unreadable.push((path, error.to_string())), + } } - println!( - "\n{:<56} {:>6} {:>6} {:>6} {:>8} {:>7}", - "dll", "funcs", "hle", "host", "missing", "images" + report +} + +fn of_file(path: &Path, resolver: &HleResolver, stubs: &StubDb) -> Result { + let info = ImageInfo::parse(&std::fs::read(path)?)?; + let name = path.file_name().unwrap_or_default().to_string_lossy(); + Ok(Census::of_images( + &[(name.into_owned(), info)], + resolver, + &|_| false, + stubs, + )) +} + +fn to_text(report: &Report, list_missing: bool) -> String { + let mut out = String::new(); + let _ = writeln!( + out, + "{} images scanned, {} unreadable", + report.images, + report.unreadable.len() ); - 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() - ); + for (path, error) in &report.unreadable { + let _ = writeln!(out, " skipped {}: {error}", path.display()); } - println!("{:<56} {f:>6} {h:>6} {o:>6} {m:>8}", "TOTAL"); + let _ = writeln!( + out, + "\n{:<56} {:>6} {:>6} {:>6} {:>6} {:>8} {:>8} {:>7}", + "dll", "funcs", "hle", "host", "title", "stubbed", "missing", "images" + ); + for (dll, stats) in &report.dlls { + text_counts(&mut out, dll, counts(stats.functions.values())); + let _ = writeln!(out, " {:>7}", stats.images.len()); + } + let totals = counts( + report + .dlls + .values() + .flat_map(|stats| stats.functions.values()), + ); + text_counts(&mut out, "TOTAL", totals); + out.push('\n'); 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()); + for (label, list) in [("missing", &report.missing), ("stubbed", &report.stubbed)] { + let _ = writeln!(out, "\n{label} (by number of images using it)"); + for ((dll, sym), users) in sorted_rows(list) { + let _ = writeln!(out, " {:>4} {dll}!{sym}", users.len()); + } } } - Ok(()) + out } -/// Stable JSON census report: totals, per-DLL counts, and missing pairs. -fn to_json( - images: usize, - unreadable: usize, - totals: (usize, usize, usize, usize), - dlls: &BTreeMap, - missing: &BTreeMap<(String, String), BTreeSet>, -) -> String { - let (functions, hle, host, missing_total) = totals; - let mut o = String::new(); - let _ = writeln!(o, "{{"); - let _ = writeln!(o, " \"format\": \"xtp-census 1\","); - let _ = writeln!(o, " \"images\": {images},"); - let _ = writeln!(o, " \"unreadable\": {unreadable},"); - let _ = writeln!( - o, - " \"totals\": {{\"functions\": {functions}, \"hle\": {hle}, \"host\": {host}, \"missing\": {missing_total}}}," +fn text_counts(out: &mut String, dll: &str, c: Counts) { + let _ = write!( + out, + "{dll:<56} {:>6} {:>6} {:>6} {:>6} {:>8} {:>8}", + c.total(), + c.hle, + c.host, + c.title, + c.stubbed, + c.missing ); +} - if dlls.is_empty() { - let _ = writeln!(o, " \"dlls\": [],"); +fn sorted_rows(list: &ImportList) -> Vec<(&(String, String), &BTreeSet)> { + let mut rows: Vec<_> = list.iter().collect(); + rows.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then_with(|| a.0.cmp(b.0))); + rows +} + +/// Stable JSON census report: totals, per-DLL counts, and unresolved pairs. +fn to_json(report: &Report) -> String { + let mut out = String::new(); + let _ = writeln!(out, "{{"); + let _ = writeln!(out, " \"format\": \"xtp-census 1\","); + let _ = writeln!(out, " \"images\": {},", report.images); + let _ = writeln!(out, " \"unreadable\": {},", report.unreadable.len()); + let totals = counts( + report + .dlls + .values() + .flat_map(|stats| stats.functions.values()), + ); + let _ = writeln!(out, " \"totals\": {{{}}},", json_counts(totals)); + if report.dlls.is_empty() { + let _ = writeln!(out, " \"dlls\": [],"); } else { - let _ = writeln!(o, " \"dlls\": ["); - for (i, (dll, s)) in dlls.iter().enumerate() { - let comma = if i + 1 < dlls.len() { "," } else { "" }; + let _ = writeln!(out, " \"dlls\": ["); + for (i, (dll, stats)) in report.dlls.iter().enumerate() { + let comma = if i + 1 < report.dlls.len() { "," } else { "" }; let _ = writeln!( - o, - " {{\"dll\": {}, \"functions\": {}, \"hle\": {}, \"host\": {}, \"missing\": {}, \"images\": {}}}{comma}", + out, + " {{\"dll\": {}, {}, \"images\": {}}}{comma}", quote(dll), - s.functions.len(), - s.hle, - s.host, - s.missing, - s.images.len(), + json_counts(counts(stats.functions.values())), + stats.images.len(), ); } - let _ = writeln!(o, " ],"); + let _ = writeln!(out, " ],"); } + json_list(&mut out, "missing", &report.missing, ","); + json_list(&mut out, "stubbed", &report.stubbed, ""); + let _ = writeln!(out, "}}"); + out +} - let mut rows: Vec<_> = missing.iter().collect(); - rows.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then_with(|| a.0.cmp(b.0))); +fn json_counts(c: Counts) -> String { + format!( + "\"functions\": {}, \"hle\": {}, \"host\": {}, \"title\": {}, \"stubbed\": {}, \"missing\": {}", + c.total(), + c.hle, + c.host, + c.title, + c.stubbed, + c.missing + ) +} + +fn json_list(out: &mut String, label: &str, list: &ImportList, comma: &str) { + let rows = sorted_rows(list); if rows.is_empty() { - let _ = writeln!(o, " \"missing\": []"); + let _ = writeln!(out, " \"{label}\": []{comma}"); } else { - let _ = writeln!(o, " \"missing\": ["); + let _ = writeln!(out, " \"{label}\": ["); for (i, ((dll, sym), users)) in rows.iter().enumerate() { - let comma = if i + 1 < rows.len() { "," } else { "" }; + let row_comma = if i + 1 < rows.len() { "," } else { "" }; let _ = writeln!( - o, - " {{\"dll\": {}, \"symbol\": {}, \"images\": {}}}{comma}", + out, + " {{\"dll\": {}, \"symbol\": {}, \"images\": {}}}{row_comma}", quote(dll), quote(sym), users.len(), ); } - let _ = writeln!(o, " ]"); + let _ = writeln!(out, " ]{comma}"); } - let _ = writeln!(o, "}}"); - o -} - -/// 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" } #[cfg(test)] mod tests { use super::*; + use xtp_pe::{ExportInfo, ImportEntry, ImportModule, ImportSymbol}; + + fn name(name: &str) -> ImportSymbol { + ImportSymbol::Name { + hint: 0, + name: name.into(), + } + } + + fn image(dll: bool, imports: Vec, exports: &[&str]) -> ImageInfo { + ImageInfo { + machine: 0x8664, + characteristics: if dll { 0x2000 } else { 0 }, + timestamp: 0, + subsystem: 0, + dll_characteristics: 0, + image_base: 0x1_4000_0000, + size_of_image: 0x10000, + entry_rva: 0, + stack_reserve: 0, + stack_commit: 0, + sections: Vec::new(), + imports, + delay_imports: Vec::new(), + exports: exports + .iter() + .enumerate() + .map(|(i, name)| ExportInfo { + name: Some((*name).into()), + ordinal: 1 + i as u16, + rva: Some(0x2000), + forward: None, + }) + .collect(), + tls: None, + has_relocations: true, + has_exception_table: true, + has_load_config: false, + codeview: None, + } + } + + fn imports(dll: &str, symbols: impl IntoIterator) -> ImportModule { + ImportModule { + dll: dll.into(), + entries: symbols + .into_iter() + .enumerate() + .map(|(i, symbol)| ImportEntry { + symbol, + iat_slot_rva: 0x1000 + 8 * i as u32, + }) + .collect(), + } + } + + #[test] + fn reports_the_loader_classes() { + let exe = image( + false, + vec![ + imports("Engine.dll", [name("Start"), name("Gone")]), + imports( + "oleaut32.dll", + [ImportSymbol::Ordinal(4), ImportSymbol::Ordinal(6)], + ), + imports("xgameruntime.dll", [name("XGameRuntimeInitialize")]), + ], + &[], + ); + let images = [ + ("sample.exe".into(), exe), + ("engine.dll".into(), image(true, vec![], &["Start"])), + ( + "oleaut32.dll".into(), + image(true, vec![], &["SysAllocStringLen"]), + ), + ]; + let resolver = HleResolver::new(HostPolicy::none()); + let wanted = |dll: &str| crate::run::title_dll(&resolver.host, dll); + let stubs = StubDb::builtin(); + let mut report = Report::default(); + report.add( + Path::new("first"), + Census::of_images(&images, &resolver, &wanted, stubs), + ); + + let json = to_json(&report); + assert!(json.contains( + r#""functions": 5, "hle": 1, "host": 0, "title": 2, "stubbed": 1, "missing": 1"# + )); + assert!(json.contains(r#""dll": "engine.dll", "symbol": "Gone", "images": 1"#)); + let text = to_text(&report, true); + let (_, lists) = text.split_once("\nmissing (").unwrap(); + let (missing, stubbed) = lists.split_once("\nstubbed (").unwrap(); + assert!(missing.contains("engine.dll!Gone")); + assert!(!missing.contains("engine.dll!Start")); + assert!(!missing.contains("oleaut32.dll!")); + assert!(stubbed.contains("oleaut32.dll!#6")); + assert!(!stubbed.contains("oleaut32.dll!#4")); + assert!(!to_text(&report, false).contains("engine.dll!Gone")); + + // A second title with the same image name has no DLL to serve Start. + report.add( + Path::new("second"), + Census::of_images(&images[..1], &resolver, &wanted, stubs), + ); + let engine = &report.dlls["engine.dll"]; + assert_eq!(engine.images.len(), 2); + assert_eq!(counts(engine.functions.values()).missing, 2); + assert_eq!( + report.missing[&("engine.dll".into(), "Gone".into())].len(), + 2 + ); + assert_eq!( + report.missing[&("engine.dll".into(), "Start".into())].len(), + 1 + ); + } + + #[test] + fn scans_only_the_requested_files() { + let dir = tempfile::tempdir().unwrap(); + let subdir = dir.path().join("subdir"); + std::fs::create_dir(&subdir).unwrap(); + let nested = subdir.join("nested.dll"); + let top = dir.path().join("top.dll"); + std::fs::write(&top, b"MZ broken").unwrap(); + std::fs::write(&nested, b"MZ broken").unwrap(); + let report = scan(vec![dir.path().to_owned(), nested.clone()], false); + assert_eq!(report.unreadable.len(), 2); + assert_eq!(report.unreadable[0].0, top); + assert_eq!(report.unreadable[1].0, nested); + } #[test] fn empty_census_json_emits_empty_arrays() { - let out = to_json(0, 0, (0, 0, 0, 0), &BTreeMap::new(), &BTreeMap::new()); + let out = to_json(&Report::default()); assert!(out.contains(r#""format": "xtp-census 1""#)); assert!(out.contains(r#""dlls": []"#)); assert!(out.contains(r#""missing": []"#)); + assert!(out.contains(r#""stubbed": []"#)); } } diff --git a/apps/xtp/src/main.rs b/apps/xtp/src/main.rs index c388b3e3..bec10567 100644 --- a/apps/xtp/src/main.rs +++ b/apps/xtp/src/main.rs @@ -44,15 +44,16 @@ enum Command { #[arg(long)] json: 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. + /// Classify imports as the loader binds them. Census { + /// Each folder is a separate title, scanned without subfolders. + /// A file is one image with no title DLLs available. Defaults to + /// the configured game and test-title folders. paths: Vec, /// Do not count host pass-through as covered. #[arg(long)] strict: bool, - /// List every missing `dll!function`, most used first. + /// List missing and table-stubbed imports separately, most used first. #[arg(long)] missing: bool, /// Emit stable JSON instead of the text table. diff --git a/apps/xtp/src/run.rs b/apps/xtp/src/run.rs index 5ee7560a..08681766 100644 --- a/apps/xtp/src/run.rs +++ b/apps/xtp/src/run.rs @@ -362,8 +362,7 @@ fn register_builder(name: &str, dir: &Path) -> Result<()> { } /// DLLs the host or our runtime provide are never taken from the title. -#[cfg(windows)] -fn title_dll(host: &xtp_hle::HostPolicy, dll: &str) -> bool { +pub(crate) fn title_dll(host: &xtp_hle::HostPolicy, dll: &str) -> bool { !host.allows(dll) && !xtp_hle::registry().iter().any(|m| m.serves(dll)) } diff --git a/docs/architecture.md b/docs/architecture.md index 82bd07c6..24ca58fe 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -112,8 +112,10 @@ names are truncated. Both notifications continue normal exception dispatch. Both observers return before any decoding or allocation once process exit has begun, because terminated threads may still hold allocator or I/O locks. -`xtp census` shows this classification without running anything (it -does not map title DLLs; `xtp run` without `--execute` does). +`xtp census` reads the exports of eligible DLLs in each title folder +without mapping them or running title code. It retries unresolved +ordinals by name and shows which remaining imports have values in the +built-in stub table. ## Shaders diff --git a/docs/contributing-without-a-gaming-pc.md b/docs/contributing-without-a-gaming-pc.md index a73b22c7..82d8b8f2 100644 --- a/docs/contributing-without-a-gaming-pc.md +++ b/docs/contributing-without-a-gaming-pc.md @@ -260,8 +260,8 @@ model for this work: code named by RVA, behaviour in our own words. ```powershell xtp inspect "\<executable>" # blake3: your build's identity -xtp census "<title folder>" --missing # imports XTP does not serve, most used first -xtp census "<title folder>" --missing --strict # host pass-through not counted as covered +xtp census "<title folder>" --missing # missing and table-stubbed imports, listed separately +xtp census "<title folder>" --missing --strict # disable host pass-through ``` - The docs' RVAs are for build 1.0.2.1 (image base `0x140000000`), whose