Skip to main content

rapx/
vm.rs

1//! Symbolic VM state and execution rules.
2
3mod arithmetic;
4mod call_contracts;
5pub(crate) mod constructor_policy;
6pub(crate) mod container;
7pub(crate) mod contract_facts;
8mod contract_expr;
9pub(crate) mod diagnostics;
10pub(crate) mod display;
11pub(crate) mod exec;
12pub(crate) mod inline;
13mod inspection;
14mod iterator;
15pub(crate) mod materialize;
16pub(crate) mod memory;
17pub(crate) mod method_cache;
18mod mir_rules;
19pub(crate) mod parameters;
20pub(crate) mod range;
21pub(crate) mod region;
22pub(crate) mod state;
23mod step;
24pub(crate) use step::RelevantItem;
25
26use rustc_hir::def_id::DefId;
27use rustc_middle::{mir::{Body, Local}, ty::TyCtxt};
28use std::cell::RefCell;
29use z3::{Context, ast::Int};
30
31use crate::{compat::{FxHashMap, FxHashSet}, vm::constructor_policy::ConstructorMirMode};
32
33use self::{
34    diagnostics::Diagnostics,
35    method_cache::CachedMethodResult,
36    state::{AllocId, Constraints, FrameState, InlineCtx, MemoryEvent, MemoryUnit, OwnershipTransfer, SavedCallerFrame},
37};
38
39/// Executes MIR using an immutable context and a path-local symbolic state.
40///
41/// # Agent Rules
42/// Do not add new fields without human approval.
43#[derive(Clone)]
44pub(crate) struct VmExecutor<'z3, 'tcx> {
45    /// Function being verified, retained while inlined callee frames execute.
46    target_def_id: DefId,
47    /// Target MIR instantiated with a selected trait-bound implementor when an
48    /// unresolved, unmodeled generic trait call needs a concrete method target.
49    /// `None` uses the original optimized MIR, even for generic functions.
50    instantiated_target_body: Option<&'tcx Body<'tcx>>,
51    /// Shared Z3 context.
52    pub(crate) z3_ctx: &'z3 Context,
53    /// Compiler type context.
54    pub(crate) tcx: TyCtxt<'tcx>,
55    /// Constructor MIR mode selected for this verification run.
56    constructor_mir_mode: ConstructorMirMode,
57    /// Mutable state cloned when execution branches into separate paths.
58    path_state: VmState<'z3, 'tcx>,
59}
60
61/// Path-local memory, constraints, frames, and diagnostics.
62///
63/// # Agent Rules
64/// Do not add new fields without human approval.
65#[derive(Clone)]
66struct VmState<'z3, 'tcx> {
67    /// Currently executing MIR frame and its local allocation bindings.
68    current_frame: FrameState<'tcx>,
69    /// Caller frames saved by path-replay inlining.
70    caller_frames: Vec<SavedCallerFrame<'z3, 'tcx>>,
71    /// Allocation units indexed by `AllocId`.
72    mem_units: Vec<MemoryUnit<'z3, 'tcx>>,
73    /// Ownership transfers shared by copies of the same raw pointer.
74    ownership_transfers: Vec<OwnershipTransfer>,
75    /// Stable allocation for each static across MIR locals and frames.
76    static_allocs: FxHashMap<DefId, AllocId>,
77    /// Path conditions and term caches.
78    constraints: Constraints<'z3, 'tcx>,
79    /// Scratch state for recursive inlining.
80    inline: InlineCtx<'z3, 'tcx>,
81    /// Stable `&self` results reused by contracts only when the method, caller,
82    /// receiver allocation and offset, fields, and slice length still match.
83    method_result_cache: Vec<CachedMethodResult<'z3, 'tcx>>,
84    /// Allocation roots licensed by declared `Alias` contract sources.
85    alias_hazard_allocs: FxHashSet<AllocId>,
86    /// Slice and index terms with their originating MIR locals.
87    index_access_facts: Vec<(Int<'z3>, Int<'z3>, Local, Local)>,
88    /// Optional trace of memory uses and drops on this path.
89    memory_events: Option<RefCell<Vec<MemoryEvent>>>,
90    /// Path diagnostics and the MIR location used to attribute new records.
91    diagnostics: Diagnostics,
92}
93
94impl<'z3, 'tcx> VmExecutor<'z3, 'tcx> {
95    /// Whether a declared alias contract accepts this allocation's root.
96    pub(crate) fn has_alias_hazard(&self, alloc_id: AllocId) -> bool {
97        self.path_state.alias_hazard_allocs.contains(&self.root_alloc(alloc_id))
98    }
99
100    /// Create an executor with fresh state for one path.
101    pub(crate) fn new(
102        z3_ctx: &'z3 Context,
103        tcx: TyCtxt<'tcx>,
104        target_def_id: DefId,
105        instantiated_target_body: Option<&'tcx Body<'tcx>>,
106        constructor_mir_mode: ConstructorMirMode,
107    ) -> Self {
108        // The `UNINIT` sentinel is created once and shared by every byte array:
109        // an unwritten offset reads it back, so `select != UNINIT` decides
110        // whether a byte was written.
111        let mut constraints = Constraints::default();
112        let uninit = Int::fresh_const(z3_ctx, "uninit_byte");
113        constraints.term_caches.uninit_byte = Some(uninit.clone());
114        constraints.assertions.push(uninit.ge(&Int::from_u64(z3_ctx, 256)));
115        Self {
116            target_def_id,
117            instantiated_target_body,
118            z3_ctx,
119            tcx,
120            constructor_mir_mode,
121            path_state: VmState {
122                current_frame: FrameState {
123                    current_def_id: target_def_id,
124                    instantiated_body: instantiated_target_body,
125                    local_alloc: FxHashMap::default(),
126                },
127                caller_frames: Vec::default(),
128                mem_units: Vec::default(),
129                ownership_transfers: Vec::new(),
130                static_allocs: FxHashMap::default(),
131                constraints,
132                inline: InlineCtx::default(),
133                method_result_cache: Vec::default(),
134                alias_hazard_allocs: FxHashSet::default(),
135                index_access_facts: Vec::new(),
136                memory_events: None,
137                diagnostics: Diagnostics::default(),
138            },
139        }
140    }
141}