//! Producer-side serialization of a complete typed module. This writer emits //! only v1; executable consumers still need bindings and code verification. use super::*; use crate::load_limits::IdDomain; use crate::model::{ConstantPoolEntry, DebugInfo, Export, SyscallDecl}; /// Borrowed producer data with already resolved Registry declarations. There /// is no version selector, inferred signature or generic Value-to-null path. pub struct PbxModule<'a> { pub registry: &'a Registry, pub constants: &'a [ConstantPoolEntry], pub code: &'a [u8], pub debug: Option<&'a DebugInfo>, pub exports: &'a [Export], pub syscalls: &'a [SyscallDecl], } impl PbxModule<'_> { /// All intermediate sections coexist with the final output and are charged /// until dropped. On success only the returned Vec capacity remains charged. pub fn serialize(&self, budget: &mut LoadBudget) -> Result, E> { budget.transaction(|budget| { let temporary_before = budget.used(Q::TemporaryBytes); budget.check(Q::CodeBytes, self.code.len() as u64)?; for (id, function) in self.registry.declarations().functions.iter().enumerate() { budget.work(1)?; if u64::from(function.code_offset) + u64::from(function.code_len) > self.code.len() as u64 { return Err(E::new(C::InvalidCode, R::CodeRange) .in_section(2) .in_function(id as u32, Some(function.code_offset))); } } let registry = encode_registry(self.registry, budget)?; let constants = write_section(budget, |w| self.write_constants(w))?; let exports = write_section(budget, |w| self.write_exports(w))?; let syscalls = write_section(budget, |w| self.write_syscalls(w))?; // Reuse the bounded identity validator; do not introduce a second // native-binding catalog or an unbounded duplicate search. Reader::new(Section { kind: 5, offset: 0, bytes: &syscalls }, budget).syscalls()?; let debug = self .debug .map(|di| write_section(budget, |w| self.write_debug(di, w))) .transpose()?; let mut sections = [SectionData { kind: 0, bytes: &[] }; 9]; let mut count = 0; for (kind, bytes) in [ (0, Some(constants.as_slice())), (1, Some(registry.functions.as_slice())), (2, Some(self.code)), (3, debug.as_deref()), (4, Some(exports.as_slice())), (5, Some(syscalls.as_slice())), (6, Some(registry.types.as_slice())), (7, Some(registry.implementations.as_slice())), (8, Some(registry.captures.as_slice())), ] { if let Some(bytes) = bytes { sections[count] = SectionData { kind, bytes }; count += 1; } } let out = encode_envelope(§ions[..count], budget)?; // The borrowed section array and all owned intermediate Vecs die // before return. Preserve prior scratch plus returned output only. let retained = out.capacity() as u64; drop(debug); drop(syscalls); drop(exports); drop(constants); drop(registry); budget.refund( Q::TemporaryBytes, budget.used(Q::TemporaryBytes) - temporary_before - retained, ); Ok(out) }) } fn write_constants(&self, w: &mut Writer<'_>) -> Result<(), E> { w.budget.check(Q::ConstantEntries, self.constants.len() as u64)?; w.count(self.constants.len())?; let mut string_bytes = 0u64; for (id, entry) in self.constants.iter().enumerate() { w.budget.work(1)?; match entry { ConstantPoolEntry::Null => w.byte(0)?, ConstantPoolEntry::Int64(value) => { w.byte(1)?; w.bytes(&value.to_le_bytes())?; } ConstantPoolEntry::Float64(value) => { w.byte(2)?; w.bytes(&value.to_bits().to_le_bytes())?; } ConstantPoolEntry::Boolean(value) => { w.byte(3)?; w.byte(u8::from(*value))?; } ConstantPoolEntry::String(value) => { if value.len() as u64 > w.budget.individual_string_limit() { return Err(E::resource( Q::ConstantStringBytes, value.len() as u64, w.budget.individual_string_limit(), ) .in_section(0) .record(id as u32)); } string_bytes = string_bytes.checked_add(value.len() as u64).ok_or_else(overflow)?; w.budget.check(Q::ConstantStringBytes, string_bytes)?; w.byte(4)?; w.count(value.len())?; w.bytes(value.as_bytes())?; } ConstantPoolEntry::Int32(value) => { w.byte(5)?; w.bytes(&value.to_le_bytes())?; } } } Ok(()) } fn check_function(&self, id: u32) -> Result<(), E> { if id as usize >= self.registry.declarations().functions.len() { Err(E::new(C::InvalidReference, R::FunctionId).reference(IdDomain::Function, id)) } else { Ok(()) } } fn write_exports(&self, w: &mut Writer<'_>) -> Result<(), E> { w.count(self.exports.len())?; for (record, export) in self.exports.iter().enumerate() { w.budget.work(1)?; self.check_function(export.func_idx) .map_err(|e| e.in_section(4).record(record as u32))?; w.u32(export.func_idx)?; w.text(&export.symbol, 4)?; } Ok(()) } fn write_syscalls(&self, w: &mut Writer<'_>) -> Result<(), E> { w.count(self.syscalls.len())?; for syscall in self.syscalls { w.budget.work(1)?; w.text(&syscall.module, 2)?; w.text(&syscall.name, 2)?; w.bytes(&syscall.version.to_le_bytes())?; w.bytes(&syscall.arg_slots.to_le_bytes())?; w.bytes(&syscall.ret_slots.to_le_bytes())?; } Ok(()) } fn write_debug(&self, debug: &DebugInfo, w: &mut Writer<'_>) -> Result<(), E> { w.count(debug.pc_to_span.len())?; for (record, (pc, span)) in debug.pc_to_span.iter().enumerate() { w.budget.work(1)?; if *pc as usize >= self.code.len() || span.end < span.start { return Err(E::new(C::InvalidFormat, R::DebugRange) .in_section(3) .record(record as u32)); } w.u32(*pc)?; w.u32(span.file_id)?; w.u32(span.start)?; w.u32(span.end)?; } w.count(debug.function_names.len())?; for (record, (id, name)) in debug.function_names.iter().enumerate() { w.budget.work(1)?; self.check_function(*id).map_err(|e| e.in_section(3).record(record as u32))?; w.u32(*id)?; w.text(name, 4)?; } Ok(()) } } impl Writer<'_> { fn text(&mut self, value: &str, length_bytes: usize) -> Result<(), E> { if value.len() as u64 > self.budget.individual_name_limit() { return Err(E::resource( Q::NameBytes, value.len() as u64, self.budget.individual_name_limit(), )); } if length_bytes == 2 { self.bytes(&u16::try_from(value.len()).map_err(|_| overflow())?.to_le_bytes())?; } else { self.count(value.len())?; } self.bytes(value.as_bytes()) } }