From 1d0b0d1547d1356e864a2d39ec4579f35c849dc1 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:18:16 -0500 Subject: [PATCH] Generate documented ordinal aliases for typed runtime services Signed-off-by: Adeeb Rahman --- crates/import-gen/src/typed.rs | 58 +++++++++++++++++++++++++++ crates/loader/src/imports.rs | 39 +++++++++++++----- crates/loader/src/services/modules.rs | 14 ++++--- docs/runtime/registry.md | 1 + 4 files changed, 96 insertions(+), 16 deletions(-) diff --git a/crates/import-gen/src/typed.rs b/crates/import-gen/src/typed.rs index 1bcb1cc..f31c603 100644 --- a/crates/import-gen/src/typed.rs +++ b/crates/import-gen/src/typed.rs @@ -20,6 +20,7 @@ pub struct Parameter { pub struct Service { pub library: String, pub symbol: String, + pub ordinal: Option<(u16, String)>, pub parameters: Vec, pub result: String, pub handler: String, @@ -96,6 +97,17 @@ pub fn parse(text: &str, test_source: &str) -> Result, String> { "handler" => service.handler = rest.to_owned(), "status" => service.status = rest.to_owned(), "alias" => service.aliases.push(rest.to_owned()), + "ordinal" => { + let (value, source) = rest + .split_once(' ') + .ok_or_else(|| at("ordinal needs a number and a source"))?; + let value = value + .parse::() + .ok() + .filter(|value| *value != 0) + .ok_or_else(|| at("ordinal must be in 1..=65535"))?; + service.ordinal = Some((value, source.trim().to_owned())); + } "fails" => service.failure = rest.to_owned(), "ref" => service.reference = rest.to_owned(), "test" => service.tests.push(rest.to_owned()), @@ -123,6 +135,7 @@ fn parse_signature(text: &str) -> Result { Ok(Service { library: library.to_owned(), symbol: symbol.trim().to_owned(), + ordinal: None, parameters, result: result.trim().to_owned(), handler: String::new(), @@ -137,6 +150,7 @@ fn parse_signature(text: &str) -> Result { fn validate(services: &[Service], test_source: &str) -> Result<(), String> { // Every key a guest could import, with the service it resolves to. let mut keys: BTreeMap<(String, &str), usize> = BTreeMap::new(); + let mut ordinals = BTreeSet::new(); for (index, service) in services.iter().enumerate() { let name = format!("{}!{}", service.library, service.symbol); let fail = |message: String| Err(format!("{name}: {message}")); @@ -149,6 +163,14 @@ fn validate(services: &[Service], test_source: &str) -> Result<(), String> { if !is_identifier(&service.symbol) { return fail("symbol is not an identifier".into()); } + if let Some((ordinal, source)) = &service.ordinal { + if source.is_empty() { + return fail("ordinal needs a source".into()); + } + if !ordinals.insert((&service.library, ordinal)) { + return fail(format!("ordinal {ordinal} already resolves in this module")); + } + } if !is_identifier(&service.handler) { return fail("missing or invalid handler".into()); } @@ -293,6 +315,13 @@ pub fn generate_rust(services: &[Service]) -> String { "{cpu} let mut context = ServiceContext {{ state: &s, memory }};\n {binding} = handlers::{}(&mut context{names})?;\n {place}\n }});", service.handler ); + if let Some((ordinal, _)) = &service.ordinal { + let _ = writeln!( + out, + " registry.try_ordinal_alias({:?}, {:?}, {ordinal}).expect(\"validated export ordinal\");", + service.library, service.symbol + ); + } } out.push_str(" for service in &SERVICES {\n for alias in service.aliases {\n if let Err(error) = registry.try_alias(alias, service.library, service.symbol) {\n panic!(\"{error}\");\n }\n }\n }\n}\n"); out.replace( @@ -343,6 +372,15 @@ pub fn generate_report(services: &[Service]) -> String { service.failure ); } + for service in services { + if let Some((ordinal, source)) = &service.ordinal { + let _ = writeln!( + out, + "\nOrdinal {ordinal} for `{}!{}` is documented by {source}.", + service.library, service.symbol + ); + } + } out } @@ -379,6 +417,26 @@ mod tests { assert!(generate_report(&services).contains("| Unique handler implementations | 1 |")); } + #[test] + fn ordinal_requires_a_source_and_unique_module_key() { + let first = entry("kernel32.dll F() -> void", "ordinal 42 test catalog"); + let services = parse(&first, TESTS).unwrap(); + assert!( + generate_rust(&services).contains("try_ordinal_alias(\"kernel32.dll\", \"F\", 42)") + ); + assert!(generate_report(&services).contains("documented by test catalog")); + let second = entry("kernel32.dll G() -> void", "ordinal 42 test catalog"); + rejects(&(first + &second), "ordinal 42 already resolves"); + rejects( + &entry("kernel32.dll F() -> void", "ordinal 42"), + "needs a number and a source", + ); + rejects( + &entry("kernel32.dll F() -> void", "ordinal 65536 test catalog"), + "1..=65535", + ); + } + #[test] fn conflicting_keys_are_rejected() { let one = entry("kernel32.dll F() -> void", ""); diff --git a/crates/loader/src/imports.rs b/crates/loader/src/imports.rs index 81b7a93..1295729 100644 --- a/crates/loader/src/imports.rs +++ b/crates/loader/src/imports.rs @@ -406,24 +406,43 @@ impl ImportRegistry { target: &str, symbol: &str, ) -> Result<(), RegistryError> { - let name = ImportName::Name(symbol.to_owned()); - Self::check_key(module, &name)?; - let index = self - .index(target, &name) - .ok_or_else(|| RegistryError::UnknownTarget { - module: target.to_owned(), - symbol: symbol.to_owned(), - })?; + self.alias_key(module, target, symbol, ImportName::Name(symbol.to_owned())) + } + + /// Publish a documented ordinal for a named export in its canonical module. + pub fn try_ordinal_alias( + &mut self, + module: &str, + symbol: &str, + ordinal: u16, + ) -> Result<(), RegistryError> { + self.alias_key(module, module, symbol, ImportName::Ordinal(ordinal)) + } + + fn alias_key( + &mut self, + module: &str, + target: &str, + symbol: &str, + key: ImportName, + ) -> Result<(), RegistryError> { + Self::check_key(module, &key)?; + let index = + self.service_index(target, symbol) + .ok_or_else(|| RegistryError::UnknownTarget { + module: target.to_owned(), + symbol: symbol.to_owned(), + })?; let previous = *self .services - .entry((module.to_ascii_lowercase(), name)) + .entry((module.to_ascii_lowercase(), key.clone())) .or_insert(index); if previous == index { Ok(()) } else { Err(RegistryError::Duplicate { module: module.to_owned(), - symbol: symbol.to_owned(), + symbol: key.to_string(), }) } } diff --git a/crates/loader/src/services/modules.rs b/crates/loader/src/services/modules.rs index 91f973e..1a059fc 100644 --- a/crates/loader/src/services/modules.rs +++ b/crates/loader/src/services/modules.rs @@ -178,14 +178,16 @@ mod tests { #[test] fn guest_module_references_control_dynamic_export_lifetime() { let mut registry = ImportRegistry::new(); + registry.register(UCRT, "SyntheticOrdinalExport", |_, _, _| Ok(42)); registry - .try_register( - UCRT, - ImportName::Ordinal(42), - ServiceStatus::Implemented, - Box::new(|_, _, _| Ok(42)), - ) + .try_ordinal_alias(UCRT, "SyntheticOrdinalExport", 42) .unwrap(); + registry.register(UCRT, "OtherSyntheticExport", |_, _, _| Ok(43)); + assert!( + registry + .try_ordinal_alias(UCRT, "OtherSyntheticExport", 42) + .is_err() + ); register_standard_services( &mut registry, Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))), diff --git a/docs/runtime/registry.md b/docs/runtime/registry.md index 81d3e32..5096a32 100644 --- a/docs/runtime/registry.md +++ b/docs/runtime/registry.md @@ -14,6 +14,7 @@ Guest imports resolve through one lookup, `ImportRegistry::resolve`. Binding, th - Module names compare without case; symbol names are exact. A name spelled `Ordinal#7` is not ordinal 7. - An API set resolves only if the registry lists that exact set for that symbol. A similar name forwards nowhere. +- An optional `ordinal ` field adds an ordinal for the canonical DLL. Cite the export catalog and version that establish the mapping. Named and ordinal imports share the same adapter. The ordinal applies only to the canonical DLL. - Registering a key twice is an error. A host module cannot replace a standard service. - Binding resolves every import before it writes any slot. A malformed table or an unresolved import leaves every slot unbound. - A service call reads its return address first, and stops the guest with `ServiceAbiViolation` if the service changed a nonvolatile register, including XMM6 to XMM15.