census.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. //! Which imports do titles need, and which do we cover?
  2. use std::collections::{BTreeMap, BTreeSet};
  3. use std::io::Read;
  4. use std::path::{Path, PathBuf};
  5. use anyhow::{Context, Result};
  6. use victory_hle::{HleResolver, HostPolicy};
  7. use victory_loader::Provenance;
  8. use victory_pe::{ImageInfo, ImportSymbol};
  9. #[derive(PartialEq, Eq, PartialOrd, Ord)]
  10. enum FunctionKey {
  11. Name(String),
  12. Ordinal(u16),
  13. }
  14. impl From<&ImportSymbol> for FunctionKey {
  15. fn from(symbol: &ImportSymbol) -> Self {
  16. match symbol {
  17. ImportSymbol::Name { name, .. } => Self::Name(name.clone()),
  18. ImportSymbol::Ordinal(ordinal) => Self::Ordinal(*ordinal),
  19. }
  20. }
  21. }
  22. #[derive(Default)]
  23. struct DllStats {
  24. functions: BTreeSet<FunctionKey>,
  25. hle: usize,
  26. host: usize,
  27. missing: usize,
  28. images: BTreeSet<PathBuf>,
  29. }
  30. pub fn run(paths: Vec<PathBuf>, strict: bool, list_missing: bool) -> Result<()> {
  31. let paths = crate::default_paths(paths)?;
  32. let resolver = HleResolver::new(if strict {
  33. HostPolicy::none()
  34. } else {
  35. HostPolicy::default()
  36. });
  37. let mut images = 0usize;
  38. let mut seen = BTreeSet::new();
  39. let mut failed = Vec::new();
  40. let mut dlls: BTreeMap<String, DllStats> = BTreeMap::new();
  41. let mut missing: BTreeMap<(String, String), BTreeSet<PathBuf>> = BTreeMap::new();
  42. for root in &paths {
  43. for entry in walkdir::WalkDir::new(root) {
  44. let entry = match entry {
  45. Ok(entry) => entry,
  46. Err(error) if error.depth() == 0 => {
  47. return Err(error).context("cannot scan census input");
  48. }
  49. Err(error) => {
  50. failed.push(error.to_string());
  51. continue;
  52. }
  53. };
  54. let path = entry.path();
  55. if !entry.file_type().is_file() || !looks_like_pe(path) {
  56. continue;
  57. }
  58. // Use the resolved path for deduplication and keep the original for output.
  59. let identity = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
  60. if !seen.insert(identity) {
  61. continue;
  62. }
  63. let info = match std::fs::read(path)
  64. .map_err(anyhow::Error::from)
  65. .and_then(|d| ImageInfo::parse(&d).map_err(anyhow::Error::from))
  66. {
  67. Ok(info) => info,
  68. Err(e) => {
  69. failed.push(format!("{}: {e}", path.display()));
  70. continue;
  71. }
  72. };
  73. images += 1;
  74. tally_image(path, &info, &resolver, &mut dlls, &mut missing);
  75. }
  76. }
  77. println!("{images} images scanned, {} unreadable", failed.len());
  78. for error in &failed {
  79. println!(" skipped {error}");
  80. }
  81. println!(
  82. "\n{:<56} {:>6} {:>6} {:>6} {:>8} {:>7}",
  83. "dll", "funcs", "hle", "host", "missing", "images"
  84. );
  85. let (mut f, mut h, mut o, mut m) = (0, 0, 0, 0);
  86. for (dll, s) in &dlls {
  87. println!(
  88. "{dll:<56} {:>6} {:>6} {:>6} {:>8} {:>7}",
  89. s.functions.len(),
  90. s.hle,
  91. s.host,
  92. s.missing,
  93. s.images.len()
  94. );
  95. f += s.functions.len();
  96. h += s.hle;
  97. o += s.host;
  98. m += s.missing;
  99. }
  100. println!("{:<56} {f:>6} {h:>6} {o:>6} {m:>8}", "TOTAL");
  101. if list_missing {
  102. let mut rows: Vec<_> = missing.into_iter().collect();
  103. rows.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then_with(|| a.0.cmp(&b.0)));
  104. println!("\nmissing (by number of images using it)");
  105. for ((dll, sym), users) in rows {
  106. println!(" {:>4} {dll}!{sym}", users.len());
  107. }
  108. }
  109. Ok(())
  110. }
  111. /// Cheap pre-filter: an `MZ` header, regardless of extension (console
  112. /// packages do not always use .exe/.dll).
  113. fn looks_like_pe(path: &Path) -> bool {
  114. let mut magic = [0u8; 2];
  115. std::fs::File::open(path)
  116. .and_then(|mut f| f.read_exact(&mut magic))
  117. .is_ok()
  118. && &magic == b"MZ"
  119. }
  120. fn tally_image(
  121. path: &Path,
  122. info: &ImageInfo,
  123. resolver: &HleResolver,
  124. dlls: &mut BTreeMap<String, DllStats>,
  125. missing: &mut BTreeMap<(String, String), BTreeSet<PathBuf>>,
  126. ) {
  127. for module in info.imports.iter().chain(&info.delay_imports) {
  128. let key = module.dll.to_ascii_lowercase();
  129. let stats = dlls.entry(key.clone()).or_default();
  130. stats.images.insert(path.to_path_buf());
  131. for e in &module.entries {
  132. let class = resolver.classify(&module.dll, &e.symbol);
  133. if class.is_none() {
  134. missing
  135. .entry((key.clone(), e.symbol.to_string()))
  136. .or_default()
  137. .insert(path.to_path_buf());
  138. }
  139. // Count each dll!function once across all images.
  140. if stats.functions.insert(FunctionKey::from(&e.symbol)) {
  141. match class {
  142. Some(Provenance::Hle) => stats.hle += 1,
  143. Some(Provenance::Host) => stats.host += 1,
  144. Some(Provenance::Title) => unreachable!("census maps no title DLLs"),
  145. None => stats.missing += 1,
  146. }
  147. }
  148. }
  149. }
  150. }
  151. #[cfg(test)]
  152. mod tests {
  153. use super::*;
  154. use victory_pe::{ImportEntry, ImportModule};
  155. fn entry(symbol: ImportSymbol) -> ImportEntry {
  156. ImportEntry {
  157. symbol,
  158. iat_slot_rva: 0,
  159. }
  160. }
  161. fn named(hint: u16, name: &str) -> ImportEntry {
  162. entry(ImportSymbol::Name {
  163. hint,
  164. name: name.into(),
  165. })
  166. }
  167. fn ordinal(ord: u16) -> ImportEntry {
  168. entry(ImportSymbol::Ordinal(ord))
  169. }
  170. fn synthetic_image(imports: Vec<ImportModule>, delay_imports: Vec<ImportModule>) -> ImageInfo {
  171. ImageInfo {
  172. machine: 0,
  173. characteristics: 0,
  174. timestamp: 0,
  175. subsystem: 0,
  176. dll_characteristics: 0,
  177. image_base: 0,
  178. size_of_image: 0,
  179. entry_rva: 0,
  180. stack_reserve: 0,
  181. stack_commit: 0,
  182. sections: Vec::new(),
  183. imports,
  184. delay_imports,
  185. exports: Vec::new(),
  186. tls: None,
  187. has_relocations: false,
  188. has_exception_table: false,
  189. has_load_config: false,
  190. codeview: None,
  191. }
  192. }
  193. #[test]
  194. fn deduplicates_imports_ignoring_hint_across_images_and_delay_imports() {
  195. let resolver = HleResolver::new(HostPolicy::none());
  196. let mut dlls: BTreeMap<String, DllStats> = BTreeMap::new();
  197. let mut missing: BTreeMap<(String, String), BTreeSet<PathBuf>> = BTreeMap::new();
  198. let image_a = synthetic_image(
  199. vec![ImportModule {
  200. dll: "XGameRuntime.dll".into(),
  201. entries: vec![
  202. named(1, "XGameRuntimeInitialize"),
  203. named(10, "SyntheticMissingApi"),
  204. ordinal(42),
  205. ],
  206. }],
  207. vec![ImportModule {
  208. dll: "XGameRuntime.dll".into(),
  209. entries: vec![
  210. named(2, "XGameRuntimeInitialize"),
  211. named(20, "SyntheticMissingApi"),
  212. ],
  213. }],
  214. );
  215. let image_b = synthetic_image(
  216. vec![ImportModule {
  217. dll: "xgameruntime.dll".into(),
  218. entries: vec![
  219. named(99, "XGameRuntimeInitialize"),
  220. named(200, "SyntheticMissingApi"),
  221. ordinal(42),
  222. ],
  223. }],
  224. vec![ImportModule {
  225. dll: "XGameRuntime.dll".into(),
  226. entries: vec![named(300, "SyntheticMissingApi"), ordinal(42)],
  227. }],
  228. );
  229. tally_image(
  230. Path::new("image_a.exe"),
  231. &image_a,
  232. &resolver,
  233. &mut dlls,
  234. &mut missing,
  235. );
  236. tally_image(
  237. Path::new("image_b.dll"),
  238. &image_b,
  239. &resolver,
  240. &mut dlls,
  241. &mut missing,
  242. );
  243. assert_eq!(dlls.len(), 1);
  244. let stats = &dlls["xgameruntime.dll"];
  245. assert_eq!(stats.functions.len(), 3);
  246. assert_eq!(stats.hle, 1);
  247. assert_eq!(stats.host, 0);
  248. assert_eq!(stats.missing, 2);
  249. assert_eq!(stats.images.len(), 2);
  250. assert_eq!(
  251. dlls.values().map(|s| s.missing).sum::<usize>(),
  252. missing.len()
  253. );
  254. assert_eq!(
  255. missing[&("xgameruntime.dll".into(), "SyntheticMissingApi".into())].len(),
  256. 2
  257. );
  258. assert_eq!(missing[&("xgameruntime.dll".into(), "#42".into())].len(), 2);
  259. }
  260. #[test]
  261. fn counts_distinct_symbols_and_dlls_separately() {
  262. let resolver = HleResolver::new(HostPolicy::none());
  263. let mut dlls: BTreeMap<String, DllStats> = BTreeMap::new();
  264. let mut missing: BTreeMap<(String, String), BTreeSet<PathBuf>> = BTreeMap::new();
  265. let image = synthetic_image(
  266. vec![
  267. ImportModule {
  268. dll: "XGameRuntime.dll".into(),
  269. entries: vec![
  270. named(0, "XGameRuntimeInitialize"),
  271. named(0, "SyntheticMissingA"),
  272. named(0, "SyntheticMissingB"),
  273. ordinal(7),
  274. ordinal(8),
  275. ],
  276. },
  277. ImportModule {
  278. dll: "SyntheticExtra.dll".into(),
  279. entries: vec![named(0, "SyntheticMissingA"), ordinal(7)],
  280. },
  281. ],
  282. Vec::new(),
  283. );
  284. tally_image(
  285. Path::new("single.exe"),
  286. &image,
  287. &resolver,
  288. &mut dlls,
  289. &mut missing,
  290. );
  291. assert_eq!(dlls.len(), 2);
  292. let xgr = &dlls["xgameruntime.dll"];
  293. assert_eq!(xgr.functions.len(), 5);
  294. assert_eq!(xgr.hle, 1);
  295. assert_eq!(xgr.missing, 4);
  296. assert_eq!(xgr.images.len(), 1);
  297. let extra = &dlls["syntheticextra.dll"];
  298. assert_eq!(extra.functions.len(), 2);
  299. assert_eq!(extra.hle, 0);
  300. assert_eq!(extra.missing, 2);
  301. assert_eq!(extra.images.len(), 1);
  302. assert_eq!(
  303. dlls.values().map(|s| s.missing).sum::<usize>(),
  304. missing.len()
  305. );
  306. }
  307. }