census.rs 10 KB

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