feat(registry): checkpoint PLN-0176 foundations and validated partial integrations

This commit is contained in:
2026-10-07 17:49:46 +01:00
parent 01fab56cc6
commit 126a9e50e7
63 changed files with 8499 additions and 1462 deletions
@@ -0,0 +1,244 @@
//! Validation of unchanged non-Registry section encodings, without allocating
//! guest constants or publishing an executable image.
use super::*;
use crate::load_limits::IdDomain;
use std::cmp::Ordering;
/// All PBX tables have passed binary and reference validation. Code has NOT
/// passed instruction/type-flow verification and host calls are NOT bound.
#[derive(Debug)]
pub struct ParsedPbx<'a> {
envelope: PbxEnvelope<'a>,
registry: Registry,
}
impl<'a> ParsedPbx<'a> {
pub fn parse(bytes: &'a [u8], budget: &mut LoadBudget) -> Result<Self, E> {
budget.transaction(|budget| {
let envelope = PbxEnvelope::parse(bytes, budget)?;
let registry = envelope.resolve_registry(budget)?;
let functions = registry.declarations().functions.len();
let code_len = envelope.section(2).unwrap().bytes.len();
Reader::new(envelope.section(0).unwrap(), budget).constants()?;
Reader::new(envelope.section(4).unwrap(), budget).exports(functions)?;
Reader::new(envelope.section(5).unwrap(), budget).syscalls()?;
if let Some(debug) = envelope.section(3) {
Reader::new(debug, budget).debug(functions, code_len)?;
}
Ok(Self { envelope, registry })
})
}
pub fn registry(&self) -> &Registry {
&self.registry
}
pub fn section(&self, kind: u32) -> Option<Section<'a>> {
self.envelope.section(kind)
}
/// Re-encode validated tables in canonical directory order; debug absence is preserved.
pub fn encode(&self, budget: &mut LoadBudget) -> Result<Vec<u8>, E> {
let mut sections = [SectionData { kind: 0, bytes: &[] }; 8];
let mut count = 0;
for kind in 0..8 {
if let Some(section) = self.section(kind) {
sections[count] = SectionData { kind, bytes: section.bytes };
count += 1;
}
}
encode_envelope(&sections[..count], budget)
}
}
impl<'a> Reader<'a, '_> {
fn u16(&mut self) -> Result<u16, E> {
Ok(u16::from_le_bytes(self.take(2)?.try_into().unwrap()))
}
fn raw_count(&mut self, minimum: usize) -> Result<usize, E> {
let count = self.u32()? as usize;
if count.checked_mul(minimum).ok_or_else(overflow)? > self.section.bytes.len() - self.pos {
return Err(self.error(C::InvalidFormat, R::Truncated));
}
Ok(count)
}
fn utf8(&mut self, len: usize) -> Result<&'a str, E> {
let bytes = self.take(len)?;
self.budget.work(len)?;
std::str::from_utf8(bytes).map_err(|_| self.error(C::InvalidFormat, R::Utf8))
}
fn text(&mut self, len: usize) -> Result<&'a str, E> {
if len as u64 > self.budget.individual_name_limit() {
return Err(E::resource(Q::NameBytes, len as u64, self.budget.individual_name_limit())
.at(self.section.kind, self.section.offset + self.pos));
}
self.utf8(len)
}
fn function(&self, id: u32, count: usize) -> Result<(), E> {
if id as usize >= count {
Err(self.error(C::InvalidReference, R::FunctionId).reference(IdDomain::Function, id))
} else {
Ok(())
}
}
fn constants(mut self) -> Result<(), E> {
let count = self.u32()? as usize;
self.budget.charge(Q::ConstantEntries, count as u64)?;
if count > self.section.bytes.len() - self.pos {
return Err(self.error(C::InvalidFormat, R::Truncated));
}
for i in 0..count {
self.budget.work(1)?;
(|| {
match self.byte()? {
0 => {}
1 | 2 => {
self.take(8)?;
}
3 => {
if self.byte()? > 1 {
return Err(self.error(C::InvalidFormat, R::InvalidFlag));
}
}
4 => {
let len = self.u32()? as usize;
if len as u64 > self.budget.individual_string_limit() {
return Err(E::resource(
Q::ConstantStringBytes,
len as u64,
self.budget.individual_string_limit(),
)
.at(0, self.section.offset + self.pos));
}
self.budget.charge(Q::ConstantStringBytes, len as u64)?;
self.utf8(len)?;
}
5 => {
self.take(4)?;
}
_ => return Err(self.error(C::UnsupportedFormat, R::ConstantTag)),
}
Ok(())
})()
.map_err(|e: E| e.record(i as u32))?;
}
self.finish()
}
fn exports(mut self, functions: usize) -> Result<(), E> {
let count = self.raw_count(8)?;
for i in 0..count {
self.budget.work(1)?;
let id = self.u32()?;
self.function(id, functions).map_err(|e| e.record(i as u32))?;
let len = self.u32()? as usize;
self.text(len).map_err(|e| e.record(i as u32))?;
}
self.finish()
}
fn debug(mut self, functions: usize, code_len: usize) -> Result<(), E> {
let count = self.raw_count(16)?;
for i in 0..count {
self.budget.work(1)?;
let pc = self.u32()?;
self.u32()?; // source file ID, local to debug information
let start = self.u32()?;
let end = self.u32()?;
if pc as usize >= code_len || end < start {
return Err(self.error(C::InvalidFormat, R::DebugRange).record(i as u32));
}
}
let names = self.raw_count(8)?;
for i in 0..names {
self.budget.work(1)?;
let id = self.u32()?;
self.function(id, functions).map_err(|e| e.record(i as u32))?;
let len = self.u32()? as usize;
self.text(len).map_err(|e| e.record(i as u32))?;
}
self.finish()
}
fn syscalls(mut self) -> Result<(), E> {
let count = self.raw_count(10)?;
let mut identities = self.budget.vector(count, Q::TemporaryBytes)?;
for i in 0..count {
self.budget.work(1)?;
let len = self.u16()? as usize;
let module = self.text(len).map_err(|e| e.record(i as u32))?;
let len = self.u16()? as usize;
let name = self.text(len).map_err(|e| e.record(i as u32))?;
let version = self.u16()?;
self.u16()?; // argument slots, unchanged SYSC encoding
self.u16()?; // result slots
identities.push((module, name, version, i as u32));
}
self.finish()?;
// Fallible heapsort bounds both auxiliary storage and comparison work;
// unlike sorting with an error flag it stops immediately at quota refusal.
fallible_sort(&mut identities, |a, b| {
let module = text_cmp(a.0, b.0, self.budget)?;
if module != Ordering::Equal {
return Ok(module);
}
let name = text_cmp(a.1, b.1, self.budget)?;
if name != Ordering::Equal {
return Ok(name);
}
self.budget.work(1)?;
Ok((a.2, a.3).cmp(&(b.2, b.3)))
})?;
for pair in identities.windows(2) {
self.budget.work(1)?;
if text_cmp(pair[0].0, pair[1].0, self.budget)? == Ordering::Equal
&& text_cmp(pair[0].1, pair[1].1, self.budget)? == Ordering::Equal
&& pair[0].2 == pair[1].2
{
return Err(self.error(C::InvalidFormat, R::DuplicateSyscall).record(pair[1].3));
}
}
self.budget.refund(
Q::TemporaryBytes,
(identities.capacity() * size_of::<(&str, &str, u16, u32)>()) as u64,
);
Ok(())
}
}
fn text_cmp(a: &str, b: &str, budget: &mut LoadBudget) -> Result<Ordering, E> {
for (a, b) in a.bytes().zip(b.bytes()) {
budget.work(2)?;
match a.cmp(&b) {
Ordering::Equal => {}
other => return Ok(other),
}
}
budget.work(1)?;
Ok(a.len().cmp(&b.len()))
}
fn fallible_sort<T>(
items: &mut [T],
mut cmp: impl FnMut(&T, &T) -> Result<Ordering, E>,
) -> Result<(), E> {
fn sift<T>(
items: &mut [T],
mut root: usize,
cmp: &mut impl FnMut(&T, &T) -> Result<Ordering, E>,
) -> Result<(), E> {
while let Some(child) =
root.checked_mul(2).and_then(|n| n.checked_add(1)).filter(|&i| i < items.len())
{
let mut child = child;
if child + 1 < items.len() && cmp(&items[child], &items[child + 1])? == Ordering::Less {
child += 1;
}
if cmp(&items[root], &items[child])? != Ordering::Less {
break;
}
items.swap(root, child);
root = child;
}
Ok(())
}
for root in (0..items.len() / 2).rev() {
sift(items, root, &mut cmp)?;
}
for end in (1..items.len()).rev() {
items.swap(0, end);
sift(&mut items[..end], 0, &mut cmp)?;
}
Ok(())
}