census.rs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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(Default)]
  10. struct DllStats {
  11. functions: BTreeSet<ImportSymbol>,
  12. hle: usize,
  13. host: usize,
  14. missing: usize,
  15. images: BTreeSet<PathBuf>,
  16. }
  17. pub fn run(paths: Vec<PathBuf>, strict: bool, list_missing: bool) -> Result<()> {
  18. let paths = crate::default_paths(paths)?;
  19. let resolver = HleResolver::new(if strict {
  20. HostPolicy::none()
  21. } else {
  22. HostPolicy::default()
  23. });
  24. let mut images = 0usize;
  25. let mut failed = Vec::new();
  26. let mut dlls: BTreeMap<String, DllStats> = BTreeMap::new();
  27. let mut missing: BTreeMap<(String, String), BTreeSet<PathBuf>> = BTreeMap::new();
  28. for root in &paths {
  29. for entry in walkdir::WalkDir::new(root) {
  30. let entry = match entry {
  31. Ok(entry) => entry,
  32. Err(error) if error.depth() == 0 => {
  33. return Err(error).context("cannot scan census input");
  34. }
  35. Err(error) => {
  36. failed.push(error.to_string());
  37. continue;
  38. }
  39. };
  40. let path = entry.path();
  41. if !entry.file_type().is_file() || !looks_like_pe(path) {
  42. continue;
  43. }
  44. let info = match std::fs::read(path)
  45. .map_err(anyhow::Error::from)
  46. .and_then(|d| ImageInfo::parse(&d).map_err(anyhow::Error::from))
  47. {
  48. Ok(info) => info,
  49. Err(e) => {
  50. failed.push(format!("{}: {e}", path.display()));
  51. continue;
  52. }
  53. };
  54. images += 1;
  55. for module in info.imports.iter().chain(&info.delay_imports) {
  56. let key = module.dll.to_ascii_lowercase();
  57. let stats = dlls.entry(key.clone()).or_default();
  58. stats.images.insert(path.to_path_buf());
  59. for e in &module.entries {
  60. let class = resolver.classify(&module.dll, &e.symbol);
  61. if class.is_none() {
  62. missing
  63. .entry((key.clone(), e.symbol.to_string()))
  64. .or_default()
  65. .insert(path.to_path_buf());
  66. }
  67. // Count each dll!function once across all images.
  68. if stats.functions.insert(e.symbol.clone()) {
  69. match class {
  70. Some(Provenance::Hle) => stats.hle += 1,
  71. Some(Provenance::Host) => stats.host += 1,
  72. Some(Provenance::Title) => unreachable!("census maps no title DLLs"),
  73. None => stats.missing += 1,
  74. }
  75. }
  76. }
  77. }
  78. }
  79. }
  80. println!("{images} images scanned, {} unreadable", failed.len());
  81. for error in &failed {
  82. println!(" skipped {error}");
  83. }
  84. println!(
  85. "\n{:<56} {:>6} {:>6} {:>6} {:>8} {:>7}",
  86. "dll", "funcs", "hle", "host", "missing", "images"
  87. );
  88. let (mut f, mut h, mut o, mut m) = (0, 0, 0, 0);
  89. for (dll, s) in &dlls {
  90. println!(
  91. "{dll:<56} {:>6} {:>6} {:>6} {:>8} {:>7}",
  92. s.functions.len(),
  93. s.hle,
  94. s.host,
  95. s.missing,
  96. s.images.len()
  97. );
  98. f += s.functions.len();
  99. h += s.hle;
  100. o += s.host;
  101. m += s.missing;
  102. }
  103. println!("{:<56} {f:>6} {h:>6} {o:>6} {m:>8}", "TOTAL");
  104. if list_missing {
  105. let mut rows: Vec<_> = missing.into_iter().collect();
  106. rows.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then_with(|| a.0.cmp(&b.0)));
  107. println!("\nmissing (by number of images using it)");
  108. for ((dll, sym), users) in rows {
  109. println!(" {:>4} {dll}!{sym}", users.len());
  110. }
  111. }
  112. Ok(())
  113. }
  114. /// Cheap pre-filter: an `MZ` header, regardless of extension (console
  115. /// packages do not always use .exe/.dll).
  116. fn looks_like_pe(path: &Path) -> bool {
  117. let mut magic = [0u8; 2];
  118. std::fs::File::open(path)
  119. .and_then(|mut f| f.read_exact(&mut magic))
  120. .is_ok()
  121. && &magic == b"MZ"
  122. }