//! Typed PBX declarations and bounded immutable Registry resolution. //! These declarations do not authorize execution: code and bindings still require verification. use crate::load_limits::IdDomain; use crate::load_limits::{ LoadBudget, LoadCode as C, LoadFailure as E, LoadReason as R, LoadResource as Q, }; use crate::Value; use std::sync::Arc; macro_rules! id { ($name:ident) => { #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct $name(pub u32); }; } id!(TypeId); id!(FunctionId); id!(ImplementationId); id!(BuiltinId); #[derive(Debug, Clone, PartialEq, Eq)] pub struct NamedType { pub type_id: TypeId, pub name: Option, } #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Signature { pub parameters: Vec, pub results: Vec, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct MethodDecl { pub name: Option, pub signature: Signature, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum TypeKind { Builtin(BuiltinId), Struct(Vec), Array(TypeId), Trait(Vec), } #[derive(Debug, Clone, PartialEq, Eq)] pub struct TypeDecl { pub name: Option, pub kind: TypeKind, } #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct FunctionDecl { pub name: Option, pub signature: Signature, pub code_offset: u32, pub code_len: u32, pub local_slots: u32, pub max_stack_slots: u32, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct ImplementationDecl { pub owner: TypeId, pub trait_id: TypeId, pub methods: Vec, } #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct RegistryDeclarations { pub types: Vec, pub functions: Vec, pub implementations: Vec, } pub type StringSlot = Option>; #[derive(Debug, Clone)] pub struct DynamicSlot { pub type_id: Option, pub payload: Value, } impl Default for DynamicSlot { fn default() -> Self { Self { type_id: None, payload: Value::Null } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DefaultKind { Int32, Int64, Float, Bool, Null, Vec2, Pixel, Trait, Dynamic, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Ownership { Plain, GuestReference, NativeString, TraitReceiver, Dynamic, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct StorageLayout { pub size: usize, pub alignment: usize, pub slots: u32, pub ownership: Ownership, pub default: DefaultKind, } impl StorageLayout { fn new( size: usize, alignment: usize, slots: u32, ownership: Ownership, default: DefaultKind, ) -> Self { Self { size, alignment, slots, ownership, default } } pub fn nullable(self) -> bool { !matches!(self.ownership, Ownership::Plain) } /// Canonical stack-side defaults, with no allocation or source constructor. /// Native typed storage still requires its own initialized-slot construction. pub fn default_values(self) -> &'static [Value] { match self.default { DefaultKind::Int32 => &[Value::Int32(0)], DefaultKind::Int64 => &[Value::Int64(0)], DefaultKind::Float => &[Value::Float(0.0)], DefaultKind::Bool => &[Value::Boolean(false)], DefaultKind::Null => &[Value::Null], DefaultKind::Vec2 => &[Value::Float(0.0), Value::Float(0.0)], DefaultKind::Pixel => &[Value::Int64(0), Value::Int64(0), Value::Int64(0)], DefaultKind::Trait | DefaultKind::Dynamic => &[Value::Null, Value::Null], } } } impl BuiltinId { pub const COLOR: Self = Self(1); pub const VEC2: Self = Self(2); pub const PIXEL: Self = Self(3); pub const INT32: Self = Self(0x10); pub const INT64: Self = Self(0x11); pub const FLOAT: Self = Self(0x12); pub const BOOL: Self = Self(0x13); pub const STRING: Self = Self(0x14); pub const DYNAMIC: Self = Self(0x15); pub fn layout(self) -> Result { use DefaultKind as D; use Ownership as O; let (size, alignment, slots, ownership, default) = match self { Self::COLOR => (4, 4, 1, O::Plain, D::Int64), Self::VEC2 => (16, 8, 2, O::Plain, D::Vec2), Self::PIXEL => (24, 8, 3, O::Plain, D::Pixel), Self::INT32 => (4, 4, 1, O::Plain, D::Int32), Self::INT64 => (8, 8, 1, O::Plain, D::Int64), Self::FLOAT => (8, 8, 1, O::Plain, D::Float), Self::BOOL => (1, 1, 1, O::Plain, D::Bool), Self::STRING => { (size_of::(), align_of::(), 1, O::NativeString, D::Null) } Self::DYNAMIC => { (size_of::(), align_of::(), 2, O::Dynamic, D::Dynamic) } _ => return Err(E::new(C::UnsupportedFormat, R::Builtin)), }; Ok(StorageLayout::new(size, alignment, slots, ownership, default)) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct FieldLayout { pub type_id: TypeId, pub offset: usize, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct OwnedField { pub offset: usize, pub ownership: Ownership, } #[derive(Debug, PartialEq, Eq)] pub struct StructLayout { pub size: usize, pub alignment: usize, pub fields: Vec, /// Sorted offsets for fields requiring guest tracing or native ownership handling. pub owned_fields: Vec, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ArrayLayout { pub element_type_id: TypeId, pub stride: usize, pub element_alignment: usize, } #[derive(Debug, PartialEq, Eq)] pub struct TypeLayout { pub storage: StorageLayout, pub instance: Option, pub array: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct FunctionLayout { pub parameter_slots: u32, pub result_slots: u32, } #[derive(Debug)] pub struct Registry { declarations: RegistryDeclarations, layouts: Vec, functions: Vec, // Sorted by owner/trait; original implementation IDs are never remapped. implementations: Vec<(TypeId, TypeId, ImplementationId)>, } impl Registry { pub fn declarations(&self) -> &RegistryDeclarations { &self.declarations } pub fn type_layout(&self, id: TypeId) -> Option<&TypeLayout> { self.layouts.get(id.0 as usize) } pub fn function_layout(&self, id: FunctionId) -> Option<&FunctionLayout> { self.functions.get(id.0 as usize) } pub fn implementation(&self, owner: TypeId, trait_id: TypeId) -> Option { self.implementations .binary_search_by_key(&(owner, trait_id), |&(a, b, _)| (a, b)) .ok() .map(|i| self.implementations[i].2) } /// Resolves declarations, not code/bindings. The caller must still verify before publication. /// Declaration allocations are retained and charged here, even for non-PBX producers. pub fn resolve( declarations: RegistryDeclarations, code_len: usize, budget: &mut LoadBudget, ) -> Result { budget.transaction(|budget| Self::resolve_inner(declarations, code_len, budget)) } fn resolve_inner( d: RegistryDeclarations, code_len: usize, b: &mut LoadBudget, ) -> Result { b.check(Q::Types, d.types.len() as u64)?; b.check(Q::Functions, d.functions.len() as u64)?; b.check(Q::Implementations, d.implementations.len() as u64)?; b.check(Q::CodeBytes, code_len as u64)?; charge_declarations(&d, b)?; validate_declarations(&d, b)?; let mut layouts = b.vector(d.types.len(), Q::RegistryBytes)?; for (i, t) in d.types.iter().enumerate() { b.work(1)?; let storage = match t.kind { TypeKind::Builtin(id) => id.layout().map_err(|e| e.record(i as u32))?, TypeKind::Trait(_) => { StorageLayout::new(16, 8, 2, Ownership::TraitReceiver, DefaultKind::Trait) } _ => StorageLayout::new(8, 8, 1, Ownership::GuestReference, DefaultKind::Null), }; layouts.push(TypeLayout { storage, instance: None, array: None }); } for (i, t) in d.types.iter().enumerate() { b.work(1)?; if let TypeKind::Array(element_type_id) = t.kind { let element = layouts[element_type_id.0 as usize].storage; layouts[i].array = Some(ArrayLayout { element_type_id, stride: align(element.size, element.alignment)?, element_alignment: element.alignment, }); } if let TypeKind::Struct(fields) = &t.kind { let mut offsets = b.vector(fields.len(), Q::RegistryBytes)?; b.work(fields.len())?; let owned_count = fields .iter() .filter(|f| layouts[f.type_id.0 as usize].storage.ownership != Ownership::Plain) .count(); let mut owned = b.vector(owned_count, Q::RegistryBytes)?; let (mut size, mut alignment) = (0, 1); for field in fields { b.work(1)?; let layout = layouts[field.type_id.0 as usize].storage; size = align(size, layout.alignment)?; offsets.push(FieldLayout { type_id: field.type_id, offset: size }); if layout.ownership != Ownership::Plain { owned.push(OwnedField { offset: size, ownership: layout.ownership }); } size = size.checked_add(layout.size).ok_or_else(overflow)?; alignment = alignment.max(layout.alignment); } layouts[i].instance = Some(StructLayout { size: align(size, alignment)?, alignment, fields: offsets, owned_fields: owned, }); } } let mut functions = b.vector(d.functions.len(), Q::RegistryBytes)?; let mut ranges = b.vector(d.functions.len(), Q::TemporaryBytes)?; for (i, f) in d.functions.iter().enumerate() { b.work(1)?; let params = width(f.signature.parameters.iter().map(|p| p.type_id), &layouts, b)?; let results = width(f.signature.results.iter().copied(), &layouts, b)?; let frame = u64::from(params) + u64::from(f.local_slots) + u64::from(f.max_stack_slots); if frame > b.frame_limit() { return Err(E::new(C::InvalidCode, R::FrameSlots) .in_section(1) .record(i as u32) .in_function(i as u32, None)); } if u64::from(results) > b.result_limit() { return Err(E::new(C::InvalidCode, R::ReturnSlots) .in_section(1) .record(i as u32) .in_function(i as u32, None)); } let end = f.code_offset.checked_add(f.code_len).ok_or_else(|| { E::new(C::InvalidCode, R::CodeRange) .in_section(1) .record(i as u32) .in_function(i as u32, Some(f.code_offset)) })?; if end as usize > code_len || f.code_len == 0 { return Err(E::new(C::InvalidCode, R::CodeRange) .in_section(1) .record(i as u32) .in_function(i as u32, Some(f.code_offset))); } ranges.push((f.code_offset, end, i as u32)); functions.push(FunctionLayout { parameter_slots: params, result_slots: results }); } sort_work(ranges.len(), b)?; ranges.sort_unstable(); for pair in ranges.windows(2) { b.work(1)?; if pair[0].1 > pair[1].0 { return Err(E::new(C::InvalidCode, R::CodeRange).record(pair[1].2)); } } b.refund(Q::TemporaryBytes, (ranges.capacity() * size_of::<(u32, u32, u32)>()) as u64); drop(ranges); let mut implementations = b.vector(d.implementations.len(), Q::RegistryBytes)?; for (i, imp) in d.implementations.iter().enumerate() { b.work(1)?; if !matches!(d.types[imp.owner.0 as usize].kind, TypeKind::Struct(_)) { return Err(E::new(C::InvalidReference, R::OwnerCategory) .in_section(7) .record(i as u32) .reference(IdDomain::Type, imp.owner.0)); } let TypeKind::Trait(methods) = &d.types[imp.trait_id.0 as usize].kind else { return Err(E::new(C::InvalidReference, R::TraitCategory) .in_section(7) .record(i as u32) .reference(IdDomain::Type, imp.trait_id.0)); }; if methods.len() != imp.methods.len() { return Err(E::new(C::InvalidRegistry, R::MethodCount) .in_section(7) .record(i as u32)); } for (j, (method, id)) in methods.iter().zip(&imp.methods).enumerate() { let signature = &d.functions[id.0 as usize].signature; b.work(signature.parameters.len() + signature.results.len() + 1)?; if signature.parameters.first().map(|p| p.type_id) != Some(imp.owner) || signature.parameters.len() != method.signature.parameters.len() + 1 || !signature.parameters.iter().skip(1).map(|p| p.type_id).eq(method .signature .parameters .iter() .map(|p| p.type_id)) || signature.results != method.signature.results { return Err(E::new(C::InvalidRegistry, R::Signature) .in_section(7) .record(i as u32) .member(j as u32)); } } implementations.push((imp.owner, imp.trait_id, ImplementationId(i as u32))); } sort_work(implementations.len(), b)?; implementations.sort_unstable(); for pair in implementations.windows(2) { b.work(1)?; if (pair[0].0, pair[0].1) == (pair[1].0, pair[1].1) { return Err(E::new(C::InvalidRegistry, R::DuplicateImplementation) .in_section(7) .record(pair[1].2 .0)); } } Ok(Self { declarations: d, layouts, functions, implementations }) } } fn overflow() -> E { E::new(C::ResourceLimit, R::Overflow) } fn align(n: usize, a: usize) -> Result { n.checked_add(a - 1).map(|v| v & !(a - 1)).ok_or_else(overflow) } fn width( ids: impl Iterator, layouts: &[TypeLayout], b: &mut LoadBudget, ) -> Result { let mut sum = 0u32; for id in ids { b.work(1)?; sum = sum.checked_add(layouts[id.0 as usize].storage.slots).ok_or_else(overflow)?; } Ok(sum) } fn sort_work(n: usize, b: &mut LoadBudget) -> Result<(), E> { let bits = usize::BITS - n.leading_zeros(); b.work(n.checked_mul(bits as usize + 1).ok_or_else(overflow)?) } fn type_ref(id: TypeId, d: &RegistryDeclarations) -> Result<(), E> { if (id.0 as usize) < d.types.len() { Ok(()) } else { Err(E::new(C::InvalidReference, R::TypeId).reference(IdDomain::Type, id.0)) } } fn name(name: &Option, b: &mut LoadBudget) -> Result<(), E> { if let Some(name) = name { if name.len() as u64 > b.individual_name_limit() { return Err(E::resource(Q::NameBytes, name.len() as u64, b.individual_name_limit())); } b.charge(Q::NameBytes, name.len() as u64)?; b.work(name.len())?; } Ok(()) } fn named(items: &[NamedType], d: &RegistryDeclarations, b: &mut LoadBudget) -> Result<(), E> { b.charge(Q::NestedRecords, items.len() as u64)?; for (i, item) in items.iter().enumerate() { b.work(1)?; type_ref(item.type_id, d).map_err(|e| e.member(i as u32))?; name(&item.name, b)?; } Ok(()) } fn signature(s: &Signature, d: &RegistryDeclarations, b: &mut LoadBudget) -> Result<(), E> { named(&s.parameters, d, b)?; b.charge(Q::NestedRecords, s.results.len() as u64)?; for (i, id) in s.results.iter().enumerate() { b.work(1)?; type_ref(*id, d).map_err(|e| e.member(i as u32))?; } Ok(()) } /// Validate all edges before indexed layout resolution; IDs remain table positions. pub(crate) fn validate_declarations(d: &RegistryDeclarations, b: &mut LoadBudget) -> Result<(), E> { b.charge(Q::Types, d.types.len() as u64)?; b.charge(Q::Functions, d.functions.len() as u64)?; b.charge(Q::Implementations, d.implementations.len() as u64)?; let mut constructors = b.vector(d.types.len(), Q::TemporaryBytes)?; for (i, t) in d.types.iter().enumerate() { b.work(1)?; name(&t.name, b).map_err(|e| e.in_section(6).record(i as u32))?; let result = (|| match &t.kind { TypeKind::Builtin(id) => { id.layout()?; constructors.push((0, id.0, i as u32)); Ok(()) } TypeKind::Array(id) => { type_ref(*id, d)?; constructors.push((1, id.0, i as u32)); Ok(()) } TypeKind::Struct(fields) => named(fields, d, b), TypeKind::Trait(methods) => { b.charge(Q::NestedRecords, methods.len() as u64)?; for m in methods { b.work(1)?; name(&m.name, b)?; signature(&m.signature, d, b)?; } Ok(()) } })(); result.map_err(|e| e.in_section(6).record(i as u32))?; } sort_work(constructors.len(), b)?; constructors.sort_unstable(); for pair in constructors.windows(2) { b.work(1)?; if (pair[0].0, pair[0].1) == (pair[1].0, pair[1].1) { return Err(E::new( C::InvalidRegistry, if pair[1].0 == 0 { R::DuplicateBuiltin } else { R::DuplicateArray }, ) .record(pair[1].2)); } } b.refund(Q::TemporaryBytes, (constructors.capacity() * size_of::<(i32, u32, u32)>()) as u64); drop(constructors); // Iterative tri-color walk: every Array has one successor; nominal nodes terminate walks. let mut colors = b.vector::(d.types.len(), Q::TemporaryBytes)?; colors.resize(d.types.len(), 0); for start in 0..d.types.len() { b.work(1)?; let mut node = start; while colors[node] == 0 { b.work(1)?; colors[node] = 1; match d.types[node].kind { TypeKind::Array(id) => node = id.0 as usize, _ => break, } } if colors[node] == 1 && matches!(d.types[node].kind, TypeKind::Array(_)) { return Err(E::new(C::InvalidRegistry, R::ArrayCycle).record(node as u32)); } node = start; while colors[node] == 1 { b.work(1)?; colors[node] = 2; match d.types[node].kind { TypeKind::Array(id) => node = id.0 as usize, _ => break, } } } b.refund(Q::TemporaryBytes, colors.capacity() as u64); drop(colors); for (i, f) in d.functions.iter().enumerate() { b.work(1)?; name(&f.name, b).map_err(|e| e.in_section(1).record(i as u32))?; signature(&f.signature, d, b).map_err(|e| e.in_section(1).record(i as u32))?; } for (i, imp) in d.implementations.iter().enumerate() { b.work(1)?; type_ref(imp.owner, d).map_err(|e| e.in_section(7).record(i as u32))?; type_ref(imp.trait_id, d).map_err(|e| e.in_section(7).record(i as u32))?; b.charge(Q::NestedRecords, imp.methods.len() as u64)?; for (j, id) in imp.methods.iter().enumerate() { b.work(1)?; if id.0 as usize >= d.functions.len() { return Err(E::new(C::InvalidReference, R::FunctionId) .in_section(7) .reference(IdDomain::Function, id.0) .record(i as u32) .member(j as u32)); } } } Ok(()) } fn charge_vec(v: &Vec, b: &mut LoadBudget) -> Result<(), E> { b.charge( Q::RegistryBytes, (v.capacity() as u64).checked_mul(size_of::() as u64).ok_or_else(overflow)?, ) } fn charge_name(n: &Option, b: &mut LoadBudget) -> Result<(), E> { if let Some(n) = n { b.charge(Q::RegistryBytes, n.capacity() as u64)?; } Ok(()) } fn charge_named(v: &Vec, b: &mut LoadBudget) -> Result<(), E> { charge_vec(v, b)?; for p in v { b.work(1)?; charge_name(&p.name, b)?; } Ok(()) } fn charge_signature(s: &Signature, b: &mut LoadBudget) -> Result<(), E> { charge_named(&s.parameters, b)?; charge_vec(&s.results, b) } fn charge_declarations(d: &RegistryDeclarations, b: &mut LoadBudget) -> Result<(), E> { b.charge(Q::RegistryBytes, size_of::() as u64)?; charge_vec(&d.types, b)?; charge_vec(&d.functions, b)?; charge_vec(&d.implementations, b)?; for t in &d.types { b.work(1)?; charge_name(&t.name, b)?; match &t.kind { TypeKind::Struct(fields) => charge_named(fields, b)?, TypeKind::Trait(methods) => { charge_vec(methods, b)?; for m in methods { b.work(1)?; charge_name(&m.name, b)?; charge_signature(&m.signature, b)?; } } _ => {} } } for f in &d.functions { b.work(1)?; charge_name(&f.name, b)?; charge_signature(&f.signature, b)?; } for imp in &d.implementations { b.work(1)?; charge_vec(&imp.methods, b)?; } Ok(()) }