396 lines
15 KiB
Rust
396 lines
15 KiB
Rust
//! 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),
|
|
}
|
|
pub(super) struct Block<F> {
|
|
pub start: usize,
|
|
pub end: usize,
|
|
pub state: Option<Vec<F>>,
|
|
pub 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))
|
|
};
|
|
}
|
|
|
|
let mut blocks = basic_blocks::<Fact>(body, budget, at_pc)?;
|
|
let count = blocks.len();
|
|
let mut pc;
|
|
|
|
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,
|
|
Fact::Unknown,
|
|
&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,
|
|
Fact::Unknown,
|
|
&mut blocks,
|
|
&mut worklist,
|
|
budget,
|
|
)?;
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub(super) fn propagate<F: Copy + Eq>(
|
|
target: usize,
|
|
incoming: &[F],
|
|
locals: usize,
|
|
unknown: F,
|
|
blocks: &mut [Block<F>],
|
|
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 {
|
|
budget.work(1)?;
|
|
if *old != unknown {
|
|
budget.work(1)?;
|
|
*old = unknown;
|
|
changed = true;
|
|
}
|
|
}
|
|
}
|
|
changed
|
|
} else {
|
|
let mut state = scratch::<F>(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)
|
|
}
|
|
pub(super) 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)
|
|
}
|
|
|
|
/// Metered CFG construction shared by the stack and semantic analyses.
|
|
pub(super) fn basic_blocks<F>(
|
|
body: &[u8],
|
|
budget: &mut LoadBudget,
|
|
at_pc: &mut usize,
|
|
) -> Result<Vec<Block<F>>, E> {
|
|
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<F>>(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 bytes = leaders.capacity() as u64;
|
|
drop(leaders);
|
|
budget.refund(Q::TemporaryBytes, bytes);
|
|
Ok(blocks)
|
|
}
|