Distinguish annotation validation from content read dependencies

This commit is contained in:
2026-10-22 13:01:40 +08:00
parent 44519abf7e
commit f9243c77c7
12 changed files with 167 additions and 15 deletions
+4 -4
View File
@@ -4,15 +4,15 @@
| 文件 | 职责 |
| --- | --- |
| [lib.rs](lib.rs) | 包边界、对象类型/ObjectStore 公开导出(含Trait/MethodRequirement/SourceSignature/AnnotationType/CallArity)与独立存储 rustdoc 示例 |
| [lib.rs](lib.rs) | 包边界、对象类型/ObjectStore 公开导出(含Trait/MethodRequirement/SourceSignature/AnnotationType/CallArity/ReadAccess)与独立存储 rustdoc 示例 |
| [object.rs](object.rs) | Value、CompareOp、ObjectPayload(含显式函数标记)、ObjectHeader、EndorObject、Record、可发布数量元数据的 NativeFunction |
| [types.rs](types.rs) | 托管名义类型、显式 Object/Type 引导、继承查询、受管方法表/接收者绑定、类字段、显式Trait定义/声明/方法参数约束、原生构造委托、统一源码/原生/绑定方法参数区间查询与能力验证、声明环境托管边、字段构造/写入检查与注解解析/匹配 |
| [types.rs](types.rs) | 托管名义类型、显式 Object/Type 引导、继承查询、受管方法表/接收者绑定、类字段、显式Trait定义/声明/方法参数约束、原生构造委托、统一源码/原生/绑定方法参数区间查询与能力验证、声明环境托管边、字段构造/写入检查与标记为校验读取的注解解析/匹配 |
| [native.rs](native.rs) | NativeContext、CallArity 元数据与调用前数量检查、上下文原生函数、作用域语言函数工厂、显式能力声明入口、函数标记、根与非递归委托调用 |
| [changes.rs](changes.rs) | 合并变更批次、变更键与有界通知额度 |
| [number.rs](number.rs) | Integer/Decimal/Rational/BinaryFloat/Complex 的无损表示和装箱载荷 |
| [builtins.rs](builtins.rs) | String、Dict、Cell、Function、BaseException 载荷与 trace 边、语言函数标记 |
| [heap.rs](heap.rs) | 私有 Heap、不可伪造 ObjectRef、稳定 Box、引用事务、迭代释放、循环回收、后代契约更新的私有借用枚举、同类型附加幂等、只读变更屏障/全调用及嵌套子调用读取跟踪及私有边界测试 |
| [store.rs](store.rs) | ObjectStore、空堆创建、字段检查配置/属性写入屏障、对象操作、retain/release 和回收入口、弱 Function 类型配置与分配分类 |
| [heap.rs](heap.rs) | 私有 Heap、不可伪造 ObjectRef、稳定 Box、引用事务、迭代释放、循环回收、后代契约更新的私有借用枚举、同类型附加幂等、只读变更屏障/全调用及嵌套子调用读取跟踪(区分注解校验与内容读取)及私有边界测试 |
| [store.rs](store.rs) | ObjectStore、空堆创建、字段检查配置/属性写入屏障、详细读取区域结果、对象操作、retain/release 和回收入口、弱 Function 类型配置与分配分类 |
| [store_builtins.rs](store_builtins.rs) | 载荷校验、代码/函数工厂、Dict/Cell 操作及键语义 |
| [instruction.rs](instruction.rs) | Opcode、Instruction、wordcode 编解码、MakeFunction/比较参数与跳转读取接口 |
| [code.rs](code.rs) | CodeLayout、EndorCode/EndorCodeObject、可选源码签名、共享不可变代码和操作数/控制流/栈验证 |
+86 -5
View File
@@ -1,7 +1,8 @@
use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fmt;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use std::thread::ThreadId;
use crate::changes::MAX_PENDING_CHANGES;
use crate::{ChangeBatch, ChangeKey, ObjectChange};
@@ -39,7 +40,7 @@ struct Slot {
struct ReadOnly {
protected: BTreeSet<ObjectRef>,
reads: Mutex<BTreeSet<ObjectRef>>,
regions: Mutex<Vec<BTreeSet<ObjectRef>>>,
regions: Mutex<Vec<BTreeMap<ObjectRef, bool>>>,
}
#[derive(Debug)]
@@ -51,6 +52,36 @@ pub(crate) struct Heap {
changes: BTreeMap<(ObjectRef, ChangeKey), u64>,
changes_overflow: bool,
read_only: Vec<ReadOnly>,
validation_reads: Mutex<HashMap<ThreadId, usize>>,
}
/// Borrowed read identity; content_read distinguishes ordinary reads from
/// annotation validation alone. Neither form retains the object.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReadAccess {
pub object: ObjectRef,
pub content_read: bool,
}
struct ValidationScope<'a> {
heap: &'a Heap,
thread: ThreadId,
}
impl Drop for ValidationScope<'_> {
fn drop(&mut self) {
let mut active = self
.heap
.validation_reads
.lock()
.expect("read tracker poisoned");
let depth = active
.get_mut(&self.thread)
.expect("active validation scope");
*depth -= 1;
if *depth == 0 {
active.remove(&self.thread);
}
}
}
impl Heap {
@@ -66,6 +97,7 @@ impl Heap {
changes: BTreeMap::new(),
changes_overflow: false,
read_only: vec![],
validation_reads: Mutex::new(HashMap::new()),
})
}
@@ -120,11 +152,22 @@ impl Heap {
"read tracking requires a read-only scope",
))?;
let mut regions = scope.regions.lock().expect("read tracker poisoned");
regions.push(BTreeSet::new());
regions.push(BTreeMap::new());
Ok(regions.len())
}
pub(crate) fn end_read_tracking(&self, token: usize) -> Result<Vec<ObjectRef>, VmError> {
Ok(self
.end_read_tracking_details(token)?
.into_iter()
.map(|read| read.object)
.collect())
}
pub(crate) fn end_read_tracking_details(
&self,
token: usize,
) -> Result<Vec<ReadAccess>, VmError> {
let scope = self.read_only.last().ok_or(VmError::InvalidArgument(
"read tracking requires a read-only scope",
))?;
@@ -132,14 +175,49 @@ impl Heap {
if token == 0 || token != regions.len() {
return Err(VmError::InvalidArgument("read tracking nesting mismatch"));
}
Ok(regions.pop().unwrap().into_iter().collect())
Ok(regions
.pop()
.unwrap()
.into_iter()
.map(|(object, content_read)| ReadAccess {
object,
content_read,
})
.collect())
}
pub(crate) fn is_read_only(&self) -> bool {
!self.read_only.is_empty()
}
pub(crate) fn with_validation_reads<T>(
&self,
compute: impl FnOnce() -> Result<T, VmError>,
) -> Result<T, VmError> {
if self.read_only.is_empty() {
return compute();
}
let thread = std::thread::current().id();
{
let mut active = self.validation_reads.lock().expect("read tracker poisoned");
let depth = active.entry(thread).or_default();
*depth = depth
.checked_add(1)
.ok_or(VmError::ExecutionLimit("validation scopes"))?;
}
let _scope = ValidationScope { heap: self, thread };
compute()
}
pub(crate) fn record_read(&self, reference: ObjectRef) {
if self.read_only.is_empty() {
return;
}
let content = !self
.validation_reads
.lock()
.expect("read tracker poisoned")
.contains_key(&std::thread::current().id());
for scope in &self.read_only {
if scope.protected.contains(&reference) {
scope
@@ -153,7 +231,10 @@ impl Heap {
.expect("read tracker poisoned")
.iter_mut()
{
region.insert(reference);
region
.entry(reference)
.and_modify(|ordinary| *ordinary |= content)
.or_insert(content);
}
}
}
+1 -1
View File
@@ -33,7 +33,7 @@ pub use builtins::{
pub use changes::{ChangeBatch, ChangeKey, ObjectChange};
pub use code::{CodeLayout, EndorCode, EndorCodeObject, SourceSignature};
pub use error::VmError;
pub use heap::{ObjectRef, WeakObjectRef};
pub use heap::{ObjectRef, ReadAccess, WeakObjectRef};
pub use instruction::{DecodedInstruction, Instruction, Opcode};
pub use native::{CallArity, ContextNativeFunction, NativeCallable, NativeContext, NativeResult};
pub use number::{
+9
View File
@@ -44,6 +44,15 @@ impl ObjectStore {
self.heap.end_read_tracking(token)
}
/// Like end_read_tracking, retaining the distinction between program reads
/// and VM annotation validation. Ordinary reads always dominate.
pub fn end_read_tracking_details(
&self,
token: usize,
) -> Result<Vec<crate::ReadAccess>, VmError> {
self.heap.end_read_tracking_details(token)
}
pub fn is_read_only(&self) -> bool {
self.heap.is_read_only()
}
+9
View File
@@ -996,6 +996,15 @@ impl ObjectStore {
&self,
value: &Value,
expected: AnnotationType,
) -> Result<bool, VmError> {
self.heap
.with_validation_reads(|| self.matches_annotation_value(value, expected))
}
fn matches_annotation_value(
&self,
value: &Value,
expected: AnnotationType,
) -> Result<bool, VmError> {
if let Value::Object(object) = value {
self.object(*object)?;