registry.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. //! The table of everything we implement.
  2. use std::sync::LazyLock;
  3. use crate::modules;
  4. /// One function we implement, under the name the title imports (`#n` for an
  5. /// ordinal).
  6. #[derive(Debug, Clone, Copy)]
  7. pub struct HleExport {
  8. pub name: &'static str,
  9. pub address: usize,
  10. }
  11. /// A group of implementations and the DLL names they answer for.
  12. #[derive(Debug)]
  13. pub struct HleModule {
  14. /// Human-readable name, e.g. "kernel".
  15. pub name: &'static str,
  16. /// Lower-case DLL names served. A trailing `*` matches a prefix, which
  17. /// covers versioned API sets (`api-ms-win-core-libraryloader-l1-2-0.dll`).
  18. pub dlls: &'static [&'static str],
  19. pub exports: Vec<HleExport>,
  20. }
  21. impl HleModule {
  22. pub fn serves(&self, dll: &str) -> bool {
  23. let dll = dll.to_ascii_lowercase();
  24. self.dlls
  25. .iter()
  26. .any(|pattern| match pattern.strip_suffix('*') {
  27. Some(prefix) => dll.starts_with(prefix),
  28. None => dll == *pattern,
  29. })
  30. }
  31. }
  32. /// Declares an export whose Rust name equals the imported name.
  33. #[macro_export]
  34. macro_rules! hle_export {
  35. ($f:ident) => {
  36. $crate::HleExport {
  37. name: stringify!($f),
  38. address: $f as *const () as usize,
  39. }
  40. };
  41. }
  42. static REGISTRY: LazyLock<Vec<HleModule>> = LazyLock::new(modules::all);
  43. /// All modules we implement.
  44. pub fn registry() -> &'static [HleModule] {
  45. &REGISTRY
  46. }
  47. pub(crate) fn lookup(dll: &str, name: &str) -> Option<usize> {
  48. registry()
  49. .iter()
  50. .filter(|m| m.serves(dll))
  51. .flat_map(|m| m.exports.iter())
  52. .find(|e| e.name == name)
  53. .map(|e| e.address)
  54. }
  55. #[cfg(test)]
  56. mod tests {
  57. use super::*;
  58. #[test]
  59. fn export_names_are_unique_per_dll_pattern() {
  60. for module in registry() {
  61. let mut names: Vec<_> = module.exports.iter().map(|e| e.name).collect();
  62. names.sort_unstable();
  63. let before = names.len();
  64. names.dedup();
  65. assert_eq!(
  66. before,
  67. names.len(),
  68. "duplicate export in module {}",
  69. module.name
  70. );
  71. }
  72. }
  73. #[test]
  74. fn api_set_prefix_matching() {
  75. let m = HleModule {
  76. name: "t",
  77. dlls: &["api-ms-win-core-libraryloader-*"],
  78. exports: vec![],
  79. };
  80. assert!(m.serves("API-MS-WIN-CORE-LIBRARYLOADER-L1-2-0.dll"));
  81. assert!(!m.serves("api-ms-win-core-file-l1-1-0.dll"));
  82. }
  83. }