Prove read-only effects through current source call graphs
This commit is contained in:
@@ -0,0 +1,274 @@
|
||||
//! Snapshot proof of read-only call graphs. All identities are borrowed and all
|
||||
//! traversals iterative; analysis neither executes code nor allocates VM objects.
|
||||
use super::{AttributeLookup, BoundMethod};
|
||||
use crate::{
|
||||
CallEffect, EndorCodeObject, EndorFunctionObject, ObjectRef, ObjectStore, Opcode, Value,
|
||||
VmError,
|
||||
};
|
||||
use std::collections::{BTreeSet, VecDeque};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
struct Target {
|
||||
function: ObjectRef,
|
||||
receiver: Option<ObjectRef>,
|
||||
}
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Fact {
|
||||
Unknown,
|
||||
Null,
|
||||
Object(ObjectRef),
|
||||
Method(Target),
|
||||
}
|
||||
impl Fact {
|
||||
fn value(value: Value) -> Self {
|
||||
match value {
|
||||
Value::Object(object) => Self::Object(object),
|
||||
_ => Self::Unknown,
|
||||
}
|
||||
}
|
||||
fn object(self) -> Option<ObjectRef> {
|
||||
match self {
|
||||
Self::Object(object) => Some(object),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ObjectStore {
|
||||
fn effect_target(&self, mut target: Target) -> Result<Target, VmError> {
|
||||
loop {
|
||||
let payload = self.object(target.function)?.payload();
|
||||
let Some(bound) = payload.as_any().downcast_ref::<BoundMethod>() else {
|
||||
return Ok(target);
|
||||
};
|
||||
target = Target {
|
||||
function: bound.function,
|
||||
receiver: Some(bound.receiver),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn infer_call_effect(
|
||||
&self,
|
||||
function: ObjectRef,
|
||||
) -> Result<Option<CallEffect>, VmError> {
|
||||
let root = self.effect_target(Target {
|
||||
function,
|
||||
receiver: None,
|
||||
})?;
|
||||
if !self
|
||||
.object(root.function)?
|
||||
.payload()
|
||||
.as_any()
|
||||
.is::<EndorFunctionObject>()
|
||||
{
|
||||
return Ok(self.native_signature(root.function)?.and_then(|signature| {
|
||||
(signature.effect != CallEffect::Delegated).then_some(signature.effect)
|
||||
}));
|
||||
}
|
||||
let mut pending = VecDeque::from([root]);
|
||||
let mut visited = BTreeSet::new();
|
||||
while let Some(target) = pending.pop_front() {
|
||||
let target = self.effect_target(target)?;
|
||||
if !visited.insert(target) {
|
||||
continue;
|
||||
}
|
||||
if let Some(source) = self
|
||||
.object(target.function)?
|
||||
.payload()
|
||||
.as_any()
|
||||
.downcast_ref::<EndorFunctionObject>()
|
||||
{
|
||||
let Some(callees) = self.read_only_callees(source, target.receiver)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
pending.extend(callees);
|
||||
} else if self
|
||||
.native_signature(target.function)?
|
||||
.is_none_or(|signature| signature.effect != CallEffect::ReadOnly)
|
||||
{
|
||||
// An impure target could rebind later globals/Cells/methods, so
|
||||
// snapshot edges cannot bound this source invocation's effects.
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
Ok(Some(CallEffect::ReadOnly))
|
||||
}
|
||||
|
||||
fn read_only_callees(
|
||||
&self,
|
||||
function: &EndorFunctionObject,
|
||||
receiver: Option<ObjectRef>,
|
||||
) -> Result<Option<BTreeSet<Target>>, VmError> {
|
||||
let code = self
|
||||
.payload::<EndorCodeObject>(function.code(), "code")?
|
||||
.code();
|
||||
if code.is_statically_read_only() {
|
||||
return Ok(Some(BTreeSet::new()));
|
||||
}
|
||||
let instructions = code.instructions();
|
||||
if instructions.iter().any(|decoded| {
|
||||
decoded.instruction.opcode != Opcode::Call
|
||||
&& !crate::code::read_only_opcode(decoded.instruction.opcode)
|
||||
}) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut states: Vec<Option<Vec<Fact>>> = vec![None; instructions.len()];
|
||||
states[0] = Some(vec![]);
|
||||
let mut work = VecDeque::from([0]);
|
||||
let mut callees = BTreeSet::new();
|
||||
while let Some(index) = work.pop_front() {
|
||||
let decoded = instructions[index];
|
||||
let opcode = decoded.instruction.opcode;
|
||||
let argument = decoded.instruction.argument as usize;
|
||||
let mut stack = states[index].clone().expect("reachable effect state");
|
||||
match opcode {
|
||||
Opcode::LoadConst => stack.push(Fact::value(code.constants()[argument].clone())),
|
||||
Opcode::LoadFast => stack.push(if argument == 0 {
|
||||
receiver.map(Fact::Object).unwrap_or(Fact::Unknown)
|
||||
} else {
|
||||
Fact::Unknown
|
||||
}),
|
||||
Opcode::LoadGlobal => {
|
||||
let key = Value::Text(code.layout().names[argument].clone());
|
||||
let mut value = self.dict_get(function.globals(), &key)?;
|
||||
if value.is_none()
|
||||
&& let Some(builtins) = function.builtins()
|
||||
{
|
||||
value = self.dict_get(builtins, &key)?;
|
||||
}
|
||||
stack.push(value.map(Fact::value).unwrap_or(Fact::Unknown));
|
||||
}
|
||||
Opcode::LoadDeref | Opcode::LoadClosure => {
|
||||
let fact = if argument >= code.layout().locals.len() {
|
||||
let cell = *function
|
||||
.closure()
|
||||
.get(argument - code.layout().locals.len())
|
||||
.ok_or(VmError::InvalidArgument(
|
||||
"function closure does not match code",
|
||||
))?;
|
||||
if opcode == Opcode::LoadClosure {
|
||||
Fact::Object(cell)
|
||||
} else {
|
||||
match self.cell_get(cell) {
|
||||
Ok(value) => Fact::value(value),
|
||||
Err(VmError::EmptyCell) => Fact::Unknown,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
} else if opcode == Opcode::LoadDeref && argument == 0 {
|
||||
receiver.map(Fact::Object).unwrap_or(Fact::Unknown)
|
||||
} else {
|
||||
Fact::Unknown
|
||||
};
|
||||
stack.push(fact);
|
||||
}
|
||||
Opcode::PushNull => stack.push(Fact::Null),
|
||||
Opcode::Copy => stack.push(stack[stack.len() - argument]),
|
||||
Opcode::Swap => {
|
||||
let length = stack.len();
|
||||
stack.swap(length - 1, length - argument);
|
||||
}
|
||||
Opcode::PopTop
|
||||
| Opcode::PopJumpIfFalse
|
||||
| Opcode::PopJumpIfTrue
|
||||
| Opcode::ReturnValue => {
|
||||
stack.pop();
|
||||
}
|
||||
Opcode::ToBool | Opcode::UnaryNot => {
|
||||
*stack.last_mut().unwrap() = Fact::Unknown;
|
||||
}
|
||||
Opcode::CompareOp => {
|
||||
stack.pop();
|
||||
*stack.last_mut().unwrap() = Fact::Unknown;
|
||||
}
|
||||
Opcode::LoadAttr => {
|
||||
let fact = stack.last_mut().unwrap();
|
||||
*fact = if let Some(owner) = fact.object() {
|
||||
match self.lookup_attr(owner, &code.layout().names[argument]) {
|
||||
Ok(AttributeLookup::Value(value)) => Fact::value(value),
|
||||
Ok(AttributeLookup::Method { function, receiver }) => {
|
||||
Fact::Method(Target {
|
||||
function,
|
||||
receiver: Some(receiver),
|
||||
})
|
||||
}
|
||||
Err(
|
||||
VmError::AttributeNotFound(_)
|
||||
| VmError::UnsupportedOperation("attributes"),
|
||||
) => Fact::Unknown,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
} else {
|
||||
Fact::Unknown
|
||||
};
|
||||
}
|
||||
Opcode::Call => {
|
||||
let start = stack.len() - argument - 2;
|
||||
let implicit = if stack[start + 1] == Fact::Null {
|
||||
(argument > 0)
|
||||
.then(|| stack[start + 2])
|
||||
.and_then(Fact::object)
|
||||
} else {
|
||||
stack[start + 1].object()
|
||||
};
|
||||
let target = match stack[start] {
|
||||
Fact::Object(function) => Target {
|
||||
function,
|
||||
receiver: implicit,
|
||||
},
|
||||
Fact::Method(target) => target,
|
||||
_ => return Ok(None),
|
||||
};
|
||||
callees.insert(target);
|
||||
stack.truncate(start);
|
||||
stack.push(Fact::Unknown);
|
||||
}
|
||||
Opcode::BuildMap => {
|
||||
stack.truncate(stack.len() - argument * 2);
|
||||
stack.push(Fact::Unknown);
|
||||
}
|
||||
Opcode::MakeFunction => {
|
||||
let (defaults, closure) =
|
||||
crate::Instruction::function_counts(decoded.instruction.argument);
|
||||
stack.truncate(stack.len() - defaults - closure - 1);
|
||||
stack.push(Fact::Unknown);
|
||||
}
|
||||
Opcode::Nop | Opcode::DeleteFast | Opcode::JumpForward | Opcode::JumpBackward => {}
|
||||
_ => unreachable!("unproved opcodes were rejected before analysis"),
|
||||
}
|
||||
let successors = match opcode {
|
||||
Opcode::ReturnValue => vec![],
|
||||
Opcode::JumpForward | Opcode::JumpBackward => {
|
||||
vec![crate::code::jump_target(decoded)?]
|
||||
}
|
||||
Opcode::PopJumpIfFalse | Opcode::PopJumpIfTrue => {
|
||||
vec![crate::code::jump_target(decoded)?, decoded.next_offset]
|
||||
}
|
||||
_ => vec![decoded.next_offset],
|
||||
};
|
||||
for offset in successors {
|
||||
let next = instructions
|
||||
.binary_search_by_key(&offset, |item| item.offset)
|
||||
.expect("validated successor");
|
||||
let changed = if let Some(existing) = &mut states[next] {
|
||||
let mut changed = false;
|
||||
for (old, new) in existing.iter_mut().zip(&stack) {
|
||||
if *old != *new && *old != Fact::Unknown {
|
||||
*old = Fact::Unknown;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
changed
|
||||
} else {
|
||||
states[next] = Some(stack.clone());
|
||||
true
|
||||
};
|
||||
if changed {
|
||||
work.push_back(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(callees))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user