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
@@ -24,6 +24,15 @@ pub const TRAP_BAD_RET_SLOTS: u32 = 0x0000_000C;
/// The intrinsic ID provided is not recognized by the runtime, or its metadata is invalid.
pub const TRAP_INVALID_INTRINSIC: u32 = 0x0000_000D;
/// Valid absence used where an instance is required.
pub const TRAP_NULL_REFERENCE: u32 = 0x0000_000E;
/// Invalid, dead or stale generational heap reference.
pub const TRAP_INVALID_HANDLE: u32 = 0x0000_000F;
/// Quota, checked size overflow or recoverable allocation failure.
pub const TRAP_RESOURCE_LIMIT: u32 = 0x0000_0010;
/// Known input query unavailable on this platform.
pub const TRAP_UNAVAILABLE: u32 = 0x0000_0011;
use serde::{Deserialize, Serialize};
/// Detailed information about a source code span.
@@ -360,6 +360,34 @@ pub fn assemble(src: &str) -> Result<Vec<u8>, AsmError> {
emit_u32(parse_u32_any(ops)?, &mut out);
}
"DYN_PACK" | "DYN_UNPACK" | "DYN_CAN_UNPACK" => {
if ops.is_empty() {
return Err(AsmError::MissingOperand(line.into()));
}
let opcode = match mn {
"DYN_PACK" => CoreOpCode::DynPack,
"DYN_UNPACK" => CoreOpCode::DynUnpack,
_ => CoreOpCode::DynCanUnpack,
};
emit_u16(opcode as u16, &mut out);
emit_u32(parse_u32_any(ops)?, &mut out);
}
"REF_IS_EXACT" | "REF_IMPLEMENTS" | "REF_TO_TRAIT" | "REF_CAST" => {
if ops.is_empty() {
return Err(AsmError::MissingOperand(line.into()));
}
let (a, b) = parse_keyvals(ops)?;
let (source, target) = parse_pair(a, "source", b, "target")?;
let opcode = match mn {
"REF_IS_EXACT" => CoreOpCode::RefIsExact,
"REF_IMPLEMENTS" => CoreOpCode::RefImplements,
"REF_TO_TRAIT" => CoreOpCode::RefToTrait,
_ => CoreOpCode::RefCast,
};
emit_u16(opcode as u16, &mut out);
emit_u32(source, &mut out);
emit_u32(target, &mut out);
}
other => return Err(AsmError::UnknownMnemonic(other.into())),
}
}
@@ -90,7 +90,7 @@ impl<'a> DecodedInstr<'a> {
/// Returns the decoded instruction with canonical `next_pc`.
#[inline]
pub fn decode_next(pc: usize, bytes: &'_ [u8]) -> Result<DecodedInstr<'_>, DecodeError> {
if pc + 2 > bytes.len() {
if pc.checked_add(2).is_none_or(|end| end > bytes.len()) {
return Err(DecodeError::TruncatedOpcode { pc });
}
@@ -100,7 +100,13 @@ pub fn decode_next(pc: usize, bytes: &'_ [u8]) -> Result<DecodedInstr<'_>, Decod
let spec: CoreOpcodeSpec = opcode.spec();
let imm_start = pc + 2;
let imm_end = imm_start + (spec.imm_bytes as usize);
let imm_end =
imm_start.checked_add(spec.imm_bytes as usize).ok_or(DecodeError::TruncatedImmediate {
pc,
opcode,
need: spec.imm_bytes as usize,
have: bytes.len().saturating_sub(imm_start),
})?;
if imm_end > bytes.len() {
return Err(DecodeError::TruncatedImmediate {
@@ -60,10 +60,21 @@ fn format_operand(op: CoreOpCode, imm: &[u8]) -> String {
| CoreOpCode::SetLocal
| CoreOpCode::Call
| CoreOpCode::Sleep
| CoreOpCode::Hostcall => {
| CoreOpCode::Hostcall
| CoreOpCode::DynPack
| CoreOpCode::DynUnpack
| CoreOpCode::DynCanUnpack => {
let v = u32::from_le_bytes(imm.try_into().unwrap());
format!("{}", v)
}
CoreOpCode::RefIsExact
| CoreOpCode::RefImplements
| CoreOpCode::RefToTrait
| CoreOpCode::RefCast => {
let source = u32::from_le_bytes(imm[..4].try_into().unwrap());
let target = u32::from_le_bytes(imm[4..].try_into().unwrap());
format!("source={}, target={}", source, target)
}
CoreOpCode::MakeClosure => {
let fn_id = u32::from_le_bytes(imm[0..4].try_into().unwrap());
let cap = u32::from_le_bytes(imm[4..8].try_into().unwrap());
@@ -1,8 +1,9 @@
//! Core ISA profile (bytecode-level, stable, canonical).
//!
//! This profile is the canonical opcode surface used by decoder/disasm and
//! mirrors the runtime-visible instruction set implemented today, including
//! closures, coroutines, intrinsics, and hostcall patching semantics.
//! exposes the canonical encoding for closures, coroutines, intrinsics,
//! hostcall patching and Registry instructions. Recognition by tooling alone
//! does not authorize execution without validated program metadata.
// For PR-1.4 we define the core profile as the current `OpCode` set. We re-export
// the opcode type and spec so downstream tools can import from a stable path:
+11 -3
View File
@@ -12,13 +12,21 @@ mod value;
pub use abi::{
SourceSpan, TrapInfo, TRAP_BAD_RET_SLOTS, TRAP_DIV_ZERO, TRAP_EXPLICIT,
TRAP_ILLEGAL_INSTRUCTION, TRAP_INVALID_FUNC, TRAP_INVALID_INTRINSIC, TRAP_INVALID_LOCAL,
TRAP_INVALID_SYSCALL, TRAP_OOB, TRAP_STACK_UNDERFLOW, TRAP_TYPE,
TRAP_ILLEGAL_INSTRUCTION, TRAP_INVALID_FUNC, TRAP_INVALID_HANDLE, TRAP_INVALID_INTRINSIC,
TRAP_INVALID_LOCAL, TRAP_INVALID_SYSCALL, TRAP_NULL_REFERENCE, TRAP_OOB, TRAP_RESOURCE_LIMIT,
TRAP_STACK_UNDERFLOW, TRAP_TYPE, TRAP_UNAVAILABLE,
};
pub use assembler::{assemble, AsmError};
pub use decoder::{decode_next, DecodeError};
pub use decoder::{decode_next, DecodeError, DecodedInstr};
pub use disassembler::disassemble;
pub use layout::{compute_function_layouts, FunctionLayout};
pub use model::{BytecodeLoader, FunctionMeta, LoadError, SyscallDecl, PBX_MAGIC};
pub use program_image::ProgramImage;
pub use value::{string_materialization_count, HeapRef, Value};
pub mod load_limits;
pub mod registry;
pub mod registry_codec;
mod registry_instruction;
pub use registry_instruction::RegistryStackEffect;
@@ -0,0 +1,341 @@
//! Shared PBX v1 resource limits and structured validation failures.
//! Counters are deterministic; a failed reservation never changes usage.
use std::fmt;
const MIB: u64 = 1_048_576;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoadCode {
InvalidFormat,
UnsupportedFormat,
InvalidReference,
InvalidRegistry,
InvalidCode,
ResourceLimit,
InvalidEntrypoint,
}
impl LoadCode {
pub const fn tag(self) -> &'static str {
match self {
Self::InvalidFormat => "LOAD_INVALID_FORMAT",
Self::UnsupportedFormat => "LOAD_UNSUPPORTED_FORMAT",
Self::InvalidReference => "LOAD_INVALID_REFERENCE",
Self::InvalidRegistry => "LOAD_INVALID_REGISTRY",
Self::InvalidCode => "LOAD_INVALID_CODE",
Self::ResourceLimit => "LOAD_RESOURCE_LIMIT",
Self::InvalidEntrypoint => "LOAD_INVALID_ENTRYPOINT",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoadReason {
Magic,
Version,
Endianness,
Reserved,
SectionKind,
MissingSection,
DuplicateSection,
Overlap,
Truncated,
TrailingBytes,
InvalidFlag,
Utf8,
Category,
Builtin,
TypeId,
FunctionId,
OwnerCategory,
TraitCategory,
DuplicateBuiltin,
DuplicateArray,
ArrayCycle,
DuplicateImplementation,
MethodCount,
Signature,
CodeRange,
FrameSlots,
ReturnSlots,
Overflow,
Limit,
Allocation,
ConstantTag,
DebugRange,
DuplicateSyscall,
UnknownOpcode,
LocalSlot,
JumpTarget,
InstructionBoundary,
BooleanImmediate,
ConstantIndex,
NativeId,
UnpatchedHostcall,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(usize)]
pub enum LoadResource {
PbxBytes,
CodeBytes,
Types,
Functions,
Implementations,
NestedRecords,
NameBytes,
RegistryBytes,
TemporaryBytes,
Work,
ConstantEntries,
ConstantStringBytes,
}
const RESOURCE_COUNT: usize = 12;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IdDomain {
Type,
Function,
Implementation,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoadFailure {
pub code: LoadCode,
pub reason: LoadReason,
pub section: Option<u32>,
pub offset: Option<usize>,
pub record: Option<u32>,
pub member: Option<u32>,
pub id_domain: Option<IdDomain>,
pub referenced_id: Option<u32>,
pub function: Option<u32>,
pub pc: Option<u32>,
pub resource: Option<LoadResource>,
pub requested: Option<u64>,
pub limit: Option<u64>,
}
impl LoadFailure {
pub fn new(code: LoadCode, reason: LoadReason) -> Self {
Self {
code,
reason,
section: None,
offset: None,
record: None,
member: None,
id_domain: None,
referenced_id: None,
function: None,
pc: None,
resource: None,
requested: None,
limit: None,
}
}
pub fn at(mut self, section: u32, offset: usize) -> Self {
self.section = Some(section);
self.offset = Some(offset);
self
}
pub fn record(mut self, record: u32) -> Self {
self.record = Some(record);
self
}
pub fn member(mut self, member: u32) -> Self {
self.member = Some(member);
self
}
pub fn in_section(mut self, section: u32) -> Self {
self.section = Some(section);
self
}
pub fn reference(mut self, domain: IdDomain, id: u32) -> Self {
self.id_domain = Some(domain);
self.referenced_id = Some(id);
self
}
pub fn in_function(mut self, function: u32, pc: Option<u32>) -> Self {
self.function = Some(function);
self.pc = pc;
self
}
pub fn resource(resource: LoadResource, requested: u64, limit: u64) -> Self {
Self {
resource: Some(resource),
requested: Some(requested),
limit: Some(limit),
..Self::new(LoadCode::ResourceLimit, LoadReason::Limit)
}
}
}
impl fmt::Display for LoadFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {:?}", self.code.tag(), self.reason)?;
if let Some(section) = self.section {
write!(f, " in section {section}")?;
}
if let Some(offset) = self.offset {
write!(f, " at byte {offset}")?;
}
if let Some(record) = self.record {
write!(f, " (record {record})")?;
}
if let Some(resource) = self.resource {
write!(f, " ({resource:?}: {:?} / {:?})", self.requested, self.limit)?;
}
Ok(())
}
}
impl std::error::Error for LoadFailure {}
/// Product maxima; callers may lower limits but cannot raise the accepted ceilings.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LoadLimits {
pub pbx_bytes: u64,
pub code_bytes: u64,
pub types: u64,
pub functions: u64,
pub implementations: u64,
pub nested_records: u64,
pub name_bytes: u64,
pub individual_name_bytes: u64,
pub registry_bytes: u64,
pub temporary_bytes: u64,
pub work: u64,
pub frame_slots: u64,
pub result_slots: u64,
pub constant_entries: u64,
pub constant_string_bytes: u64,
pub individual_string_bytes: u64,
}
impl Default for LoadLimits {
fn default() -> Self {
Self {
pbx_bytes: 64 * MIB,
code_bytes: 32 * MIB,
types: 65_536,
functions: 65_536,
implementations: 262_144,
nested_records: 1_048_576,
name_bytes: 4 * MIB,
individual_name_bytes: 4096,
registry_bytes: 64 * MIB,
temporary_bytes: 128 * MIB,
work: 268_435_456,
frame_slots: 16_384,
result_slots: 1024,
constant_entries: 1_048_576,
constant_string_bytes: 64 * MIB,
individual_string_bytes: 4 * MIB,
}
}
}
impl LoadLimits {
fn ceiling(self, r: LoadResource) -> u64 {
match r {
LoadResource::PbxBytes => self.pbx_bytes,
LoadResource::CodeBytes => self.code_bytes,
LoadResource::Types => self.types,
LoadResource::Functions => self.functions,
LoadResource::Implementations => self.implementations,
LoadResource::NestedRecords => self.nested_records,
LoadResource::NameBytes => self.name_bytes,
LoadResource::RegistryBytes => self.registry_bytes,
LoadResource::TemporaryBytes => self.temporary_bytes,
LoadResource::Work => self.work,
LoadResource::ConstantEntries => self.constant_entries,
LoadResource::ConstantStringBytes => self.constant_string_bytes,
}
}
}
/// One load attempt's counters. Successful retained allocations stay charged
/// for the remainder of this attempt; executable-image lifetime accounting is
/// a separate owner. Reuse a budget only when its earlier allocations still live.
#[derive(Debug)]
pub struct LoadBudget {
limits: LoadLimits,
used: [u64; RESOURCE_COUNT],
}
impl LoadBudget {
pub fn new(limits: LoadLimits) -> Self {
Self { limits, used: [0; RESOURCE_COUNT] }
}
pub fn limit(&self, r: LoadResource) -> u64 {
self.limits.ceiling(r).min(LoadLimits::default().ceiling(r))
}
pub fn individual_string_limit(&self) -> u64 {
self.limits.individual_string_bytes.min(4 * MIB)
}
pub fn individual_name_limit(&self) -> u64 {
self.limits.individual_name_bytes.min(4096)
}
pub fn frame_limit(&self) -> u64 {
self.limits.frame_slots.min(16_384)
}
pub fn result_limit(&self) -> u64 {
self.limits.result_slots.min(1024)
}
pub fn used(&self, r: LoadResource) -> u64 {
self.used[r as usize]
}
pub fn charge(&mut self, r: LoadResource, amount: u64) -> Result<(), LoadFailure> {
let next = self
.used(r)
.checked_add(amount)
.ok_or_else(|| LoadFailure::new(LoadCode::ResourceLimit, LoadReason::Overflow))?;
self.check(r, next)?;
self.used[r as usize] = next;
Ok(())
}
pub fn check(&self, r: LoadResource, amount: u64) -> Result<(), LoadFailure> {
if amount > self.limit(r) {
Err(LoadFailure::resource(r, amount, self.limit(r)))
} else {
Ok(())
}
}
pub fn refund(&mut self, r: LoadResource, amount: u64) {
self.used[r as usize] = self.used[r as usize]
.checked_sub(amount)
.expect("internal load budget accounting imbalance");
}
pub fn work(&mut self, amount: usize) -> Result<(), LoadFailure> {
self.charge(LoadResource::Work, amount as u64)
}
pub(crate) fn vector<T>(
&mut self,
count: usize,
r: LoadResource,
) -> Result<Vec<T>, LoadFailure> {
let bytes = count
.checked_mul(std::mem::size_of::<T>())
.ok_or_else(|| LoadFailure::new(LoadCode::ResourceLimit, LoadReason::Overflow))?
as u64;
self.charge(r, bytes)?;
let mut result = Vec::new();
if result.try_reserve_exact(count).is_err() {
self.refund(r, bytes);
return Err(LoadFailure::new(LoadCode::ResourceLimit, LoadReason::Allocation));
}
let actual = (result.capacity() as u64)
.checked_mul(std::mem::size_of::<T>() as u64)
.ok_or_else(|| LoadFailure::new(LoadCode::ResourceLimit, LoadReason::Overflow))?;
if let Err(err) = self.charge(r, actual - bytes) {
self.refund(r, bytes);
return Err(err);
}
Ok(result)
}
/// Roll back retained counters on failure; attempted work remains charged.
pub(crate) fn transaction<T>(
&mut self,
f: impl FnOnce(&mut Self) -> Result<T, LoadFailure>,
) -> Result<T, LoadFailure> {
let before = self.used;
let result = f(self);
if result.is_err() {
let work = self.used(LoadResource::Work);
self.used = before;
self.used[LoadResource::Work as usize] = work;
}
result
}
}
@@ -202,6 +202,22 @@ pub enum OpCode {
/// Synchronizes the VM with the hardware frame (usually 60Hz).
/// Execution pauses until the next VSync.
FrameSync = 0x80,
// Registry-dependent typed operations (DEC-0045).
/// DYN_PACK: TypeId:u32; requires validated Registry metadata.
DynPack = 0x90,
/// DYN_UNPACK: TypeId:u32; requires validated Registry metadata.
DynUnpack = 0x91,
/// DYN_CAN_UNPACK: TypeId:u32; requires validated Registry metadata.
DynCanUnpack = 0x92,
/// REF_IS_EXACT: source:TypeId, target:TypeId; requires validated Registry metadata.
RefIsExact = 0x93,
/// REF_IMPLEMENTS: source:TypeId, target:TypeId; requires validated Registry metadata.
RefImplements = 0x94,
/// REF_TO_TRAIT: source:TypeId, target:TypeId; requires validated Registry metadata.
RefToTrait = 0x95,
/// REF_CAST: source:TypeId, target:TypeId; requires validated Registry metadata.
RefCast = 0x96,
}
impl TryFrom<u16> for OpCode {
@@ -259,6 +275,14 @@ impl TryFrom<u16> for OpCode {
0x71 => Ok(OpCode::Hostcall),
0x72 => Ok(OpCode::Intrinsic),
0x80 => Ok(OpCode::FrameSync),
0x90 => Ok(OpCode::DynPack),
0x91 => Ok(OpCode::DynUnpack),
0x92 => Ok(OpCode::DynCanUnpack),
0x93 => Ok(OpCode::RefIsExact),
0x94 => Ok(OpCode::RefImplements),
0x95 => Ok(OpCode::RefToTrait),
0x96 => Ok(OpCode::RefCast),
_ => Err(format!("Invalid OpCode: 0x{:04X}", value)),
}
}
@@ -319,6 +343,13 @@ impl OpCode {
OpCode::Hostcall => 1,
OpCode::Intrinsic => 1,
OpCode::FrameSync => 1,
OpCode::DynPack => 8,
OpCode::DynUnpack => 4,
OpCode::DynCanUnpack => 3,
OpCode::RefIsExact => 4,
OpCode::RefImplements => 4,
OpCode::RefToTrait => 5,
OpCode::RefCast => 4,
}
}
}
@@ -5,18 +5,24 @@ use crate::opcode::OpCode;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OpcodeSpec {
pub name: &'static str,
pub imm_bytes: u8, // immediate payload size (decode)
pub pops: u16, // slots popped
pub pushes: u16, // slots pushed
pub is_branch: bool, // has a control-flow target
pub imm_bytes: u8, // immediate payload size (decode)
/// None requires Registry resolution; it never means zero slots.
pub pops: Option<u16>, // slots popped
/// None requires Registry resolution; it never means zero slots.
pub pushes: Option<u16>, // slots pushed
pub is_branch: bool, // has a control-flow target
pub is_terminator: bool, // ends basic block: JMP/RET/TRAP/HALT
pub may_trap: bool, // runtime trap possible
pub may_trap: bool, // runtime trap possible
/// Marks this opcode as a VM safepoint. Used by GC/scheduler policies.
pub is_safepoint: bool,
}
pub trait OpCodeSpecExt {
fn spec(&self) -> OpcodeSpec;
/// These instructions cannot be verified from slot-only FunctionMeta.
fn requires_registry(&self) -> bool {
self.spec().pops.is_none() || self.spec().pushes.is_none()
}
}
impl OpCodeSpecExt for OpCode {
@@ -25,8 +31,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Nop => OpcodeSpec {
name: "NOP",
imm_bytes: 0,
pops: 0,
pushes: 0,
pops: Some(0),
pushes: Some(0),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -35,8 +41,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Halt => OpcodeSpec {
name: "HALT",
imm_bytes: 0,
pops: 0,
pushes: 0,
pops: Some(0),
pushes: Some(0),
is_branch: false,
is_terminator: true,
may_trap: false,
@@ -45,8 +51,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Jmp => OpcodeSpec {
name: "JMP",
imm_bytes: 4,
pops: 0,
pushes: 0,
pops: Some(0),
pushes: Some(0),
is_branch: true,
is_terminator: true,
may_trap: false,
@@ -55,8 +61,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::JmpIfFalse => OpcodeSpec {
name: "JMP_IF_FALSE",
imm_bytes: 4,
pops: 1,
pushes: 0,
pops: Some(1),
pushes: Some(0),
is_branch: true,
is_terminator: false,
may_trap: true,
@@ -65,8 +71,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::JmpIfTrue => OpcodeSpec {
name: "JMP_IF_TRUE",
imm_bytes: 4,
pops: 1,
pushes: 0,
pops: Some(1),
pushes: Some(0),
is_branch: true,
is_terminator: false,
may_trap: true,
@@ -75,8 +81,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Trap => OpcodeSpec {
name: "TRAP",
imm_bytes: 0,
pops: 0,
pushes: 0,
pops: Some(0),
pushes: Some(0),
is_branch: false,
is_terminator: true,
may_trap: true,
@@ -85,8 +91,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::PushConst => OpcodeSpec {
name: "PUSH_CONST",
imm_bytes: 4,
pops: 0,
pushes: 1,
pops: Some(0),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -95,8 +101,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Pop => OpcodeSpec {
name: "POP",
imm_bytes: 0,
pops: 1,
pushes: 0,
pops: Some(1),
pushes: Some(0),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -105,8 +111,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::PopN => OpcodeSpec {
name: "POP_N",
imm_bytes: 4,
pops: 0,
pushes: 0,
pops: Some(0),
pushes: Some(0),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -115,8 +121,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Dup => OpcodeSpec {
name: "DUP",
imm_bytes: 0,
pops: 1,
pushes: 2,
pops: Some(1),
pushes: Some(2),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -125,8 +131,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Swap => OpcodeSpec {
name: "SWAP",
imm_bytes: 0,
pops: 2,
pushes: 2,
pops: Some(2),
pushes: Some(2),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -135,8 +141,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::PushI64 => OpcodeSpec {
name: "PUSH_I64",
imm_bytes: 8,
pops: 0,
pushes: 1,
pops: Some(0),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -145,8 +151,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::PushF64 => OpcodeSpec {
name: "PUSH_F64",
imm_bytes: 8,
pops: 0,
pushes: 1,
pops: Some(0),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -155,8 +161,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::PushBool => OpcodeSpec {
name: "PUSH_BOOL",
imm_bytes: 1,
pops: 0,
pushes: 1,
pops: Some(0),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -165,8 +171,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::PushI32 => OpcodeSpec {
name: "PUSH_I32",
imm_bytes: 4,
pops: 0,
pushes: 1,
pops: Some(0),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -175,8 +181,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Add => OpcodeSpec {
name: "ADD",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: true,
@@ -185,8 +191,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Sub => OpcodeSpec {
name: "SUB",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: true,
@@ -195,8 +201,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Mul => OpcodeSpec {
name: "MUL",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: true,
@@ -205,8 +211,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Div => OpcodeSpec {
name: "DIV",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: true,
@@ -215,8 +221,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Mod => OpcodeSpec {
name: "MOD",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: true,
@@ -225,8 +231,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Eq => OpcodeSpec {
name: "EQ",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -235,8 +241,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Neq => OpcodeSpec {
name: "NEQ",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -245,8 +251,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Lt => OpcodeSpec {
name: "LT",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -255,8 +261,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Gt => OpcodeSpec {
name: "GT",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -265,8 +271,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::And => OpcodeSpec {
name: "AND",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -275,8 +281,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Or => OpcodeSpec {
name: "OR",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -285,8 +291,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Not => OpcodeSpec {
name: "NOT",
imm_bytes: 0,
pops: 1,
pushes: 1,
pops: Some(1),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -295,8 +301,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::BitAnd => OpcodeSpec {
name: "BIT_AND",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -305,8 +311,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::BitOr => OpcodeSpec {
name: "BIT_OR",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -315,8 +321,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::BitXor => OpcodeSpec {
name: "BIT_XOR",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -325,8 +331,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Shl => OpcodeSpec {
name: "SHL",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -335,8 +341,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Shr => OpcodeSpec {
name: "SHR",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -345,8 +351,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Lte => OpcodeSpec {
name: "LTE",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -355,8 +361,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Gte => OpcodeSpec {
name: "GTE",
imm_bytes: 0,
pops: 2,
pushes: 1,
pops: Some(2),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -365,8 +371,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Neg => OpcodeSpec {
name: "NEG",
imm_bytes: 0,
pops: 1,
pushes: 1,
pops: Some(1),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -375,8 +381,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::GetGlobal => OpcodeSpec {
name: "GET_GLOBAL",
imm_bytes: 4,
pops: 0,
pushes: 1,
pops: Some(0),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -385,8 +391,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::SetGlobal => OpcodeSpec {
name: "SET_GLOBAL",
imm_bytes: 4,
pops: 1,
pushes: 0,
pops: Some(1),
pushes: Some(0),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -395,8 +401,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::GetLocal => OpcodeSpec {
name: "GET_LOCAL",
imm_bytes: 4,
pops: 0,
pushes: 1,
pops: Some(0),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -405,8 +411,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::SetLocal => OpcodeSpec {
name: "SET_LOCAL",
imm_bytes: 4,
pops: 1,
pushes: 0,
pops: Some(1),
pushes: Some(0),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -415,8 +421,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Call => OpcodeSpec {
name: "CALL",
imm_bytes: 4,
pops: 0,
pushes: 0,
pops: Some(0),
pushes: Some(0),
is_branch: false,
is_terminator: false,
may_trap: true,
@@ -425,8 +431,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Ret => OpcodeSpec {
name: "RET",
imm_bytes: 0,
pops: 0,
pushes: 0,
pops: Some(0),
pushes: Some(0),
is_branch: false,
is_terminator: true,
may_trap: false,
@@ -437,8 +443,8 @@ impl OpCodeSpecExt for OpCode {
// Two u32 immediates: fn_id and capture_count
imm_bytes: 8,
// Dynamic, depends on capture_count; keep 0 here for verifier-free spec
pops: 0,
pushes: 1,
pops: Some(0),
pushes: Some(1),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -449,8 +455,8 @@ impl OpCodeSpecExt for OpCode {
// One u32 immediate: arg_count (user args, excludes hidden arg0)
imm_bytes: 4,
// Dynamic: pops closure_ref + arg_count; keep 0 in spec layer
pops: 0,
pushes: 0,
pops: Some(0),
pushes: Some(0),
is_branch: false,
is_terminator: false,
may_trap: true,
@@ -461,8 +467,8 @@ impl OpCodeSpecExt for OpCode {
// Two u32 immediates: fn_id and arg_count
imm_bytes: 8,
// Dynamic pops depends on arg_count; keep 0 here in spec layer
pops: 0,
pushes: 0,
pops: Some(0),
pushes: Some(0),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -471,8 +477,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Yield => OpcodeSpec {
name: "YIELD",
imm_bytes: 0,
pops: 0,
pushes: 0,
pops: Some(0),
pushes: Some(0),
is_branch: false,
// Not a block terminator; effect realized at safepoint
is_terminator: false,
@@ -484,8 +490,8 @@ impl OpCodeSpecExt for OpCode {
name: "SLEEP",
// One u32 immediate: duration_ticks
imm_bytes: 4,
pops: 0,
pushes: 0,
pops: Some(0),
pushes: Some(0),
is_branch: false,
// Ends execution at safepoint after instruction completes
is_terminator: false,
@@ -496,8 +502,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Hostcall => OpcodeSpec {
name: "HOSTCALL",
imm_bytes: 4,
pops: 0,
pushes: 0,
pops: Some(0),
pushes: Some(0),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -506,8 +512,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::Syscall => OpcodeSpec {
name: "SYSCALL",
imm_bytes: 4,
pops: 0,
pushes: 0,
pops: Some(0),
pushes: Some(0),
is_branch: false,
is_terminator: false,
may_trap: true,
@@ -516,8 +522,78 @@ impl OpCodeSpecExt for OpCode {
OpCode::Intrinsic => OpcodeSpec {
name: "INTRINSIC",
imm_bytes: 4,
pops: 0,
pushes: 0,
pops: Some(0),
pushes: Some(0),
is_branch: false,
is_terminator: false,
may_trap: true,
is_safepoint: false,
},
OpCode::DynPack => OpcodeSpec {
name: "DYN_PACK",
imm_bytes: 4,
pops: None,
pushes: None,
is_branch: false,
is_terminator: false,
may_trap: true,
is_safepoint: false,
},
OpCode::DynUnpack => OpcodeSpec {
name: "DYN_UNPACK",
imm_bytes: 4,
pops: None,
pushes: None,
is_branch: false,
is_terminator: false,
may_trap: true,
is_safepoint: false,
},
OpCode::DynCanUnpack => OpcodeSpec {
name: "DYN_CAN_UNPACK",
imm_bytes: 4,
pops: None,
pushes: None,
is_branch: false,
is_terminator: false,
may_trap: true,
is_safepoint: false,
},
OpCode::RefIsExact => OpcodeSpec {
name: "REF_IS_EXACT",
imm_bytes: 8,
pops: None,
pushes: None,
is_branch: false,
is_terminator: false,
may_trap: true,
is_safepoint: false,
},
OpCode::RefImplements => OpcodeSpec {
name: "REF_IMPLEMENTS",
imm_bytes: 8,
pops: None,
pushes: None,
is_branch: false,
is_terminator: false,
may_trap: true,
is_safepoint: false,
},
OpCode::RefToTrait => OpcodeSpec {
name: "REF_TO_TRAIT",
imm_bytes: 8,
pops: None,
pushes: None,
is_branch: false,
is_terminator: false,
may_trap: true,
is_safepoint: false,
},
OpCode::RefCast => OpcodeSpec {
name: "REF_CAST",
imm_bytes: 8,
pops: None,
pushes: None,
is_branch: false,
is_terminator: false,
may_trap: true,
@@ -526,8 +602,8 @@ impl OpCodeSpecExt for OpCode {
OpCode::FrameSync => OpcodeSpec {
name: "FRAME_SYNC",
imm_bytes: 0,
pops: 0,
pushes: 0,
pops: Some(0),
pushes: Some(0),
is_branch: false,
is_terminator: false,
may_trap: false,
@@ -0,0 +1,607 @@
//! 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<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Signature {
pub parameters: Vec<NamedType>,
pub results: Vec<TypeId>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MethodDecl {
pub name: Option<String>,
pub signature: Signature,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TypeKind {
Builtin(BuiltinId),
Struct(Vec<NamedType>),
Array(TypeId),
Trait(Vec<MethodDecl>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypeDecl {
pub name: Option<String>,
pub kind: TypeKind,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FunctionDecl {
pub name: Option<String>,
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<FunctionId>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RegistryDeclarations {
pub types: Vec<TypeDecl>,
pub functions: Vec<FunctionDecl>,
pub implementations: Vec<ImplementationDecl>,
}
pub type StringSlot = Option<Arc<str>>;
#[derive(Debug, Clone)]
pub struct DynamicSlot {
pub type_id: Option<TypeId>,
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<StorageLayout, E> {
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::<StringSlot>(), align_of::<StringSlot>(), 1, O::NativeString, D::Null)
}
Self::DYNAMIC => {
(size_of::<DynamicSlot>(), align_of::<DynamicSlot>(), 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<FieldLayout>,
/// Sorted offsets for fields requiring guest tracing or native ownership handling.
pub owned_fields: Vec<OwnedField>,
}
#[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<StructLayout>,
pub array: Option<ArrayLayout>,
}
#[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<TypeLayout>,
functions: Vec<FunctionLayout>,
// 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<ImplementationId> {
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<Self, E> {
budget.transaction(|budget| Self::resolve_inner(declarations, code_len, budget))
}
fn resolve_inner(
d: RegistryDeclarations,
code_len: usize,
b: &mut LoadBudget,
) -> Result<Self, E> {
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<usize, E> {
n.checked_add(a - 1).map(|v| v & !(a - 1)).ok_or_else(overflow)
}
fn width(
ids: impl Iterator<Item = TypeId>,
layouts: &[TypeLayout],
b: &mut LoadBudget,
) -> Result<u32, E> {
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<String>, 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::<u8>(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<T>(v: &Vec<T>, b: &mut LoadBudget) -> Result<(), E> {
b.charge(
Q::RegistryBytes,
(v.capacity() as u64).checked_mul(size_of::<T>() as u64).ok_or_else(overflow)?,
)
}
fn charge_name(n: &Option<String>, b: &mut LoadBudget) -> Result<(), E> {
if let Some(n) = n {
b.charge(Q::RegistryBytes, n.capacity() as u64)?;
}
Ok(())
}
fn charge_named(v: &Vec<NamedType>, 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::<Registry>() 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(())
}
@@ -0,0 +1,473 @@
//! Strict PBX v1 envelope and Registry sections. No legacy fallback.
//! Envelope parsing is structural only: non-Registry sections and instructions
//! must be validated by their consumers before an executable image is published.
use crate::load_limits::{
LoadBudget, LoadCode as C, LoadFailure as E, LoadReason as R, LoadResource as Q,
};
use crate::registry::*;
#[derive(Debug, Clone, Copy)]
pub struct Section<'a> {
pub kind: u32,
pub offset: usize,
pub bytes: &'a [u8],
}
#[derive(Debug)]
pub struct PbxEnvelope<'a> {
sections: [Option<Section<'a>>; 8],
}
impl<'a> PbxEnvelope<'a> {
pub fn section(&self, kind: u32) -> Option<Section<'a>> {
self.sections.get(kind as usize).copied().flatten()
}
pub fn parse(bytes: &'a [u8], b: &mut LoadBudget) -> Result<Self, E> {
b.transaction(|b| Self::parse_inner(bytes, b))
}
fn parse_inner(bytes: &'a [u8], b: &mut LoadBudget) -> Result<Self, E> {
b.check(Q::PbxBytes, bytes.len() as u64)?;
if bytes.len() < 32 {
return Err(E::new(C::InvalidFormat, R::Truncated));
}
b.work(32)?;
if &bytes[..4] != b"PBX\0" {
return Err(E::new(C::InvalidFormat, R::Magic));
}
if bytes[4..6] != [1, 0] {
return Err(E::new(C::UnsupportedFormat, R::Version));
}
if bytes[6] != 0 {
return Err(E::new(C::InvalidFormat, R::Endianness));
}
if bytes[7] != 0 || bytes[12..32].iter().any(|&x| x != 0) {
return Err(E::new(C::InvalidFormat, R::Reserved));
}
let count = u32::from_le_bytes(bytes[8..12].try_into().unwrap()) as usize;
let directory_end =
count.checked_mul(12).and_then(|n| n.checked_add(32)).ok_or_else(overflow)?;
if directory_end > bytes.len() {
return Err(E::new(C::InvalidFormat, R::Truncated));
}
let mut result = Self { sections: [None; 8] };
for i in 0..count {
b.work(13)?;
let pos = 32 + i * 12;
let kind = u32::from_le_bytes(bytes[pos..pos + 4].try_into().unwrap());
if kind > 7 {
return Err(E::new(C::UnsupportedFormat, R::SectionKind).at(kind, pos));
}
if result.sections[kind as usize].is_some() {
return Err(E::new(C::InvalidFormat, R::DuplicateSection).at(kind, pos));
}
let start = u32::from_le_bytes(bytes[pos + 4..pos + 8].try_into().unwrap()) as usize;
let len = u32::from_le_bytes(bytes[pos + 8..pos + 12].try_into().unwrap()) as usize;
let end = start.checked_add(len).ok_or_else(overflow)?;
if end > bytes.len() {
return Err(E::new(C::InvalidFormat, R::Truncated).at(kind, start));
}
if start < directory_end {
return Err(E::new(C::InvalidFormat, R::Overlap).at(kind, start));
}
if kind == 2 {
b.check(Q::CodeBytes, len as u64)?;
}
for other in result.sections.iter().flatten() {
b.work(1)?;
if len > 0
&& !other.bytes.is_empty()
&& start < other.offset + other.bytes.len()
&& other.offset < end
{
return Err(E::new(C::InvalidFormat, R::Overlap).at(kind, start));
}
}
result.sections[kind as usize] =
Some(Section { kind, offset: start, bytes: &bytes[start..end] });
}
for kind in [0, 1, 2, 4, 5, 6, 7] {
if result.sections[kind].is_none() {
return Err(E::new(C::InvalidFormat, R::MissingSection).at(kind as u32, 8));
}
}
Ok(result)
}
/// Decode and resolve Registry metadata only. This is not an executable loader.
pub fn resolve_registry(&self, b: &mut LoadBudget) -> Result<Registry, E> {
b.transaction(|b| {
let resources = [
Q::TemporaryBytes,
Q::Types,
Q::Functions,
Q::Implementations,
Q::NestedRecords,
Q::NameBytes,
];
let before = resources.map(|r| b.used(r));
let types = Reader::new(self.section(6).unwrap(), b).types()?;
let functions = Reader::new(self.section(1).unwrap(), b).functions()?;
let implementations = Reader::new(self.section(7).unwrap(), b).implementations()?;
// Ownership moves from parse scratch to retained Registry. No clone or
// simultaneous second declaration allocation occurs at this boundary.
for (r, used) in resources.into_iter().zip(before) {
b.refund(r, b.used(r) - used);
}
Registry::resolve(
RegistryDeclarations { types, functions, implementations },
self.section(2).unwrap().bytes.len(),
b,
)
})
}
}
fn overflow() -> E {
E::new(C::ResourceLimit, R::Overflow)
}
struct Reader<'a, 'b> {
section: Section<'a>,
pos: usize,
budget: &'b mut LoadBudget,
}
impl<'a, 'b> Reader<'a, 'b> {
fn new(section: Section<'a>, budget: &'b mut LoadBudget) -> Self {
Self { section, pos: 0, budget }
}
fn error(&self, code: C, reason: R) -> E {
E::new(code, reason).at(self.section.kind, self.section.offset + self.pos)
}
fn take(&mut self, n: usize) -> Result<&'a [u8], E> {
let end = self.pos.checked_add(n).ok_or_else(overflow)?;
let value = self
.section
.bytes
.get(self.pos..end)
.ok_or_else(|| self.error(C::InvalidFormat, R::Truncated))?;
self.budget.work(n)?;
self.pos = end;
Ok(value)
}
fn byte(&mut self) -> Result<u8, E> {
Ok(self.take(1)?[0])
}
fn u32(&mut self) -> Result<u32, E> {
Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap()))
}
fn finish(&self) -> Result<(), E> {
if self.pos == self.section.bytes.len() {
Ok(())
} else {
Err(self.error(C::InvalidFormat, R::TrailingBytes))
}
}
fn list<T>(&mut self, resource: Q, min_bytes: usize) -> Result<(Vec<T>, usize), E> {
let count = self.u32()? as usize;
self.budget.charge(resource, count as u64)?;
let min = count.checked_mul(min_bytes).ok_or_else(overflow)?;
if min > self.section.bytes.len() - self.pos {
return Err(self.error(C::InvalidFormat, R::Truncated));
}
Ok((self.budget.vector(count, Q::TemporaryBytes)?, count))
}
fn name(&mut self) -> Result<Option<String>, E> {
match self.byte()? {
0 => Ok(None),
1 => {
let len = self.u32()? as usize;
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.budget.charge(Q::NameBytes, len as u64)?;
let bytes = self.take(len)?;
self.budget.work(len)?;
let value = std::str::from_utf8(bytes)
.map_err(|_| self.error(C::InvalidFormat, R::Utf8))?;
self.budget.work(len)?;
let mut storage = self.budget.vector::<u8>(len, Q::TemporaryBytes)?;
storage.extend_from_slice(value.as_bytes());
// UTF-8 was checked above; moving Vec into String performs no allocation.
Ok(Some(
String::from_utf8(storage)
.map_err(|_| self.error(C::InvalidFormat, R::Utf8))?,
))
}
_ => Err(self.error(C::InvalidFormat, R::InvalidFlag)),
}
}
fn named(&mut self) -> Result<Vec<NamedType>, E> {
let (mut out, n) = self.list(Q::NestedRecords, 5)?;
for i in 0..n {
self.budget.work(1)?;
let type_id = TypeId(self.u32()?);
let name = self.name().map_err(|e| e.member(i as u32))?;
out.push(NamedType { type_id, name });
}
Ok(out)
}
fn signature(&mut self) -> Result<Signature, E> {
let parameters = self.named()?;
let (mut results, n) = self.list(Q::NestedRecords, 4)?;
for _ in 0..n {
self.budget.work(1)?;
results.push(TypeId(self.u32()?));
}
Ok(Signature { parameters, results })
}
fn types(mut self) -> Result<Vec<TypeDecl>, E> {
let (mut out, n) = self.list(Q::Types, 6)?;
for i in 0..n {
self.budget.work(1)?;
let record = (|| {
let kind = self.byte()?;
let name = self.name()?;
let kind = match kind {
0 => TypeKind::Builtin(BuiltinId(self.u32()?)),
1 => TypeKind::Struct(self.named()?),
2 => TypeKind::Array(TypeId(self.u32()?)),
3 => {
let (mut methods, n) = self.list(Q::NestedRecords, 9)?;
for j in 0..n {
self.budget.work(1)?;
let name = self.name()?;
let signature = self.signature().map_err(|e| e.member(j as u32))?;
methods.push(MethodDecl { name, signature });
}
TypeKind::Trait(methods)
}
_ => return Err(self.error(C::UnsupportedFormat, R::Category)),
};
Ok(TypeDecl { name, kind })
})()
.map_err(|e: E| e.record(i as u32))?;
out.push(record);
}
self.finish()?;
Ok(out)
}
fn functions(mut self) -> Result<Vec<FunctionDecl>, E> {
let (mut out, n) = self.list(Q::Functions, 25)?;
for i in 0..n {
self.budget.work(1)?;
let f = (|| {
Ok(FunctionDecl {
name: self.name()?,
signature: self.signature()?,
code_offset: self.u32()?,
code_len: self.u32()?,
local_slots: self.u32()?,
max_stack_slots: self.u32()?,
})
})()
.map_err(|e: E| e.record(i as u32))?;
out.push(f);
}
self.finish()?;
Ok(out)
}
fn implementations(mut self) -> Result<Vec<ImplementationDecl>, E> {
let (mut out, n) = self.list(Q::Implementations, 12)?;
for i in 0..n {
self.budget.work(1)?;
let imp = (|| {
let owner = TypeId(self.u32()?);
let trait_id = TypeId(self.u32()?);
let (mut methods, n) = self.list(Q::NestedRecords, 4)?;
for _ in 0..n {
self.budget.work(1)?;
methods.push(FunctionId(self.u32()?));
}
Ok(ImplementationDecl { owner, trait_id, methods })
})()
.map_err(|e: E| e.record(i as u32))?;
out.push(imp);
}
self.finish()?;
Ok(out)
}
}
/// Raw section input for a v1 envelope writer. Non-Registry section bytes must
/// come from their own validated writers; this API never invents defaults.
#[derive(Clone, Copy)]
pub struct SectionData<'a> {
pub kind: u32,
pub bytes: &'a [u8],
}
/// Assemble strict v1 sections. The output buffer is charged to temporary load storage.
pub fn encode_envelope(sections: &[SectionData<'_>], b: &mut LoadBudget) -> Result<Vec<u8>, E> {
b.transaction(|b| {
let mut by_kind = [None; 8];
for section in sections {
b.work(1)?;
if section.kind > 7 {
return Err(E::new(C::UnsupportedFormat, R::SectionKind));
}
if by_kind[section.kind as usize].replace(section.bytes).is_some() {
return Err(E::new(C::InvalidFormat, R::DuplicateSection));
}
}
for k in [0, 1, 2, 4, 5, 6, 7] {
if by_kind[k].is_none() {
return Err(E::new(C::InvalidFormat, R::MissingSection).at(k as u32, 8));
}
}
b.check(Q::CodeBytes, by_kind[2].unwrap().len() as u64)?;
let count = sections.len();
let directory_end = 32 + 12 * count;
let total = sections
.iter()
.try_fold(directory_end, |n, s| n.checked_add(s.bytes.len()).ok_or_else(overflow))?;
b.check(Q::PbxBytes, total as u64)?;
b.work(total)?;
let mut out = b.vector(total, Q::TemporaryBytes)?;
out.extend_from_slice(b"PBX\0");
out.extend_from_slice(&[1, 0, 0, 0]);
out.extend_from_slice(&(count as u32).to_le_bytes());
out.extend_from_slice(&[0; 20]);
let mut offset = directory_end;
for (kind, data) in by_kind.iter().enumerate() {
if let Some(data) = data {
out.extend_from_slice(&(kind as u32).to_le_bytes());
out.extend_from_slice(&(offset as u32).to_le_bytes());
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
offset += data.len();
}
}
for data in by_kind.into_iter().flatten() {
out.extend_from_slice(data);
}
Ok(out)
})
}
#[derive(Debug)]
pub struct RegistrySections {
pub types: Vec<u8>,
pub functions: Vec<u8>,
pub implementations: Vec<u8>,
}
/// Field-by-field serialization of already resolved Registry declarations.
/// There is no source-language inference or unsupported-value-to-null fallback.
pub fn encode_registry(registry: &Registry, b: &mut LoadBudget) -> Result<RegistrySections, E> {
b.transaction(|b| {
let d = registry.declarations();
let types = write_section(b, |w| {
w.count(d.types.len())?;
for t in &d.types {
w.byte(match t.kind {
TypeKind::Builtin(_) => 0,
TypeKind::Struct(_) => 1,
TypeKind::Array(_) => 2,
TypeKind::Trait(_) => 3,
})?;
w.name(&t.name)?;
match &t.kind {
TypeKind::Builtin(id) => w.u32(id.0)?,
TypeKind::Struct(fields) => w.named(fields)?,
TypeKind::Array(id) => w.u32(id.0)?,
TypeKind::Trait(methods) => {
w.count(methods.len())?;
for m in methods {
w.name(&m.name)?;
w.signature(&m.signature)?;
}
}
}
}
Ok(())
})?;
let functions = write_section(b, |w| {
w.count(d.functions.len())?;
for f in &d.functions {
w.name(&f.name)?;
w.signature(&f.signature)?;
w.u32(f.code_offset)?;
w.u32(f.code_len)?;
w.u32(f.local_slots)?;
w.u32(f.max_stack_slots)?;
}
Ok(())
})?;
let implementations = write_section(b, |w| {
w.count(d.implementations.len())?;
for imp in &d.implementations {
w.u32(imp.owner.0)?;
w.u32(imp.trait_id.0)?;
w.count(imp.methods.len())?;
for id in &imp.methods {
w.u32(id.0)?;
}
}
Ok(())
})?;
Ok(RegistrySections { types, functions, implementations })
})
}
// Count first so a malicious producer cannot trigger unbounded geometric growth.
struct Writer<'a> {
out: Option<&'a mut Vec<u8>>,
len: usize,
budget: &'a mut LoadBudget,
}
impl Writer<'_> {
fn bytes(&mut self, bytes: &[u8]) -> Result<(), E> {
self.budget.work(bytes.len())?;
self.len = self.len.checked_add(bytes.len()).ok_or_else(overflow)?;
self.budget.check(Q::PbxBytes, self.len as u64)?;
if let Some(out) = self.out.as_mut() {
out.extend_from_slice(bytes);
}
Ok(())
}
fn byte(&mut self, n: u8) -> Result<(), E> {
self.bytes(&[n])
}
fn u32(&mut self, n: u32) -> Result<(), E> {
self.bytes(&n.to_le_bytes())
}
fn count(&mut self, n: usize) -> Result<(), E> {
self.u32(u32::try_from(n).map_err(|_| overflow())?)
}
fn name(&mut self, n: &Option<String>) -> Result<(), E> {
match n {
None => self.byte(0),
Some(n) => {
self.byte(1)?;
self.count(n.len())?;
self.bytes(n.as_bytes())
}
}
}
fn named(&mut self, items: &[NamedType]) -> Result<(), E> {
self.count(items.len())?;
for p in items {
self.u32(p.type_id.0)?;
self.name(&p.name)?;
}
Ok(())
}
fn signature(&mut self, s: &Signature) -> Result<(), E> {
self.named(&s.parameters)?;
self.count(s.results.len())?;
for id in &s.results {
self.u32(id.0)?;
}
Ok(())
}
}
fn write_section(
b: &mut LoadBudget,
write: impl Fn(&mut Writer<'_>) -> Result<(), E>,
) -> Result<Vec<u8>, E> {
let mut counter = Writer { out: None, len: 0, budget: b };
write(&mut counter)?;
let len = counter.len;
let mut out = b.vector(len, Q::TemporaryBytes)?;
write(&mut Writer { out: Some(&mut out), len: 0, budget: b })?;
Ok(out)
}
mod payloads;
pub use payloads::ParsedPbx;
@@ -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(())
}
@@ -0,0 +1,83 @@
//! Registry-aware immediate validation and slot effects for typed instructions.
use crate::decoder::DecodedInstr;
use crate::isa::core::{CoreOpCode as Op, CoreOpCodeSpecExt};
use crate::load_limits::{IdDomain, LoadCode, LoadFailure, LoadReason};
use crate::registry::{Registry, TypeId, TypeKind};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RegistryStackEffect {
pub pops: u32,
pub pushes: u32,
}
impl DecodedInstr<'_> {
/// Resolve an instruction's exact group widths and check immediate domains.
/// None means this is not a Registry instruction, not a zero stack effect.
/// This does not prove that the values on the stack satisfy the signature.
pub fn registry_stack_effect(
&self,
registry: &Registry,
) -> Result<Option<RegistryStackEffect>, LoadFailure> {
if !self.opcode.requires_registry() {
return Ok(None);
}
let malformed = || {
let mut e = LoadFailure::new(LoadCode::InvalidCode, LoadReason::Truncated);
e.pc = u32::try_from(self.pc).ok();
e
};
let type_info = |id: u32| {
let decl = registry.declarations().types.get(id as usize);
let layout = registry.type_layout(TypeId(id));
decl.zip(layout).ok_or_else(|| {
let mut e = LoadFailure::new(LoadCode::InvalidReference, LoadReason::TypeId)
.reference(IdDomain::Type, id);
e.pc = u32::try_from(self.pc).ok();
e
})
};
let bad_category = |id: u32| {
let mut e = LoadFailure::new(LoadCode::InvalidReference, LoadReason::Category)
.reference(IdDomain::Type, id);
e.pc = u32::try_from(self.pc).ok();
e
};
let (pops, pushes) = match self.opcode {
Op::DynPack | Op::DynUnpack | Op::DynCanUnpack => {
let id = self.imm_u32().map_err(|_| malformed())?;
let (_, layout) = type_info(id)?;
match self.opcode {
Op::DynPack => (layout.storage.slots, 2),
Op::DynUnpack => (2, layout.storage.slots),
_ => (2, 1),
}
}
Op::RefIsExact | Op::RefImplements | Op::RefToTrait | Op::RefCast => {
let (source, target) = self.imm_u32x2().map_err(|_| malformed())?;
let (source_decl, source_layout) = type_info(source)?;
let (target_decl, target_layout) = type_info(target)?;
if !matches!(
source_decl.kind,
TypeKind::Struct(_) | TypeKind::Array(_) | TypeKind::Trait(_)
) {
return Err(bad_category(source));
}
let trait_target = matches!(self.opcode, Op::RefImplements | Op::RefToTrait);
if (trait_target && !matches!(target_decl.kind, TypeKind::Trait(_)))
|| (!trait_target
&& !matches!(target_decl.kind, TypeKind::Struct(_) | TypeKind::Array(_)))
{
return Err(bad_category(target));
}
let pushes = if matches!(self.opcode, Op::RefIsExact | Op::RefImplements) {
1
} else {
target_layout.storage.slots
};
(source_layout.storage.slots, pushes)
}
_ => unreachable!("requires_registry is defined by the typed opcode catalogue"),
};
Ok(Some(RegistryStackEffect { pops, pushes }))
}
}
+20 -9
View File
@@ -10,17 +10,28 @@ thread_local! {
/// Opaque handle that references an object stored in the VM heap.
///
/// This is an index-based handle. It does not imply ownership and carries
/// no lifetime information. GC/allocator integration will come in later PRs.
/// Handles belong to the heap/session that issued them. Native boundaries must
/// preserve that provenance. Generation zero is reserved; compact null is (0, 0).
#[repr(C, align(8))]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct HeapRef(pub u32);
pub struct HeapRef {
pub index: u32,
pub generation: u32,
}
impl HeapRef {
pub const NULL: Self = Self { index: 0, generation: 0 };
pub const fn is_null(self) -> bool {
self.index == 0 && self.generation == 0
}
}
/// Represents any piece of data that can be stored on the VM stack or in globals.
///
/// The PVM is "dynamically typed" at the bytecode level, meaning a single
/// `Value` enum can hold different primitive types. The VM performs
/// automatic type promotion (e.g., adding an Int32 to a Float64 results
/// in a Float64) to ensure mathematical correctness.
/// This enum is a physical carrier, not a semantic type declaration. Registry
/// boundaries validate exact types and complete multi-slot groups. Arithmetic
/// instructions may have their own numeric promotion rules; those rules do not
/// authorize implicit conversions at typed storage or call boundaries.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Value {
@@ -123,7 +134,7 @@ impl Value {
}
Value::String(s) => out.push_str(s),
Value::HeapRef(r) => {
let _ = write!(out, "[HeapRef {}]", r.0);
let _ = write!(out, "[HeapRef {}:{}]", r.index, r.generation);
}
Value::Null => out.push_str("null"),
}
@@ -138,7 +149,7 @@ impl Value {
Value::Int32(i) => i.to_string().len(),
Value::Int64(i) => i.to_string().len(),
Value::Float(f) => f.to_string().len(),
Value::HeapRef(r) => 11 + r.0.to_string().len(),
Value::HeapRef(r) => 11 + r.index.to_string().len() + r.generation.to_string().len(),
}
}