This commit is contained in:
2026-03-24 13:40:40 +00:00
parent 5095fc1a76
commit e894ea1a8c
4 changed files with 811 additions and 96 deletions
+190 -8
View File
@@ -25,6 +25,13 @@ pub enum VerifierError {
/// (e.g., RET, JMP to end, HALT/TRAP). Verifier requires every reachable path to end
/// in a terminator.
UnterminatedPath { func_idx: usize, at_pc: usize },
// --- Closure-specific errors ---
/// Top of stack is not a closure value on CALL_CLOSURE
NotAClosureOnCallClosure { pc: usize },
/// CALL_CLOSURE used with a closure whose callee function is not known at verify time
UnknownClosureCallee { pc: usize },
/// User-provided arg_count for CALL_CLOSURE does not match callee signature
BadClosureArgCount { pc: usize, expected: u16, got: u16 },
}
pub struct Verifier;
@@ -101,16 +108,37 @@ impl Verifier {
return Err(VerifierError::TrailingBytes { func_idx, at_pc: func_start + pc });
}
let mut stack_height_in: HashMap<usize, u16> = HashMap::new();
// Minimal stack type lattice to validate closure semantics
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SlotTy {
/// Type information not known statically (join of different paths or from loads/calls)
Unknown,
/// A value that is definitely not a closure (immediates, arithmetic results)
NonClosure,
/// A closure value whose target function id is known (from MAKE_CLOSURE)
Closure(u32),
}
fn join_slot(a: SlotTy, b: SlotTy) -> SlotTy {
use SlotTy::*;
match (a, b) {
(Closure(id1), Closure(id2)) if id1 == id2 => Closure(id1),
(NonClosure, NonClosure) => NonClosure,
_ => Unknown,
}
}
let mut stack_types_in: HashMap<usize, Vec<SlotTy>> = HashMap::new();
let mut worklist = VecDeque::new();
let mut max_stack: u16 = 0;
// Start from function entry
stack_height_in.insert(0, 0);
stack_types_in.insert(0, Vec::new());
worklist.push_back(0);
while let Some(pc) = worklist.pop_front() {
let in_height = *stack_height_in.get(&pc).unwrap();
let in_types = stack_types_in.get(&pc).cloned().unwrap();
let in_height = in_types.len() as u16;
let instr = decode_next(pc, func_code).unwrap(); // Guaranteed to succeed due to first pass
let spec = instr.opcode.spec();
@@ -127,6 +155,19 @@ impl Verifier {
})?;
(callee.param_slots, callee.return_slots)
}
OpCode::MakeClosure => {
// imm: fn_id (u32), capture_count (u32)
let (_fn_id, capture_count_u32) = instr.imm_u32x2().unwrap();
let capture_count = capture_count_u32 as u16;
(capture_count, 1)
}
OpCode::CallClosure => {
// imm: arg_count (u32). Pops closure_ref + arg_count, pushes callee returns.
// We can't determine pushes here without looking at TOS type; will validate below.
let arg_count = instr.imm_u32().unwrap() as u16;
// Temporarily set pushes=0; we'll compute real pushes after type checks.
(arg_count + 1, 0)
}
OpCode::Ret => (func.return_slots, 0),
OpCode::Syscall => {
let id = instr.imm_u32().unwrap();
@@ -145,7 +186,121 @@ impl Verifier {
});
}
let out_height = in_height - pops + pushes;
// Compute out types vector with closure-aware rules
use SlotTy::*;
let mut out_types = in_types.clone();
// Pop first
for _ in 0..pops {
out_types.pop();
}
// Special handling per opcode that affects types/pushes
let mut dynamic_pushes: Option<u16> = None;
match instr.opcode {
OpCode::MakeClosure => {
let (fn_id, _cap) = instr.imm_u32x2().unwrap();
out_types.push(Closure(fn_id));
}
OpCode::CallClosure => {
// Validate TOS was a known closure and arg_count matches signature
let tos = in_types.last().copied().unwrap_or(Unknown);
match tos {
Closure(fn_id) => {
let callee = all_functions.get(fn_id as usize).ok_or_else(|| {
VerifierError::InvalidFuncId { pc: func_start + pc, id: fn_id }
})?;
let user_argc = instr.imm_u32().unwrap() as u16;
if callee.param_slots == 0 {
// Hidden arg0 must exist in callee signature
return Err(VerifierError::BadClosureArgCount {
pc: func_start + pc,
expected: 0,
got: user_argc,
});
}
let expected_user = callee.param_slots - 1; // exclude hidden arg0
if expected_user != user_argc {
return Err(VerifierError::BadClosureArgCount {
pc: func_start + pc,
expected: expected_user,
got: user_argc,
});
}
// Push callee returns as Unknown types
for _ in 0..callee.return_slots {
out_types.push(Unknown);
}
dynamic_pushes = Some(callee.return_slots);
}
NonClosure => {
return Err(VerifierError::NotAClosureOnCallClosure { pc: func_start + pc });
}
Unknown => {
// We cannot determine return arity; be strict and reject
return Err(VerifierError::UnknownClosureCallee { pc: func_start + pc });
}
}
}
// Immediates and known non-closure pushes
OpCode::PushConst | OpCode::PushI64 | OpCode::PushF64 | OpCode::PushBool
| OpCode::PushI32 | OpCode::PushBounded => {
out_types.push(NonClosure);
}
// Dup duplicates TOS type
OpCode::Dup => {
let tos = in_types.last().copied().unwrap_or(Unknown);
if matches!(tos, Unknown) && in_height == 0 {
// Will already have underflowed on pops check for other ops; for Dup, enforce explicitly
return Err(VerifierError::StackUnderflow { pc: func_start + pc, opcode: OpCode::Dup });
}
out_types.push(tos);
}
// Swap swaps top-2 types; ensure enough stack
OpCode::Swap => {
if in_types.len() < 2 {
return Err(VerifierError::StackUnderflow { pc: func_start + pc, opcode: OpCode::Swap });
}
let len = out_types.len();
out_types.swap(len - 1, len - 2);
}
// Arithmetic/logic produce NonClosure but we don't strictly need it; mark Unknown conservatively
// Calls and syscalls return Unknown
OpCode::Call => {
let func_id = instr.imm_u32().unwrap();
let callee = all_functions.get(func_id as usize).unwrap();
for _ in 0..callee.return_slots {
out_types.push(Unknown);
}
}
OpCode::Syscall => {
let id = instr.imm_u32().unwrap();
let syscall = Syscall::from_u32(id).unwrap();
for _ in 0..(syscall.results_count() as u16) {
out_types.push(Unknown);
}
}
_ => {
// Default: push Unknown for any declared pushes
if spec.pushes > 0 {
for _ in 0..spec.pushes {
out_types.push(Unknown);
}
}
}
}
let pushes_final = dynamic_pushes.unwrap_or_else(|| match instr.opcode {
OpCode::MakeClosure => 1,
OpCode::CallClosure => {
// If we reached here, we handled it above and set dynamic_pushes
0
}
OpCode::Syscall => spec.pushes, // already added Unknowns above
OpCode::Call => spec.pushes, // already added Unknowns above
_ => spec.pushes,
});
let out_height = (out_types.len()) as u16;
max_stack = max_stack.max(out_height);
// Enforce declared max stack if provided (0 means "no explicit limit")
@@ -220,7 +375,8 @@ impl Verifier {
});
}
if let Some(&existing_height) = stack_height_in.get(&target_rel) {
if let Some(existing_types) = stack_types_in.get_mut(&target_rel) {
let existing_height = existing_types.len() as u16;
if existing_height != out_height {
return Err(VerifierError::StackMismatchJoin {
pc: func_start + pc,
@@ -228,9 +384,22 @@ impl Verifier {
height_in: out_height,
height_target: existing_height,
});
} else {
// Merge types pointwise; if any slot changes, re-enqueue
let mut changed = false;
for i in 0..existing_types.len() {
let joined = join_slot(existing_types[i], out_types[i]);
if joined != existing_types[i] {
existing_types[i] = joined;
changed = true;
}
}
if changed {
worklist.push_back(target_rel);
}
}
} else {
stack_height_in.insert(target_rel, out_height);
stack_types_in.insert(target_rel, out_types.clone());
worklist.push_back(target_rel);
}
}
@@ -240,7 +409,8 @@ impl Verifier {
let next_pc = instr.next_pc;
let func_len = layouts.get(func_idx).map(|l| l.end - l.start).unwrap_or_else(|| 0);
if next_pc < func_len {
if let Some(&existing_height) = stack_height_in.get(&next_pc) {
if let Some(existing_types) = stack_types_in.get_mut(&next_pc) {
let existing_height = existing_types.len() as u16;
if existing_height != out_height {
return Err(VerifierError::StackMismatchJoin {
pc: func_start + pc,
@@ -248,9 +418,21 @@ impl Verifier {
height_in: out_height,
height_target: existing_height,
});
} else {
let mut changed = false;
for i in 0..existing_types.len() {
let joined = join_slot(existing_types[i], out_types[i]);
if joined != existing_types[i] {
existing_types[i] = joined;
changed = true;
}
}
if changed {
worklist.push_back(next_pc);
}
}
} else {
stack_height_in.insert(next_pc, out_height);
stack_types_in.insert(next_pc, out_types);
worklist.push_back(next_pc);
}
} else if next_pc == func_len {