feat(verifier): add bounded stack analysis for PLN-0176 step 24
This commit is contained in:
@@ -70,6 +70,14 @@ pub enum LoadReason {
|
||||
ConstantIndex,
|
||||
NativeId,
|
||||
UnpatchedHostcall,
|
||||
StackUnderflow,
|
||||
StackOverflow,
|
||||
StackJoin,
|
||||
ReturnHeight,
|
||||
UnterminatedPath,
|
||||
UnknownClosureCallee,
|
||||
NotClosure,
|
||||
InvalidYield,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[repr(usize)]
|
||||
|
||||
@@ -209,3 +209,8 @@ fn reference_error(mut e: E) -> E {
|
||||
e.code = C::InvalidReference;
|
||||
e
|
||||
}
|
||||
|
||||
mod heights;
|
||||
// The executable v1 loader is the pending production consumer.
|
||||
#[allow(unused_imports)]
|
||||
pub(crate) use heights::validate_registry_stacks;
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
//! Bounded basic-block stack analysis. This does not publish an image or prove
|
||||
//! semantic argument types. Closure target facts preserve the existing known
|
||||
//! callee restriction; no guest callable descriptor is invented here.
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Fact {
|
||||
Unknown,
|
||||
NonClosure,
|
||||
Closure(u32),
|
||||
}
|
||||
struct Block {
|
||||
start: usize,
|
||||
end: usize,
|
||||
state: Option<Vec<Fact>>,
|
||||
queued: bool,
|
||||
}
|
||||
|
||||
pub(crate) fn validate_registry_stacks(
|
||||
code: &[u8],
|
||||
registry: &Registry,
|
||||
constants: usize,
|
||||
budget: &mut LoadBudget,
|
||||
) -> Result<(), E> {
|
||||
validate_registry_instructions(code, registry, constants, budget)?;
|
||||
let before = budget.used(Q::TemporaryBytes);
|
||||
let result = (|| {
|
||||
for (id, function) in registry.declarations().functions.iter().enumerate() {
|
||||
let function_before = budget.used(Q::TemporaryBytes);
|
||||
budget
|
||||
.work(1)
|
||||
.map_err(|e| e.in_section(2).in_function(id as u32, Some(function.code_offset)))?;
|
||||
let start = function.code_offset as usize;
|
||||
let body = &code[start..start + function.code_len as usize];
|
||||
let mut at_pc = 0;
|
||||
let result = analyze(body, registry, id as u32, budget, &mut at_pc)
|
||||
.map_err(|e| e.in_section(2).in_function(id as u32, Some((start + at_pc) as u32)));
|
||||
// analyze has dropped all blocks, states and the worklist here.
|
||||
budget.refund(Q::TemporaryBytes, budget.used(Q::TemporaryBytes) - function_before);
|
||||
result?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
budget.refund(Q::TemporaryBytes, budget.used(Q::TemporaryBytes) - before);
|
||||
result
|
||||
}
|
||||
|
||||
fn analyze(
|
||||
body: &[u8],
|
||||
registry: &Registry,
|
||||
id: u32,
|
||||
budget: &mut LoadBudget,
|
||||
at_pc: &mut usize,
|
||||
) -> Result<(), E> {
|
||||
let function = ®istry.declarations().functions[id as usize];
|
||||
let layout = registry.function_layout(FunctionId(id)).unwrap();
|
||||
let locals = layout.parameter_slots as usize + function.local_slots as usize;
|
||||
let max = function.max_stack_slots as usize;
|
||||
let results = layout.result_slots as usize;
|
||||
if body.is_empty() {
|
||||
return if results == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(count_error(R::ReturnHeight, 0, results as u64))
|
||||
};
|
||||
}
|
||||
|
||||
// A dense leader map is bounded by code bytes. States are retained at
|
||||
// basic-block entries, so a long straight-line program needs one state,
|
||||
// rather than one full frame snapshot per instruction.
|
||||
let mut leaders = scratch::<u8>(body.len() + 1, budget)?;
|
||||
budget.work(body.len() + 2)?;
|
||||
leaders.resize(body.len() + 1, 0);
|
||||
leaders[0] = 1;
|
||||
let mut pc = 0;
|
||||
while pc < body.len() {
|
||||
*at_pc = pc;
|
||||
let instruction = metered_decode(pc, body, budget)?;
|
||||
let spec = instruction.opcode.spec();
|
||||
if spec.is_branch {
|
||||
budget.work(1)?;
|
||||
leaders[instruction.imm_u32().unwrap() as usize] = 1;
|
||||
}
|
||||
if spec.is_branch || spec.is_terminator {
|
||||
budget.work(1)?;
|
||||
leaders[instruction.next_pc] = 1;
|
||||
}
|
||||
pc = instruction.next_pc;
|
||||
}
|
||||
budget.work(body.len())?;
|
||||
let count = leaders[..body.len()].iter().filter(|&&mark| mark != 0).count();
|
||||
let mut blocks = scratch::<Block>(count, budget)?;
|
||||
budget.work(body.len())?;
|
||||
for (pc, &mark) in leaders[..body.len()].iter().enumerate() {
|
||||
if mark == 0 {
|
||||
continue;
|
||||
}
|
||||
budget.work(2)?;
|
||||
if let Some(previous) = blocks.last_mut() {
|
||||
previous.end = pc;
|
||||
}
|
||||
blocks.push(Block { start: pc, end: body.len(), state: None, queued: false });
|
||||
}
|
||||
let leader_bytes = leaders.capacity() as u64;
|
||||
drop(leaders);
|
||||
budget.refund(Q::TemporaryBytes, leader_bytes);
|
||||
|
||||
let mut initial = scratch::<Fact>(locals, budget)?;
|
||||
budget.work(locals)?;
|
||||
initial.resize(locals, Fact::NonClosure); // Additional locals start Null.
|
||||
budget.work(layout.parameter_slots as usize)?;
|
||||
initial[..layout.parameter_slots as usize].fill(Fact::Unknown);
|
||||
blocks[0].state = Some(initial);
|
||||
let mut worklist = scratch::<usize>(count, budget)?;
|
||||
budget.work(2)?;
|
||||
blocks[0].queued = true;
|
||||
worklist.push(0);
|
||||
let total = locals.checked_add(max).ok_or_else(|| E::new(C::ResourceLimit, R::Overflow))?;
|
||||
let mut working = scratch::<Fact>(total, budget)?;
|
||||
budget.work(total)?;
|
||||
working.resize(total, Fact::Unknown);
|
||||
|
||||
while let Some(index) = worklist.pop() {
|
||||
*at_pc = blocks[index].start;
|
||||
budget.work(3)?;
|
||||
blocks[index].queued = false;
|
||||
let input = blocks[index].state.as_ref().unwrap();
|
||||
budget.work(input.len().checked_mul(2).ok_or_else(overflow)?)?;
|
||||
working[..input.len()].copy_from_slice(input);
|
||||
let mut height = input.len() - locals;
|
||||
let end = blocks[index].end;
|
||||
pc = blocks[index].start;
|
||||
while pc < end {
|
||||
*at_pc = pc;
|
||||
let instruction = metered_decode(pc, body, budget)?;
|
||||
budget.work(1)?; // Instruction transfer, independently of decoding.
|
||||
let spec = instruction.opcode.spec();
|
||||
let mut effect = if instruction.opcode.requires_registry() {
|
||||
budget.work(
|
||||
if matches!(instruction.opcode, Op::DynPack | Op::DynUnpack | Op::DynCanUnpack)
|
||||
{
|
||||
2
|
||||
} else {
|
||||
4
|
||||
},
|
||||
)?;
|
||||
let effect = instruction.registry_stack_effect(registry)?.unwrap();
|
||||
(u64::from(effect.pops), u64::from(effect.pushes))
|
||||
} else {
|
||||
(u64::from(spec.pops.unwrap()), u64::from(spec.pushes.unwrap()))
|
||||
};
|
||||
match instruction.opcode {
|
||||
Op::PopN => effect = (u64::from(instruction.imm_u32().unwrap()), 0),
|
||||
Op::MakeClosure => effect = (u64::from(instruction.imm_u32x2().unwrap().1), 1),
|
||||
Op::Spawn => effect = (u64::from(instruction.imm_u32x2().unwrap().1), 0),
|
||||
Op::Call => {
|
||||
budget.work(1)?;
|
||||
let callee = registry
|
||||
.function_layout(FunctionId(instruction.imm_u32().unwrap()))
|
||||
.unwrap();
|
||||
effect = (u64::from(callee.parameter_slots), u64::from(callee.result_slots));
|
||||
}
|
||||
Op::CallClosure => {
|
||||
let arguments = u64::from(instruction.imm_u32().unwrap());
|
||||
if (height as u64) < arguments + 1 {
|
||||
return Err(count_error(R::StackUnderflow, height as u64, arguments + 1));
|
||||
}
|
||||
budget.work(2)?;
|
||||
let target = match working[locals + height - 1] {
|
||||
Fact::Closure(target) => target,
|
||||
Fact::NonClosure => return Err(E::new(C::InvalidCode, R::NotClosure)),
|
||||
Fact::Unknown => {
|
||||
return Err(E::new(C::InvalidCode, R::UnknownClosureCallee));
|
||||
}
|
||||
};
|
||||
let callee = registry.function_layout(FunctionId(target)).unwrap();
|
||||
if u64::from(callee.parameter_slots) != arguments + 1 {
|
||||
return Err(count_error(
|
||||
R::Signature,
|
||||
arguments + 1,
|
||||
u64::from(callee.parameter_slots),
|
||||
)
|
||||
.reference(IdDomain::Function, target));
|
||||
}
|
||||
effect = (arguments + 1, u64::from(callee.result_slots));
|
||||
}
|
||||
Op::Ret => {
|
||||
if height != results {
|
||||
return Err(count_error(R::ReturnHeight, height as u64, results as u64));
|
||||
}
|
||||
effect = (results as u64, 0);
|
||||
}
|
||||
Op::Syscall => {
|
||||
budget.work(1)?;
|
||||
let native =
|
||||
prometeu_hal::syscalls::Syscall::from_u32(instruction.imm_u32().unwrap())
|
||||
.unwrap();
|
||||
effect = (native.args_count() as u64, native.results_count() as u64);
|
||||
}
|
||||
Op::Intrinsic => {
|
||||
let native = crate::builtins::metered_lookup_intrinsic(
|
||||
instruction.imm_u32().unwrap(),
|
||||
budget,
|
||||
)?
|
||||
.unwrap();
|
||||
effect = (native.arg_slots() as u64, native.ret_slots() as u64);
|
||||
}
|
||||
Op::Yield if height != 0 => {
|
||||
return Err(count_error(R::InvalidYield, height as u64, 0));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if (height as u64) < effect.0 {
|
||||
return Err(count_error(R::StackUnderflow, height as u64, effect.0));
|
||||
}
|
||||
let out = (height as u64) - effect.0 + effect.1;
|
||||
// Zero is an actual ceiling in v1; do not infer or rewrite it.
|
||||
if out > max as u64 {
|
||||
return Err(count_error(R::StackOverflow, out, max as u64));
|
||||
}
|
||||
let popped = effect.0 as usize;
|
||||
let pushed = effect.1 as usize;
|
||||
let base = locals + height - popped;
|
||||
match instruction.opcode {
|
||||
Op::Dup => {
|
||||
budget.work(3)?;
|
||||
let fact = working[locals + height - 1];
|
||||
working[base] = fact;
|
||||
working[base + 1] = fact;
|
||||
}
|
||||
Op::Swap => {
|
||||
budget.work(4)?;
|
||||
working.swap(base, base + 1);
|
||||
}
|
||||
Op::GetLocal => {
|
||||
budget.work(2)?;
|
||||
working[base] = working[instruction.imm_u32().unwrap() as usize];
|
||||
}
|
||||
Op::SetLocal => {
|
||||
budget.work(2)?;
|
||||
working[instruction.imm_u32().unwrap() as usize] = working[base];
|
||||
}
|
||||
Op::MakeClosure => {
|
||||
budget.work(1)?;
|
||||
working[base] = Fact::Closure(instruction.imm_u32x2().unwrap().0);
|
||||
}
|
||||
_ => {
|
||||
budget.work(pushed)?;
|
||||
let fact = if matches!(
|
||||
instruction.opcode,
|
||||
Op::PushConst | Op::PushI32 | Op::PushI64 | Op::PushF64 | Op::PushBool
|
||||
) || instruction.opcode.requires_registry()
|
||||
{
|
||||
Fact::NonClosure
|
||||
} else {
|
||||
Fact::Unknown
|
||||
};
|
||||
working[base..base + pushed].fill(fact);
|
||||
}
|
||||
}
|
||||
height = out as usize;
|
||||
if spec.is_branch {
|
||||
let target = instruction.imm_u32().unwrap() as usize;
|
||||
if target == body.len() {
|
||||
if height != results {
|
||||
return Err(count_error(R::ReturnHeight, height as u64, results as u64));
|
||||
}
|
||||
} else {
|
||||
propagate(
|
||||
target,
|
||||
&working[..locals + height],
|
||||
locals,
|
||||
&mut blocks,
|
||||
&mut worklist,
|
||||
budget,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
if spec.is_terminator {
|
||||
break;
|
||||
}
|
||||
pc = instruction.next_pc;
|
||||
if pc == end {
|
||||
if pc == body.len() {
|
||||
return Err(E::new(C::InvalidCode, R::UnterminatedPath));
|
||||
}
|
||||
propagate(
|
||||
pc,
|
||||
&working[..locals + height],
|
||||
locals,
|
||||
&mut blocks,
|
||||
&mut worklist,
|
||||
budget,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn propagate(
|
||||
target: usize,
|
||||
incoming: &[Fact],
|
||||
locals: usize,
|
||||
blocks: &mut [Block],
|
||||
queue: &mut Vec<usize>,
|
||||
budget: &mut LoadBudget,
|
||||
) -> Result<(), E> {
|
||||
budget.work(1)?; // Edge.
|
||||
let mut low = 0;
|
||||
let mut high = blocks.len();
|
||||
while low < high {
|
||||
budget.work(1)?;
|
||||
let mid = low + (high - low) / 2;
|
||||
if blocks[mid].start < target {
|
||||
low = mid + 1;
|
||||
} else {
|
||||
high = mid;
|
||||
}
|
||||
}
|
||||
let node = &mut blocks[low];
|
||||
debug_assert_eq!(node.start, target);
|
||||
budget.work(1)?;
|
||||
let changed = if let Some(current) = &mut node.state {
|
||||
if current.len() != incoming.len() {
|
||||
return Err(count_error(
|
||||
R::StackJoin,
|
||||
(incoming.len() - locals) as u64,
|
||||
(current.len() - locals) as u64,
|
||||
));
|
||||
}
|
||||
budget.work(incoming.len().checked_mul(3).ok_or_else(overflow)?)?;
|
||||
let mut changed = false;
|
||||
for (old, &new) in current.iter_mut().zip(incoming) {
|
||||
if *old != new && *old != Fact::Unknown {
|
||||
*old = Fact::Unknown;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
changed
|
||||
} else {
|
||||
let mut state = scratch::<Fact>(incoming.len(), budget)?;
|
||||
budget.work(incoming.len().checked_mul(2).ok_or_else(overflow)?)?;
|
||||
state.extend_from_slice(incoming);
|
||||
node.state = Some(state);
|
||||
true
|
||||
};
|
||||
budget.work(1)?;
|
||||
if changed && !node.queued {
|
||||
budget.work(2)?;
|
||||
debug_assert!(queue.len() < queue.capacity());
|
||||
node.queued = true;
|
||||
queue.push(low);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn count_error(reason: R, actual: u64, expected: u64) -> E {
|
||||
let mut e = E::new(C::InvalidCode, reason);
|
||||
e.requested = Some(actual);
|
||||
e.limit = Some(expected);
|
||||
e
|
||||
}
|
||||
fn overflow() -> E {
|
||||
E::new(C::ResourceLimit, R::Overflow)
|
||||
}
|
||||
fn scratch<T>(count: usize, budget: &mut LoadBudget) -> Result<Vec<T>, E> {
|
||||
let bytes = count.checked_mul(size_of::<T>()).ok_or_else(overflow)? as u64;
|
||||
budget.charge(Q::TemporaryBytes, bytes)?;
|
||||
let mut values = Vec::new();
|
||||
values.try_reserve_exact(count).map_err(|_| {
|
||||
let mut e = E::resource(Q::TemporaryBytes, bytes, budget.limit(Q::TemporaryBytes));
|
||||
e.reason = R::Allocation;
|
||||
e
|
||||
})?;
|
||||
let actual = values.capacity().checked_mul(size_of::<T>()).ok_or_else(overflow)? as u64;
|
||||
budget.charge(Q::TemporaryBytes, actual - bytes)?;
|
||||
Ok(values)
|
||||
}
|
||||
@@ -36,6 +36,317 @@ 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![];
|
||||
|
||||
Reference in New Issue
Block a user