feat(vm): publish validated shared PBX v1 images for PLN-0176 step 14
This commit is contained in:
@@ -17,7 +17,7 @@ pub struct ProgramImage {
|
||||
pub rom: Arc<[u8]>,
|
||||
pub constant_pool: Arc<[Value]>,
|
||||
pub functions: Arc<[FunctionMeta]>,
|
||||
pub debug_info: Option<DebugInfo>,
|
||||
pub debug_info: Option<Arc<DebugInfo>>,
|
||||
pub exports: Arc<HashMap<String, u32>>,
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ impl ProgramImage {
|
||||
rom: Arc::from(rom),
|
||||
constant_pool: Arc::from(constant_pool),
|
||||
functions: Arc::from(functions),
|
||||
debug_info,
|
||||
debug_info: debug_info.map(Arc::new),
|
||||
exports: Arc::new(exports),
|
||||
}
|
||||
}
|
||||
@@ -116,7 +116,7 @@ impl From<ProgramImage> for BytecodeModule {
|
||||
const_pool,
|
||||
functions: program.functions.as_ref().to_vec(),
|
||||
code: program.rom.as_ref().to_vec(),
|
||||
debug_info: program.debug_info.clone(),
|
||||
debug_info: program.debug_info.as_deref().cloned(),
|
||||
exports,
|
||||
syscalls: Vec::new(),
|
||||
}
|
||||
|
||||
@@ -11,6 +11,12 @@ pub use resolver::{
|
||||
resolve_declared_program_syscalls, resolve_program_syscalls, resolve_syscall,
|
||||
};
|
||||
|
||||
/// Native metadata iteration for bounded image binding. This is not guest
|
||||
/// reflection; callers account comparisons before examining catalogue entries.
|
||||
pub fn catalogue() -> impl Iterator<Item = &'static SyscallRegistryEntry> {
|
||||
domains::all_entries()
|
||||
}
|
||||
|
||||
/// Enumeration of all System Calls (Syscalls) available in the Prometeu environment.
|
||||
///
|
||||
/// Syscalls are the primary mechanism for a program running in the Virtual Machine
|
||||
|
||||
@@ -9,9 +9,11 @@ mod object;
|
||||
pub mod resource_budget;
|
||||
mod roots;
|
||||
// Bounded Registry preflight is consumed by the upcoming v1 image loader.
|
||||
mod program_image;
|
||||
#[allow(dead_code)]
|
||||
mod registry_verifier;
|
||||
mod scheduler;
|
||||
pub use program_image::{ImageStringLease, ValidatedProgramImage};
|
||||
// Image/session creation and native provenance consume this in step 19.
|
||||
#[allow(dead_code)]
|
||||
mod string_ledger;
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
//! PBX v1 publication: immutable metadata and shared payload, after bindings
|
||||
//! and bounded whole-program verification. No public unchecked constructor.
|
||||
use crate::{LoaderPatchError, VmInitError};
|
||||
use prometeu_bytecode::isa::core::CoreOpCode as Op;
|
||||
use prometeu_bytecode::load_limits::{
|
||||
LoadBudget, LoadCode as C, LoadFailure as E, LoadReason as R, LoadResource as Q,
|
||||
};
|
||||
use prometeu_bytecode::model::{ConstantPoolEntry as K, DebugInfo, Export};
|
||||
use prometeu_bytecode::registry::{FunctionId, Registry};
|
||||
use prometeu_bytecode::registry_codec::OwnedPbx;
|
||||
use prometeu_bytecode::{FunctionMeta, ProgramImage, Value};
|
||||
use prometeu_hal::syscalls::{CapFlags, DeclaredLoadError, SyscallResolved};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
const DOMAINS: [Q; 11] = [
|
||||
Q::PbxBytes,
|
||||
Q::CodeBytes,
|
||||
Q::Types,
|
||||
Q::Functions,
|
||||
Q::Implementations,
|
||||
Q::NestedRecords,
|
||||
Q::NameBytes,
|
||||
Q::RegistryBytes,
|
||||
Q::TemporaryBytes,
|
||||
Q::ConstantEntries,
|
||||
Q::ConstantStringBytes,
|
||||
];
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ImageStrings {
|
||||
records: Vec<(Weak<str>, usize)>,
|
||||
bytes: u64,
|
||||
}
|
||||
impl ImageStrings {
|
||||
fn reconcile(&mut self) {
|
||||
self.records.retain(|(weak, len)| {
|
||||
if weak.strong_count() == 0 {
|
||||
self.bytes -= *len as u64;
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Native retention carries the image accounting domain with the content.
|
||||
/// This is provenance metadata, not a new guest string representation.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ImageStringLease {
|
||||
content: Arc<str>,
|
||||
domain: Arc<Mutex<ImageStrings>>,
|
||||
}
|
||||
impl ImageStringLease {
|
||||
pub fn content(&self) -> &Arc<str> {
|
||||
&self.content
|
||||
}
|
||||
pub fn retained_content(&self) -> (u64, usize) {
|
||||
let mut domain = self.domain.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
domain.reconcile();
|
||||
(domain.bytes, domain.records.len())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ValidatedProgramImage {
|
||||
registry: Arc<Registry>,
|
||||
pub(crate) execution: ProgramImage,
|
||||
exports: Vec<Export>,
|
||||
strings: Arc<Mutex<ImageStrings>>,
|
||||
registry_bytes: u64,
|
||||
payload_bytes: u64,
|
||||
capabilities: CapFlags,
|
||||
}
|
||||
impl ValidatedProgramImage {
|
||||
pub fn registry(&self) -> &Arc<Registry> {
|
||||
&self.registry
|
||||
}
|
||||
pub fn code(&self) -> &[u8] {
|
||||
&self.execution.rom
|
||||
}
|
||||
pub fn constants(&self) -> &[Value] {
|
||||
&self.execution.constant_pool
|
||||
}
|
||||
pub fn debug(&self) -> Option<&DebugInfo> {
|
||||
self.execution.debug_info.as_deref()
|
||||
}
|
||||
pub fn exports(&self) -> &[Export] {
|
||||
&self.exports
|
||||
}
|
||||
pub fn capabilities(&self) -> CapFlags {
|
||||
self.capabilities
|
||||
}
|
||||
/// Domain measurements are native capacities/content, not process RSS.
|
||||
pub fn registry_bytes(&self) -> u64 {
|
||||
self.registry_bytes
|
||||
}
|
||||
pub fn payload_bytes(&self) -> u64 {
|
||||
self.payload_bytes
|
||||
}
|
||||
pub fn lease_constant(&self, index: usize) -> Option<ImageStringLease> {
|
||||
let Value::String(content) = self.constants().get(index)? else { return None };
|
||||
Some(ImageStringLease { content: content.clone(), domain: self.strings.clone() })
|
||||
}
|
||||
pub fn retains_string(&self, content: &Arc<str>) -> bool {
|
||||
let strings = self.strings.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
strings.records.iter().any(|(weak, _)| std::ptr::eq(weak.as_ptr(), Arc::as_ptr(content)))
|
||||
}
|
||||
pub fn constant_content(&self) -> (u64, usize) {
|
||||
let mut strings = self.strings.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
strings.reconcile();
|
||||
(strings.bytes, strings.records.len())
|
||||
}
|
||||
/// Only this factory can publish an image. Unsupported versions have no
|
||||
/// fallback. The caller's input domain is separate from load scratch.
|
||||
pub fn load(
|
||||
bytes: &[u8],
|
||||
budget: &mut LoadBudget,
|
||||
capabilities: CapFlags,
|
||||
) -> Result<Arc<Self>, VmInitError> {
|
||||
let before = DOMAINS.map(|resource| budget.used(resource));
|
||||
let result = Self::load_inner(bytes, budget, capabilities);
|
||||
// Failure drops partial owners before this rollback; success transfers
|
||||
// scratch-owned payload into the measured immutable image domain.
|
||||
for (resource, old) in DOMAINS.into_iter().zip(before) {
|
||||
if result.is_err() || resource == Q::TemporaryBytes {
|
||||
budget.refund(resource, budget.used(resource) - old);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
fn load_inner(
|
||||
bytes: &[u8],
|
||||
b: &mut LoadBudget,
|
||||
capabilities: CapFlags,
|
||||
) -> Result<Arc<Self>, VmInitError> {
|
||||
let payload_before = b.used(Q::TemporaryBytes);
|
||||
let registry_before = b.used(Q::RegistryBytes);
|
||||
let mut module = OwnedPbx::parse(bytes, b)?;
|
||||
if module.registry.declarations().functions.is_empty() {
|
||||
return Err(E::new(C::InvalidEntrypoint, R::FunctionId).in_function(0, None).into());
|
||||
}
|
||||
bind(&mut module, b, capabilities)?;
|
||||
crate::registry_verifier::validate_registry_types(
|
||||
&module.code,
|
||||
&module.registry,
|
||||
&module.constants,
|
||||
b,
|
||||
)?;
|
||||
|
||||
let mut functions =
|
||||
scratch::<FunctionMeta>(module.registry.declarations().functions.len(), b)?;
|
||||
for (index, f) in module.registry.declarations().functions.iter().enumerate() {
|
||||
b.work(1)?;
|
||||
let slots = module.registry.function_layout(FunctionId(index as u32)).unwrap();
|
||||
// The accepted 16,384-slot frame/1,024-slot result ceilings prove
|
||||
// these cached execution widths fit; no serialized field narrows.
|
||||
let narrow = |n| {
|
||||
u16::try_from(n).map_err(|_| {
|
||||
E::new(C::InvalidCode, R::FrameSlots)
|
||||
.in_function(index as u32, Some(f.code_offset))
|
||||
})
|
||||
};
|
||||
functions.push(FunctionMeta {
|
||||
code_offset: f.code_offset,
|
||||
code_len: f.code_len,
|
||||
param_slots: narrow(slots.parameter_slots)?,
|
||||
local_slots: narrow(f.local_slots)?,
|
||||
return_slots: narrow(slots.result_slots)?,
|
||||
max_stack_slots: narrow(f.max_stack_slots)?,
|
||||
});
|
||||
}
|
||||
let constants_capacity = (module.constants.capacity() * size_of::<K>()) as u64;
|
||||
b.work(module.constants.len())?;
|
||||
let string_count = module.constants.iter().filter(|c| matches!(c, K::String(_))).count();
|
||||
let mut records = scratch::<(Weak<str>, usize)>(string_count, b)?;
|
||||
let mut values = scratch::<Value>(module.constants.len(), b)?;
|
||||
let mut content_bytes = 0;
|
||||
for constant in module.constants {
|
||||
b.work(1)?;
|
||||
let value = match constant {
|
||||
K::Null => Value::Null,
|
||||
K::Int32(v) => Value::Int32(v),
|
||||
K::Int64(v) => Value::Int64(v),
|
||||
K::Float64(v) => Value::Float(v),
|
||||
K::Boolean(v) => Value::Boolean(v),
|
||||
K::String(text) => {
|
||||
arc_charge::<u8>(text.len(), b, Q::TemporaryBytes)?;
|
||||
b.work(text.len())?;
|
||||
let content: Arc<str> = Arc::from(text.as_str());
|
||||
content_bytes += text.len() as u64;
|
||||
records.push((Arc::downgrade(&content), text.len()));
|
||||
b.refund(Q::TemporaryBytes, text.capacity() as u64);
|
||||
Value::String(content)
|
||||
}
|
||||
};
|
||||
values.push(value);
|
||||
}
|
||||
b.refund(Q::TemporaryBytes, constants_capacity);
|
||||
// Binding no longer needs source declarations. They were validated,
|
||||
// used exactly, and can be released before final payload publication.
|
||||
b.work(module.syscalls.len())?;
|
||||
let syscall_bytes = (module.syscalls.capacity()
|
||||
* size_of::<prometeu_bytecode::SyscallDecl>()) as u64
|
||||
+ module
|
||||
.syscalls
|
||||
.iter()
|
||||
.map(|d| (d.module.capacity() + d.name.capacity()) as u64)
|
||||
.sum::<u64>();
|
||||
drop(module.syscalls);
|
||||
b.refund(Q::TemporaryBytes, syscall_bytes);
|
||||
let rom = shared_slice(module.code, b)?;
|
||||
let constant_pool = shared_slice(values, b)?;
|
||||
let functions = shared_slice(functions, b)?;
|
||||
let debug_info = if let Some(debug) = module.debug {
|
||||
arc_charge::<DebugInfo>(1, b, Q::TemporaryBytes)?;
|
||||
Some(Arc::new(debug))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Export vectors retain source order; lookup can preserve the existing
|
||||
// last-declaration-wins native entry behavior without another HashMap.
|
||||
arc_charge::<Mutex<ImageStrings>>(1, b, Q::TemporaryBytes)?;
|
||||
let strings = Arc::new(Mutex::new(ImageStrings { records, bytes: content_bytes }));
|
||||
arc_charge::<Registry>(1, b, Q::RegistryBytes)?;
|
||||
let registry = Arc::new(module.registry);
|
||||
arc_charge::<Self>(1, b, Q::TemporaryBytes)?;
|
||||
arc_charge::<HashMap<String, u32>>(1, b, Q::TemporaryBytes)?;
|
||||
let registry_bytes = b.used(Q::RegistryBytes) - registry_before;
|
||||
let payload_bytes = b.used(Q::TemporaryBytes) - payload_before;
|
||||
let execution = ProgramImage {
|
||||
rom,
|
||||
constant_pool,
|
||||
functions,
|
||||
debug_info,
|
||||
exports: Arc::new(HashMap::new()),
|
||||
};
|
||||
Ok(Arc::new(Self {
|
||||
registry,
|
||||
execution,
|
||||
exports: module.exports,
|
||||
strings,
|
||||
registry_bytes,
|
||||
payload_bytes,
|
||||
capabilities,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn scratch<T>(count: usize, b: &mut LoadBudget) -> Result<Vec<T>, E> {
|
||||
let bytes = count
|
||||
.checked_mul(size_of::<T>())
|
||||
.ok_or_else(|| E::new(C::ResourceLimit, R::Overflow))? as u64;
|
||||
b.charge(Q::TemporaryBytes, bytes)?;
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(count).map_err(|_| {
|
||||
let mut e = E::resource(Q::TemporaryBytes, bytes, b.limit(Q::TemporaryBytes));
|
||||
e.reason = R::Allocation;
|
||||
e
|
||||
})?;
|
||||
b.charge(Q::TemporaryBytes, (out.capacity() - count) as u64 * size_of::<T>() as u64)?;
|
||||
Ok(out)
|
||||
}
|
||||
fn arc_charge<T>(count: usize, b: &mut LoadBudget, resource: Q) -> Result<(), E> {
|
||||
let align = align_of::<T>().max(align_of::<usize>());
|
||||
let bytes = count
|
||||
.checked_mul(size_of::<T>())
|
||||
.and_then(|n| n.checked_add(2 * size_of::<usize>() + align - 1))
|
||||
.map(|n| n / align * align)
|
||||
.ok_or_else(|| E::new(C::ResourceLimit, R::Overflow))?;
|
||||
b.charge(resource, bytes as u64)
|
||||
}
|
||||
fn shared_slice<T>(items: Vec<T>, b: &mut LoadBudget) -> Result<Arc<[T]>, E> {
|
||||
arc_charge::<T>(items.len(), b, Q::TemporaryBytes)?;
|
||||
b.work(items.len())?;
|
||||
let capacity = (items.capacity() * size_of::<T>()) as u64;
|
||||
let shared = Arc::from(items);
|
||||
b.refund(Q::TemporaryBytes, capacity);
|
||||
Ok(shared)
|
||||
}
|
||||
fn same_text(left: &str, right: &str, b: &mut LoadBudget) -> Result<bool, E> {
|
||||
b.work(1)?;
|
||||
if left.len() != right.len() {
|
||||
return Ok(false);
|
||||
}
|
||||
for (a, c) in left.bytes().zip(right.bytes()) {
|
||||
b.work(2)?;
|
||||
if a != c {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
fn diagnostic_text(text: &str, b: &mut LoadBudget) -> Result<String, E> {
|
||||
let mut bytes = scratch(text.len(), b)?;
|
||||
b.work(text.len())?;
|
||||
bytes.extend_from_slice(text.as_bytes());
|
||||
Ok(String::from_utf8(bytes).expect("declaration text is UTF-8"))
|
||||
}
|
||||
fn patch_error(error: LoaderPatchError) -> VmInitError {
|
||||
VmInitError::LoaderPatchFailed(error)
|
||||
}
|
||||
fn bind(module: &mut OwnedPbx, b: &mut LoadBudget, caps: CapFlags) -> Result<(), VmInitError> {
|
||||
let before = b.used(Q::TemporaryBytes);
|
||||
let result = (|| {
|
||||
let mut resolved = scratch::<SyscallResolved>(module.syscalls.len(), b)?;
|
||||
let mut used = scratch::<bool>(module.syscalls.len(), b)?;
|
||||
b.work(module.syscalls.len())?;
|
||||
used.resize(module.syscalls.len(), false);
|
||||
for decl in &module.syscalls {
|
||||
let mut found = None;
|
||||
for entry in prometeu_hal::syscalls::catalogue() {
|
||||
b.work(1)?;
|
||||
if entry.meta.version == decl.version
|
||||
&& same_text(entry.meta.module, &decl.module, b)?
|
||||
&& same_text(entry.meta.name, &decl.name, b)?
|
||||
{
|
||||
found = Some(SyscallResolved { id: entry.meta.id, meta: entry.meta });
|
||||
break;
|
||||
}
|
||||
}
|
||||
let native_error = if let Some(value) = found {
|
||||
if value.meta.caps & !caps != 0 {
|
||||
Some(DeclaredLoadError::MissingCapability {
|
||||
required: value.meta.caps,
|
||||
provided: caps,
|
||||
module: diagnostic_text(&decl.module, b)?,
|
||||
name: diagnostic_text(&decl.name, b)?,
|
||||
version: decl.version,
|
||||
})
|
||||
} else if decl.arg_slots != value.meta.arg_slots as u16
|
||||
|| decl.ret_slots != value.meta.ret_slots
|
||||
{
|
||||
Some(DeclaredLoadError::AbiMismatch {
|
||||
module: diagnostic_text(&decl.module, b)?,
|
||||
name: diagnostic_text(&decl.name, b)?,
|
||||
version: decl.version,
|
||||
declared_arg_slots: decl.arg_slots,
|
||||
declared_ret_slots: decl.ret_slots,
|
||||
expected_arg_slots: value.meta.arg_slots as u16,
|
||||
expected_ret_slots: value.meta.ret_slots,
|
||||
})
|
||||
} else {
|
||||
resolved.push(value);
|
||||
None
|
||||
}
|
||||
} else {
|
||||
Some(DeclaredLoadError::UnknownSyscall {
|
||||
module: diagnostic_text(&decl.module, b)?,
|
||||
name: diagnostic_text(&decl.name, b)?,
|
||||
version: decl.version,
|
||||
})
|
||||
};
|
||||
if let Some(error) = native_error {
|
||||
return Err(patch_error(LoaderPatchError::ResolveFailed(error)));
|
||||
}
|
||||
}
|
||||
for (id, function) in module.registry.declarations().functions.iter().enumerate() {
|
||||
let mut pc = function.code_offset as usize;
|
||||
let end = pc + function.code_len as usize;
|
||||
while pc < end {
|
||||
let instruction = (|| {
|
||||
b.work(2)?;
|
||||
let instruction = prometeu_bytecode::decode_next(pc, &module.code[..end])
|
||||
.map_err(|e| {
|
||||
E::new(
|
||||
C::InvalidCode,
|
||||
if matches!(e, prometeu_bytecode::DecodeError::UnknownOpcode { .. })
|
||||
{
|
||||
R::UnknownOpcode
|
||||
} else {
|
||||
R::Truncated
|
||||
},
|
||||
)
|
||||
})?;
|
||||
b.work(instruction.imm.len() + 1)?;
|
||||
Ok(instruction)
|
||||
})()
|
||||
.map_err(|e: E| e.in_section(2).in_function(id as u32, Some(pc as u32)))?;
|
||||
let next = instruction.next_pc;
|
||||
match instruction.opcode {
|
||||
Op::Hostcall => {
|
||||
let index = instruction.imm_u32().unwrap();
|
||||
let syscall = resolved.get(index as usize).ok_or_else(|| {
|
||||
patch_error(LoaderPatchError::HostcallIndexOutOfBounds {
|
||||
pc,
|
||||
sysc_index: index,
|
||||
syscalls_len: resolved.len(),
|
||||
})
|
||||
})?;
|
||||
b.work(7)?;
|
||||
used[index as usize] = true;
|
||||
module.code[pc..pc + 2]
|
||||
.copy_from_slice(&(Op::Syscall as u16).to_le_bytes());
|
||||
module.code[pc + 2..pc + 6].copy_from_slice(&syscall.id.to_le_bytes());
|
||||
}
|
||||
Op::Syscall => {
|
||||
return Err(patch_error(LoaderPatchError::RawSyscallInPreloadArtifact {
|
||||
pc,
|
||||
syscall_id: instruction.imm_u32().unwrap(),
|
||||
}));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
pc = next;
|
||||
}
|
||||
}
|
||||
for (index, (decl, used)) in module.syscalls.iter().zip(&used).enumerate() {
|
||||
b.work(1)?;
|
||||
if !used {
|
||||
return Err(patch_error(LoaderPatchError::UnusedSyscallDecl {
|
||||
sysc_index: index as u32,
|
||||
module: diagnostic_text(&decl.module, b)?,
|
||||
name: diagnostic_text(&decl.name, b)?,
|
||||
version: decl.version,
|
||||
}));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
b.refund(Q::TemporaryBytes, b.used(Q::TemporaryBytes) - before);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,216 @@
|
||||
use super::*;
|
||||
use prometeu_bytecode::load_limits::LoadLimits;
|
||||
use prometeu_bytecode::registry::{
|
||||
BuiltinId, FunctionDecl, RegistryDeclarations, TypeDecl, TypeKind,
|
||||
};
|
||||
use prometeu_bytecode::registry_codec::PbxModule;
|
||||
use prometeu_bytecode::{SourceSpan, SyscallDecl};
|
||||
use prometeu_hal::syscalls::{Syscall, caps, meta_for};
|
||||
|
||||
fn budget() -> LoadBudget {
|
||||
LoadBudget::new(LoadLimits::default())
|
||||
}
|
||||
|
||||
fn fixture(
|
||||
code: &[u8],
|
||||
max: u32,
|
||||
constants: &[K],
|
||||
debug: Option<&DebugInfo>,
|
||||
syscalls: &[SyscallDecl],
|
||||
) -> Vec<u8> {
|
||||
let registry = Registry::resolve(
|
||||
RegistryDeclarations {
|
||||
types: vec![TypeDecl {
|
||||
name: Some("boolean".into()),
|
||||
kind: TypeKind::Builtin(BuiltinId::BOOL),
|
||||
}],
|
||||
functions: vec![FunctionDecl {
|
||||
name: Some("boot".into()),
|
||||
code_len: code.len() as u32,
|
||||
max_stack_slots: max,
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
code.len(),
|
||||
&mut budget(),
|
||||
)
|
||||
.unwrap();
|
||||
PbxModule { registry: ®istry, code, constants, debug, exports: &[], syscalls }
|
||||
.serialize(&mut budget())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn has_cart() -> SyscallDecl {
|
||||
let m = meta_for(Syscall::SystemHasCart);
|
||||
SyscallDecl {
|
||||
module: m.module.into(),
|
||||
name: m.name.into(),
|
||||
version: m.version,
|
||||
arg_slots: m.arg_slots as u16,
|
||||
ret_slots: m.ret_slots,
|
||||
}
|
||||
}
|
||||
|
||||
fn hostcall_code() -> Vec<u8> {
|
||||
let mut code = (Op::Hostcall as u16).to_le_bytes().to_vec();
|
||||
code.extend_from_slice(&0u32.to_le_bytes());
|
||||
code.extend_from_slice(&(Op::Pop as u16).to_le_bytes());
|
||||
code.extend_from_slice(&(Op::Halt as u16).to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publication_shares_owners_and_preserves_payload_bits_and_names() {
|
||||
let debug = DebugInfo {
|
||||
pc_to_span: vec![(0, SourceSpan { file_id: 7, start: 2, end: 3 })],
|
||||
function_names: vec![(0, "debug boot".into())],
|
||||
};
|
||||
let constants = [
|
||||
K::Null,
|
||||
K::String("é猫".into()),
|
||||
K::String(String::new()),
|
||||
K::Float64(f64::from_bits(0x7ff8000000000042)),
|
||||
K::Float64(-0.0),
|
||||
];
|
||||
let bytes = fixture(&[1, 0], 0, &constants, Some(&debug), &[]);
|
||||
let mut b = budget();
|
||||
b.charge(Q::TemporaryBytes, 7).unwrap();
|
||||
let image = ValidatedProgramImage::load(&bytes, &mut b, caps::NONE).unwrap();
|
||||
assert_eq!(b.used(Q::TemporaryBytes), 7);
|
||||
assert!(image.payload_bytes() > 0 && image.registry_bytes() > 0);
|
||||
assert_eq!(image.registry().declarations().functions[0].name.as_deref(), Some("boot"));
|
||||
assert_eq!(image.execution.functions[0].max_stack_slots, 0);
|
||||
assert_eq!(image.constant_content(), (5, 2));
|
||||
assert!(image.lease_constant(0).is_none());
|
||||
let Value::Float(nan) = image.constants()[3] else { panic!() };
|
||||
let Value::Float(zero) = image.constants()[4] else { panic!() };
|
||||
assert_eq!(nan.to_bits(), 0x7ff8000000000042);
|
||||
assert_eq!(zero.to_bits(), (-0.0f64).to_bits());
|
||||
let projection = image.execution.clone();
|
||||
assert!(Arc::ptr_eq(&projection.rom, &image.execution.rom));
|
||||
assert!(Arc::ptr_eq(&projection.constant_pool, &image.execution.constant_pool));
|
||||
assert!(Arc::ptr_eq(
|
||||
projection.debug_info.as_ref().unwrap(),
|
||||
image.execution.debug_info.as_ref().unwrap()
|
||||
));
|
||||
assert_eq!(image.debug().unwrap().function_names[0].1, "debug boot");
|
||||
let lease = image.lease_constant(1).unwrap();
|
||||
let Value::String(text) = &image.constants()[1] else { panic!() };
|
||||
assert!(Arc::ptr_eq(text, lease.content()));
|
||||
drop(bytes);
|
||||
drop(projection);
|
||||
drop(image);
|
||||
assert_eq!(lease.content().as_ref(), "é猫");
|
||||
assert_eq!(lease.retained_content(), (5, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binding_precedes_publication_and_does_not_mutate_input() {
|
||||
let code = hostcall_code();
|
||||
let bytes = fixture(&code, 1, &[], None, &[has_cart()]);
|
||||
let original = bytes.clone();
|
||||
let image = ValidatedProgramImage::load(&bytes, &mut budget(), caps::SYSTEM).unwrap();
|
||||
assert_eq!(bytes, original);
|
||||
assert_eq!(&image.code()[..2], &(Op::Syscall as u16).to_le_bytes());
|
||||
assert_eq!(&image.code()[2..6], &(Syscall::SystemHasCart as u32).to_le_bytes());
|
||||
assert_eq!(image.capabilities(), caps::SYSTEM);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_binding_errors_keep_identity_and_roll_back_image_ownership() {
|
||||
let code = hostcall_code();
|
||||
let mut unknown = has_cart();
|
||||
unknown.name = "missing".into();
|
||||
let mut abi = has_cart();
|
||||
abi.ret_slots = 2;
|
||||
for (decl, caps, expected) in
|
||||
[(unknown, caps::SYSTEM, 0), (has_cart(), caps::NONE, 1), (abi, caps::SYSTEM, 2)]
|
||||
{
|
||||
let bytes = fixture(&code, 1, &[], None, &[decl]);
|
||||
let mut b = budget();
|
||||
b.charge(Q::TemporaryBytes, 7).unwrap();
|
||||
b.charge(Q::RegistryBytes, 3).unwrap();
|
||||
let error = ValidatedProgramImage::load(&bytes, &mut b, caps).unwrap_err();
|
||||
let VmInitError::LoaderPatchFailed(LoaderPatchError::ResolveFailed(error)) = error else {
|
||||
panic!("{error:?}")
|
||||
};
|
||||
assert!(matches!(
|
||||
(expected, error),
|
||||
(0, DeclaredLoadError::UnknownSyscall { .. })
|
||||
| (1, DeclaredLoadError::MissingCapability { .. })
|
||||
| (2, DeclaredLoadError::AbiMismatch { .. })
|
||||
));
|
||||
assert_eq!(b.used(Q::TemporaryBytes), 7);
|
||||
assert_eq!(b.used(Q::RegistryBytes), 3);
|
||||
assert_eq!(b.used(Q::Functions), 0);
|
||||
assert_eq!(b.used(Q::ConstantEntries), 0);
|
||||
assert!(b.used(Q::Work) > 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_or_unbound_calls_cannot_reach_an_image() {
|
||||
let mut raw = hostcall_code();
|
||||
raw[..2].copy_from_slice(&(Op::Syscall as u16).to_le_bytes());
|
||||
let mut out_of_bounds = hostcall_code();
|
||||
out_of_bounds[2..6].copy_from_slice(&1u32.to_le_bytes());
|
||||
for (code, decls, kind) in [
|
||||
(&raw[..], vec![], 0),
|
||||
(&out_of_bounds[..], vec![has_cart()], 1),
|
||||
(&[1, 0][..], vec![has_cart()], 2),
|
||||
] {
|
||||
let bytes = fixture(code, 1, &[], None, &decls);
|
||||
let error = ValidatedProgramImage::load(&bytes, &mut budget(), caps::SYSTEM).unwrap_err();
|
||||
assert!(matches!(
|
||||
(kind, error),
|
||||
(
|
||||
0,
|
||||
VmInitError::LoaderPatchFailed(
|
||||
LoaderPatchError::RawSyscallInPreloadArtifact { .. }
|
||||
)
|
||||
) | (
|
||||
1,
|
||||
VmInitError::LoaderPatchFailed(LoaderPatchError::HostcallIndexOutOfBounds { .. })
|
||||
) | (2, VmInitError::LoaderPatchFailed(LoaderPatchError::UnusedSyscallDecl { .. }))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verification_rejects_unreachable_bad_instructions_and_underflow() {
|
||||
let pop = (Op::Pop as u16).to_le_bytes();
|
||||
for code in [&pop[..], &[1, 0, 0xff, 0xff][..]] {
|
||||
let bytes = fixture(code, 0, &[], None, &[]);
|
||||
let mut b = budget();
|
||||
let VmInitError::RegistryLoadFailed(error) =
|
||||
ValidatedProgramImage::load(&bytes, &mut b, caps::NONE).unwrap_err()
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(error.function, Some(0));
|
||||
assert_eq!(b.used(Q::RegistryBytes), 0);
|
||||
assert_eq!(b.used(Q::TemporaryBytes), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn late_work_refusal_releases_all_new_owners() {
|
||||
let bytes = fixture(&[1, 0], 0, &[K::String("abc".into())], None, &[]);
|
||||
let mut full = budget();
|
||||
ValidatedProgramImage::load(&bytes, &mut full, caps::NONE).unwrap();
|
||||
let mut b =
|
||||
LoadBudget::new(LoadLimits { work: full.used(Q::Work) - 1, ..Default::default() });
|
||||
b.charge(Q::TemporaryBytes, 7).unwrap();
|
||||
b.charge(Q::RegistryBytes, 3).unwrap();
|
||||
let VmInitError::RegistryLoadFailed(error) =
|
||||
ValidatedProgramImage::load(&bytes, &mut b, caps::NONE).unwrap_err()
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(error.resource, Some(Q::Work));
|
||||
assert_eq!(b.used(Q::TemporaryBytes), 7);
|
||||
assert_eq!(b.used(Q::RegistryBytes), 3);
|
||||
assert_eq!(b.used(Q::ConstantStringBytes), 0);
|
||||
assert_eq!(b.used(Q::PbxBytes), 0);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ pub enum LoaderPatchError {
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum VmInitError {
|
||||
RegistryLoadFailed(prometeu_bytecode::load_limits::LoadFailure),
|
||||
RuntimeResourceLimit(crate::resource_budget::ResourceFailure),
|
||||
InvalidFormat,
|
||||
UnsupportedFormat,
|
||||
@@ -18,3 +19,9 @@ pub enum VmInitError {
|
||||
EntrypointNotFound,
|
||||
VerificationFailed(crate::verifier::VerifierError),
|
||||
}
|
||||
|
||||
impl From<prometeu_bytecode::load_limits::LoadFailure> for VmInitError {
|
||||
fn from(value: prometeu_bytecode::load_limits::LoadFailure) -> Self {
|
||||
Self::RegistryLoadFailed(value)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user