Files
prometeu-runtime/crates/console/prometeu-vm/src/registry_verifier/tests.rs
T

571 lines
20 KiB
Rust

use super::*;
use prometeu_bytecode::load_limits::LoadLimits;
use prometeu_bytecode::registry::{
BuiltinId as B, FunctionDecl, NamedType, RegistryDeclarations, Signature, TypeDecl, TypeId,
TypeKind,
};
fn op(code: &mut Vec<u8>, op: Op) {
code.extend_from_slice(&(op as u16).to_le_bytes());
}
fn arg(code: &mut Vec<u8>, op_code: Op, n: u32) {
op(code, op_code);
code.extend_from_slice(&n.to_le_bytes());
}
fn registry(code: &[u8], functions: Vec<FunctionDecl>) -> Registry {
Registry::resolve(
RegistryDeclarations {
types: vec![
TypeDecl { name: None, kind: TypeKind::Builtin(B::INT32) },
TypeDecl { name: None, kind: TypeKind::Builtin(B::VEC2) },
TypeDecl { name: None, kind: TypeKind::Struct(vec![]) },
TypeDecl { name: None, kind: TypeKind::Trait(vec![]) },
],
functions,
implementations: vec![],
},
code.len(),
&mut LoadBudget::new(Default::default()),
)
.unwrap()
}
fn function(code: &[u8]) -> FunctionDecl {
FunctionDecl { code_len: code.len() as u32, max_stack_slots: 4, ..Default::default() }
}
fn check(code: &[u8], registry: &Registry) -> Result<(), E> {
validate_registry_instructions(code, registry, 1, &mut LoadBudget::new(Default::default()))
}
fn stacks(code: &[u8], registry: &Registry) -> Result<(), E> {
validate_registry_stacks(code, registry, 1, &mut LoadBudget::new(Default::default()))
}
#[test]
fn stack_analysis_honors_literal_zero_and_wide_pop_operands() {
let mut code = vec![];
arg(&mut code, Op::PushI32, 0);
op(&mut code, Op::Halt);
let r = registry(&code, vec![FunctionDecl { max_stack_slots: 0, ..function(&code) }]);
let e = stacks(&code, &r).unwrap_err();
assert_eq!(
(e.reason, e.requested, e.limit, e.pc),
(R::StackOverflow, Some(1), Some(0), Some(0))
);
for count in [65_536, u32::MAX] {
let mut code = vec![];
arg(&mut code, Op::PopN, count);
let r = registry(&code, vec![function(&code)]);
let e = stacks(&code, &r).unwrap_err();
assert_eq!(
(e.reason, e.requested, e.limit),
(R::StackUnderflow, Some(0), Some(u64::from(count)))
);
}
}
#[test]
fn stack_analysis_cannot_consume_parameters_or_extra_locals_as_temporaries() {
let mut code = vec![];
op(&mut code, Op::Pop);
let r = registry(
&code,
vec![FunctionDecl {
local_slots: 100,
signature: Signature {
parameters: vec![NamedType { type_id: TypeId(1), name: None }],
results: vec![],
},
..function(&code)
}],
);
let e = stacks(&code, &r).unwrap_err();
assert_eq!((e.reason, e.pc), (R::StackUnderflow, Some(0)));
}
#[test]
fn stack_analysis_resolves_multislot_calls_and_registry_operations() {
let mut code = vec![];
for _ in 0..2 {
op(&mut code, Op::PushF64);
code.extend_from_slice(&0f64.to_le_bytes());
}
arg(&mut code, Op::DynPack, 1);
arg(&mut code, Op::DynUnpack, 1);
arg(&mut code, Op::Call, 1);
op(&mut code, Op::Halt);
let callee = code.len();
arg(&mut code, Op::GetLocal, 0);
arg(&mut code, Op::GetLocal, 1);
op(&mut code, Op::Ret);
let signature = Signature {
parameters: vec![NamedType { type_id: TypeId(1), name: None }],
results: vec![TypeId(1)],
};
let r = registry(
&code,
vec![
FunctionDecl { code_len: callee as u32, max_stack_slots: 2, ..function(&code) },
FunctionDecl {
code_offset: callee as u32,
code_len: (code.len() - callee) as u32,
signature,
max_stack_slots: 2,
..Default::default()
},
],
);
assert!(stacks(&code, &r).is_ok());
// This is a slot proof only, not validation of Runtime Dynamic boxes.
}
#[test]
fn stack_analysis_checks_returns_empty_bodies_and_implicit_end_branches() {
for operation in [Op::Ret, Op::Jmp] {
let mut code = vec![];
if operation == Op::Jmp {
arg(&mut code, operation, 6);
} else {
op(&mut code, operation);
}
let f = FunctionDecl {
signature: Signature { parameters: vec![], results: vec![TypeId(0)] },
..function(&code)
};
let r = registry(&code, vec![f]);
let e = stacks(&code, &r).unwrap_err();
assert_eq!((e.reason, e.requested, e.limit), (R::ReturnHeight, Some(0), Some(1)));
}
// Resolved Registries already reject empty declared function bodies.
let e = Registry::resolve(
RegistryDeclarations { functions: vec![Default::default()], ..Default::default() },
0,
&mut LoadBudget::new(Default::default()),
)
.unwrap_err();
assert_eq!(e.reason, R::CodeRange);
let r = registry(&[], vec![]);
assert!(stacks(&[], &r).is_ok());
let code = (Op::Nop as u16).to_le_bytes();
let r = registry(&code, vec![function(&code)]);
assert_eq!(stacks(&code, &r).unwrap_err().reason, R::UnterminatedPath);
}
#[test]
fn stack_analysis_rejects_different_join_heights_and_accepts_a_bounded_loop() {
let mut code = vec![];
op(&mut code, Op::PushBool);
code.push(1);
arg(&mut code, Op::JmpIfTrue, 21);
arg(&mut code, Op::PushI32, 0);
arg(&mut code, Op::Jmp, 23);
op(&mut code, Op::Nop);
op(&mut code, Op::Halt);
let r = registry(&code, vec![function(&code)]);
assert_eq!(stacks(&code, &r).unwrap_err().reason, R::StackJoin);
let mut code = vec![];
arg(&mut code, Op::Jmp, 0);
let r = registry(&code, vec![FunctionDecl { max_stack_slots: 0, ..function(&code) }]);
assert!(stacks(&code, &r).is_ok());
}
#[test]
fn stack_analysis_accounts_only_reachable_transfers_but_preflights_dead_operands() {
let mut code = vec![];
op(&mut code, Op::Halt);
arg(&mut code, Op::PopN, u32::MAX);
let r = registry(&code, vec![FunctionDecl { max_stack_slots: 0, ..function(&code) }]);
assert!(stacks(&code, &r).is_ok());
let mut code = vec![];
op(&mut code, Op::Halt);
arg(&mut code, Op::GetLocal, 0);
let r = registry(&code, vec![function(&code)]);
assert_eq!(stacks(&code, &r).unwrap_err().reason, R::LocalSlot);
}
#[test]
fn stack_analysis_refunds_all_state_buffers_and_preserves_prior_ownership() {
let mut code = vec![];
arg(&mut code, Op::PushI32, 0);
op(&mut code, Op::Halt);
let r = registry(&code, vec![function(&code)]);
let mut b = LoadBudget::new(Default::default());
b.charge(Q::TemporaryBytes, 7).unwrap();
b.charge(Q::RegistryBytes, 11).unwrap();
validate_registry_stacks(&code, &r, 1, &mut b).unwrap();
assert_eq!((b.used(Q::TemporaryBytes), b.used(Q::RegistryBytes)), (7, 11));
let mut limits = LoadLimits::default();
limits.temporary_bytes = 32; // Decode maps fit; CFG/state/work buffers cannot all fit.
let mut b = LoadBudget::new(limits);
b.charge(Q::TemporaryBytes, 7).unwrap();
let e = validate_registry_stacks(&code, &r, 1, &mut b).unwrap_err();
assert_eq!((e.code, e.resource), (C::ResourceLimit, Some(Q::TemporaryBytes)));
assert_eq!(b.used(Q::TemporaryBytes), 7);
assert_eq!((e.function, e.section), (Some(0), Some(2)));
}
#[test]
fn stack_analysis_straight_line_storage_is_bounded_by_blocks_not_instruction_frames() {
let mut code = Vec::new();
for _ in 0..20_000 {
op(&mut code, Op::Nop);
}
op(&mut code, Op::Halt);
let r = registry(
&code,
vec![FunctionDecl { local_slots: 300, max_stack_slots: 0, ..function(&code) }],
);
let mut limits = LoadLimits::default();
limits.temporary_bytes = 41_000;
let mut b = LoadBudget::new(limits);
validate_registry_stacks(&code, &r, 1, &mut b).unwrap();
assert_eq!(b.used(Q::TemporaryBytes), 0);
}
#[test]
fn stack_analysis_retains_unknown_closure_and_yield_safety_rules() {
let mut code = vec![];
arg(&mut code, Op::GetLocal, 0);
arg(&mut code, Op::CallClosure, 0);
op(&mut code, Op::Halt);
let f = FunctionDecl {
signature: Signature {
parameters: vec![NamedType { type_id: TypeId(0), name: None }],
results: vec![],
},
..function(&code)
};
let r = registry(&code, vec![f]);
assert_eq!(stacks(&code, &r).unwrap_err().reason, R::UnknownClosureCallee);
let mut code = vec![];
arg(&mut code, Op::GetLocal, 0);
arg(&mut code, Op::CallClosure, 0);
let r = registry(&code, vec![FunctionDecl { local_slots: 1, ..function(&code) }]);
assert_eq!(stacks(&code, &r).unwrap_err().reason, R::NotClosure);
let mut code = vec![];
arg(&mut code, Op::PushI32, 0);
op(&mut code, Op::Yield);
let r = registry(&code, vec![function(&code)]);
assert_eq!(stacks(&code, &r).unwrap_err().reason, R::InvalidYield);
}
#[test]
fn stack_analysis_preserves_closure_facts_through_permutations_before_rejecting_bad_arity() {
let mut code = vec![];
arg(&mut code, Op::PushI32, 0);
arg(&mut code, Op::MakeClosure, 1);
code.extend_from_slice(&0u32.to_le_bytes());
op(&mut code, Op::Swap);
op(&mut code, Op::Pop);
op(&mut code, Op::Dup);
op(&mut code, Op::Pop);
arg(&mut code, Op::SetLocal, 0);
arg(&mut code, Op::GetLocal, 0);
arg(&mut code, Op::CallClosure, 0);
op(&mut code, Op::Halt);
let end = code.len();
op(&mut code, Op::Ret);
let r = registry(
&code,
vec![
FunctionDecl {
code_len: end as u32,
local_slots: 1,
max_stack_slots: 2,
..function(&code)
},
FunctionDecl { code_offset: end as u32, code_len: 2, ..Default::default() },
],
);
let e = stacks(&code, &r).unwrap_err();
// The callee deliberately lacks hidden arg0: this fixture is rejected,
// and does not invent a typed descriptor for a valid guest closure.
assert_eq!((e.reason, e.referenced_id), (R::Signature, Some(1)));
assert_eq!((e.requested, e.limit), (Some(1), Some(0)));
}
#[test]
fn stack_analysis_checks_closure_counts_without_wraparound() {
for operation in [Op::MakeClosure, Op::CallClosure] {
let mut code = vec![];
if operation == Op::MakeClosure {
arg(&mut code, operation, 0);
code.extend_from_slice(&u32::MAX.to_le_bytes());
} else {
arg(&mut code, operation, u32::MAX);
}
op(&mut code, Op::Halt);
let r = registry(&code, vec![function(&code)]);
let e = stacks(&code, &r).unwrap_err();
assert_eq!(e.reason, R::StackUnderflow);
assert_eq!(e.limit, Some(u64::from(u32::MAX) + u64::from(operation == Op::CallClosure)));
}
}
#[test]
fn stack_analysis_charges_work_for_loop_reprocessing_and_refunds_on_exhaustion() {
let mut code = vec![];
arg(&mut code, Op::Jmp, 6);
arg(&mut code, Op::GetLocal, 0);
op(&mut code, Op::Pop);
arg(&mut code, Op::Call, 1);
arg(&mut code, Op::SetLocal, 0);
op(&mut code, Op::PushBool);
code.push(1);
arg(&mut code, Op::JmpIfTrue, 6);
op(&mut code, Op::Halt);
let end = code.len();
arg(&mut code, Op::PushI32, 1);
op(&mut code, Op::Ret);
let r = registry(
&code,
vec![
FunctionDecl {
code_len: end as u32,
local_slots: 1,
max_stack_slots: 1,
..function(&code)
},
FunctionDecl {
code_offset: end as u32,
code_len: (code.len() - end) as u32,
max_stack_slots: 1,
signature: Signature { parameters: vec![], results: vec![TypeId(0)] },
..Default::default()
},
],
);
let mut b = LoadBudget::new(Default::default());
validate_registry_stacks(&code, &r, 1, &mut b).unwrap();
let mut limits = LoadLimits::default();
limits.work = b.used(Q::Work) - 1;
let mut limited = LoadBudget::new(limits);
limited.charge(Q::TemporaryBytes, 7).unwrap();
let e = validate_registry_stacks(&code, &r, 1, &mut limited).unwrap_err();
assert_eq!((e.code, e.resource), (C::ResourceLimit, Some(Q::Work)));
assert_eq!((e.function, e.pc), (Some(1), Some((code.len() - 2) as u32)));
assert_eq!(limited.used(Q::TemporaryBytes), 7);
assert_eq!(limited.used(Q::Work), limits.work);
}
#[test]
fn typed_opcodes_and_relative_jumps_are_resolved_in_declared_ranges() {
let mut code = vec![];
op(&mut code, Op::Halt);
arg(&mut code, Op::DynPack, 1);
arg(&mut code, Op::DynUnpack, 1);
arg(&mut code, Op::DynCanUnpack, 1);
for (operation, target) in
[(Op::RefIsExact, 2), (Op::RefCast, 2), (Op::RefImplements, 3), (Op::RefToTrait, 3)]
{
arg(&mut code, operation, 2);
code.extend_from_slice(&(target as u32).to_le_bytes());
}
let start = code.len();
arg(&mut code, Op::Jmp, 6);
let r = registry(
&code,
vec![
FunctionDecl { code_len: start as u32, ..function(&code) },
FunctionDecl {
code_offset: start as u32,
code_len: 6,
max_stack_slots: 0,
..Default::default()
},
],
);
assert!(check(&code, &r).is_ok());
// This phase is structural: stack heights/type groups still need the next analysis.
}
#[test]
fn unreachable_bad_type_ids_and_categories_preserve_function_and_pc() {
for (operation, id) in [(Op::DynPack, 99), (Op::RefCast, 0)] {
let mut code = vec![];
op(&mut code, Op::Halt);
arg(&mut code, operation, id);
if operation == Op::RefCast {
code.extend_from_slice(&2_u32.to_le_bytes());
}
let r = registry(&code, vec![function(&code)]);
let e = check(&code, &r).unwrap_err();
assert_eq!(e.code, C::InvalidReference);
assert_eq!(e.function, Some(0));
assert_eq!(e.pc, Some(2));
assert_eq!(e.section, Some(2));
assert_eq!(e.referenced_id, Some(id));
}
}
#[test]
fn jumps_reject_cross_range_and_mid_instruction_even_when_unreachable() {
for (target, reason) in [(7, R::JumpTarget), (3, R::InstructionBoundary)] {
let mut code = vec![];
arg(&mut code, Op::Jmp, target);
op(&mut code, Op::Halt);
let r = registry(
&code,
vec![
FunctionDecl { code_len: 6, ..function(&code) },
FunctionDecl { code_offset: 6, code_len: 2, ..function(&code) },
],
);
let e = check(&code, &r).unwrap_err();
assert_eq!((e.code, e.reason, e.pc), (C::InvalidCode, reason, Some(0)));
}
}
#[test]
fn local_bounds_use_derived_parameter_widths_and_u32_local_counts() {
let mut code = vec![];
arg(&mut code, Op::GetLocal, 70);
let mut f = function(&code);
f.signature = Signature {
parameters: vec![NamedType { type_id: TypeId(1), name: None }],
results: vec![],
};
f.local_slots = 69; // vec2 contributes two parameter slots, total 71.
let r = registry(&code, vec![f.clone()]);
assert!(check(&code, &r).is_ok());
for slot in [71, 65_536, u32::MAX] {
let mut bad = vec![];
arg(&mut bad, Op::SetLocal, slot);
let e = check(&bad, &r).unwrap_err();
assert_eq!((e.reason, e.member), (R::LocalSlot, Some(slot)));
}
let mut limits = LoadLimits::default();
limits.frame_slots = 74;
let mut budget = LoadBudget::new(limits);
let e = validate_registry_instructions(&code, &r, 1, &mut budget).unwrap_err();
assert_eq!(e.reason, R::FrameSlots); // 2 parameters + 69 locals + 4 temporaries = 75.
assert_eq!(budget.used(Q::TemporaryBytes), 0);
}
#[test]
fn unreachable_function_constant_boolean_and_native_operands_are_checked() {
for (operation, id, reason) in [
(Op::Call, u32::MAX, R::FunctionId),
(Op::PushConst, 1, R::ConstantIndex),
(Op::Intrinsic, u32::MAX, R::NativeId),
(Op::Syscall, u32::MAX, R::NativeId),
(Op::Hostcall, 0, R::UnpatchedHostcall),
] {
let mut code = vec![];
op(&mut code, Op::Halt);
arg(&mut code, operation, id);
let r = registry(&code, vec![function(&code)]);
let e = check(&code, &r).unwrap_err();
assert_eq!((e.reason, e.pc, e.referenced_id), (reason, Some(2), Some(id)));
assert_eq!(
e.code,
if operation == Op::Hostcall { C::InvalidCode } else { C::InvalidReference }
);
}
let code = [
(Op::Halt as u16).to_le_bytes().as_slice(),
(Op::PushBool as u16).to_le_bytes().as_slice(),
&[2],
]
.concat();
let r = registry(&code, vec![function(&code)]);
assert_eq!(check(&code, &r).unwrap_err().reason, R::BooleanImmediate);
}
#[test]
fn spawn_arity_does_not_truncate_and_closure_function_ids_are_checked() {
for (operation, function_id, count, reason) in
[(Op::Spawn, 0, 65_536, R::Signature), (Op::MakeClosure, 1, 0, R::FunctionId)]
{
let mut code = vec![];
op(&mut code, Op::Halt);
arg(&mut code, operation, function_id);
code.extend_from_slice(&(count as u32).to_le_bytes());
let r = registry(&code, vec![function(&code)]);
assert_eq!(check(&code, &r).unwrap_err().reason, reason);
}
}
#[test]
fn declared_range_is_not_extended_into_gaps_or_neighbor_functions() {
let code = vec![Op::Halt as u8, 0, 0xff, 0xff];
let r = registry(&code, vec![FunctionDecl { code_len: 2, ..function(&code) }]);
assert!(check(&code, &r).is_ok()); // Unowned gap is outside this phase's ranges.
let r = registry(&code, vec![function(&code)]);
assert_eq!(check(&code, &r).unwrap_err().reason, R::UnknownOpcode);
let short = &code[..1];
assert_eq!(check(short, &r).unwrap_err().reason, R::CodeRange);
}
#[test]
fn scratch_is_refunded_per_function_and_preserves_prior_load_ownership() {
let code = vec![Op::Halt as u8, 0, Op::Halt as u8, 0];
let r = registry(
&code,
vec![
FunctionDecl { code_len: 2, ..function(&code) },
FunctionDecl { code_offset: 2, code_len: 2, ..function(&code) },
],
);
let mut limits = LoadLimits::default();
limits.temporary_bytes = 8;
let mut budget = LoadBudget::new(limits);
budget.charge(Q::TemporaryBytes, 5).unwrap();
budget.charge(Q::RegistryBytes, 10).unwrap();
validate_registry_instructions(&code, &r, 1, &mut budget).unwrap();
assert_eq!(budget.used(Q::TemporaryBytes), 5); // Both 3-byte maps fit separately.
assert_eq!(budget.used(Q::RegistryBytes), 10);
assert!(budget.used(Q::Work) > 0);
}
#[test]
fn scratch_and_work_exhaustion_fail_with_context_and_no_counter_leak() {
let code = vec![Op::Halt as u8, 0];
let r = registry(&code, vec![function(&code)]);
for limits in [
LoadLimits { temporary_bytes: 2, ..Default::default() },
LoadLimits { work: 4, ..Default::default() },
] {
let mut budget = LoadBudget::new(limits);
let e = validate_registry_instructions(&code, &r, 1, &mut budget).unwrap_err();
assert_eq!(e.code, C::ResourceLimit);
assert_eq!(e.function, Some(0));
assert_eq!(e.pc, Some(0));
assert_eq!(budget.used(Q::TemporaryBytes), 0);
assert!(budget.used(Q::Work) <= budget.limit(Q::Work));
}
}
#[test]
fn truncated_immediates_cannot_borrow_bytes_from_the_next_function() {
let code = vec![Op::PushI64 as u8, 0, Op::Halt as u8, 0];
let r = registry(
&code,
vec![
FunctionDecl { code_len: 2, ..function(&code) },
FunctionDecl { code_offset: 2, code_len: 2, ..function(&code) },
],
);
let e = check(&code, &r).unwrap_err();
assert_eq!((e.code, e.reason, e.pc), (C::InvalidCode, R::Truncated, Some(0)));
}
#[test]
fn native_lookup_work_refusal_retains_the_actual_instruction_pc() {
let mut code = vec![];
op(&mut code, Op::Halt);
arg(&mut code, Op::Intrinsic, 0x2100);
let r = registry(&code, vec![function(&code)]);
assert!(check(&code, &r).is_ok()); // Known input query, even in unreachable code.
// One function + nine initialized map bytes + two decoding passes and
// boundary writes consume 33 units before the first catalogue record.
let limits = LoadLimits { work: 33, ..Default::default() };
let mut budget = LoadBudget::new(limits);
let e = validate_registry_instructions(&code, &r, 1, &mut budget).unwrap_err();
assert_eq!(
(e.code, e.resource, e.function, e.pc),
(C::ResourceLimit, Some(Q::Work), Some(0), Some(2))
);
assert_eq!(budget.used(Q::TemporaryBytes), 0);
assert_eq!(budget.used(Q::Work), 33);
}