1use rustc_hir::{def::DefKind, def_id::DefId};
2use rustc_middle::{
3 mir::{Local, Operand, Place, ProjectionElem, Rvalue, StatementKind, TerminatorKind},
4 ty::{TyCtxt, TyKind},
5};
6use z3::ast::Int;
7
8use crate::analysis::dataflow::call_summary::pointer_semantics;
9use crate::compat::FxHashMap;
10use crate::def_ids::{self, diagnostic_api, intrinsic_api};
11use crate::util::mir_utils;
12
13use super::state::{AllocId, VmExecutor, VmValue};
14
15#[derive(Clone)]
16pub(crate) struct MethodSnapshot<'z3, 'tcx> {
17 method: DefId,
18 caller: DefId,
19 receiver_alloc: AllocId,
20 receiver_offset: Int<'z3>,
21 receiver_slice_len: Option<Int<'z3>>,
22 owner: Local,
23 fields: FxHashMap<Vec<usize>, FieldSnapshot<'z3, 'tcx>>,
24}
25
26#[derive(Clone)]
27struct FieldSnapshot<'z3, 'tcx> {
28 value: VmValue<'z3, 'tcx>,
29 slice_len: Option<Int<'z3>>,
30}
31
32#[derive(Clone)]
34pub(crate) struct CachedMethodResult<'z3, 'tcx> {
35 snapshot: MethodSnapshot<'z3, 'tcx>,
36 result: Int<'z3>,
37}
38
39impl<'z3, 'tcx> VmExecutor<'z3, 'tcx> {
40 pub(crate) fn begin_method_call(
41 &self,
42 method: DefId,
43 receiver: &VmValue<'z3, 'tcx>,
44 receiver_local: Option<Local>,
45 ) -> Option<MethodSnapshot<'z3, 'tcx>> {
46 if !stable_local_query(self.tcx, method) {
47 return None;
48 }
49 let provenance = receiver.provenance.as_ref()?;
50 let receiver_alloc = provenance.alloc_id;
51 let owner = self.method_owner_local(receiver)?;
52 if let Some(local) = receiver_local {
53 let paths = self.field_paths(local);
54 if !paths.is_empty()
55 && (paths.len() != self.field_paths(owner).len()
56 || paths.iter().any(|path| {
57 self.field_value(local, path).map(|value| &value.z3_term)
58 != self.field_value(owner, path).map(|value| &value.z3_term)
59 }))
60 {
61 return None;
62 }
63 }
64 let fields = self
65 .field_paths(owner)
66 .into_iter()
67 .filter_map(|path| {
68 self.field_value(owner, &path)
69 .map(|value| (path, self.snapshot_field(value)))
70 })
71 .collect::<FxHashMap<_, _>>();
72 if fields.is_empty() {
73 return None;
74 }
75 Some(MethodSnapshot {
76 method,
77 caller: self.path_state.current_frame.current_def_id,
78 receiver_alloc,
79 receiver_offset: provenance.offset.clone(),
80 receiver_slice_len: self.alloc(receiver_alloc).slice_len().cloned(),
81 owner,
82 fields,
83 })
84 }
85
86 pub(crate) fn finish_method_call(
87 &mut self,
88 snapshot: Option<MethodSnapshot<'z3, 'tcx>>,
89 result: Option<&VmValue<'z3, 'tcx>>,
90 ) {
91 let (Some(snapshot), Some(result)) = (snapshot, result) else {
92 return;
93 };
94 if self.method_snapshot_matches(&snapshot) {
95 self.path_state.method_result_cache.push(CachedMethodResult {
96 snapshot,
97 result: result.z3_term.clone(),
98 });
99 }
100 }
101
102 pub(crate) fn cached_method_result(
103 &self,
104 method: DefId,
105 receiver: &VmValue<'z3, 'tcx>,
106 ) -> Option<Int<'z3>> {
107 let provenance = receiver.provenance.as_ref()?;
108 self.path_state.method_result_cache.iter().rev().find_map(|entry| {
109 (entry.snapshot.method == method
110 && entry.snapshot.caller == self.path_state.current_frame.current_def_id
111 && entry.snapshot.receiver_alloc == provenance.alloc_id
112 && entry.snapshot.receiver_offset == provenance.offset
113 && self.method_snapshot_matches(&entry.snapshot))
114 .then(|| entry.result.clone())
115 })
116 }
117
118 fn method_snapshot_matches(&self, snapshot: &MethodSnapshot<'z3, 'tcx>) -> bool {
119 if snapshot.caller != self.path_state.current_frame.current_def_id {
120 return false;
121 }
122 let Some(owner) = self.local_value(snapshot.owner) else {
123 return false;
124 };
125 if owner.provenance_alloc_id() != Some(snapshot.receiver_alloc) {
126 return false;
127 }
128 if self.alloc(snapshot.receiver_alloc).slice_len() != snapshot.receiver_slice_len.as_ref() {
129 return false;
130 }
131 let paths = self.field_paths(snapshot.owner);
132 paths.len() == snapshot.fields.len()
133 && paths.iter().all(|path| {
134 self.field_value(snapshot.owner, path).and_then(|value| {
135 snapshot
136 .fields
137 .get(path)
138 .map(|old| self.field_matches(value, old))
139 }) == Some(true)
140 })
141 }
142
143 fn snapshot_field(&self, value: &VmValue<'z3, 'tcx>) -> FieldSnapshot<'z3, 'tcx> {
144 FieldSnapshot {
145 value: value.clone(),
146 slice_len: value
147 .provenance_alloc_id()
148 .and_then(|id| self.alloc(id).slice_len().cloned()),
149 }
150 }
151
152 fn field_matches(&self, value: &VmValue<'z3, 'tcx>, old: &FieldSnapshot<'z3, 'tcx>) -> bool {
153 value.z3_term == old.value.z3_term
154 && value.ty == old.value.ty
155 && value.provenance_alloc_id() == old.value.provenance_alloc_id()
156 && value.provenance.as_ref().map(|p| &p.offset)
157 == old.value.provenance.as_ref().map(|p| &p.offset)
158 && value
159 .provenance_alloc_id()
160 .and_then(|id| self.alloc(id).slice_len().cloned())
161 == old.slice_len
162 }
163
164 fn method_owner_local(&self, receiver: &VmValue<'z3, 'tcx>) -> Option<Local> {
165 let alloc = receiver.provenance_alloc_id()?;
166 self.path_state.current_frame
167 .local_alloc
168 .keys()
169 .copied()
170 .filter(|local| {
171 self.local_value(*local).is_some_and(|value| {
172 value.provenance_alloc_id() == Some(alloc) && value.ty == receiver.ty
173 })
174 })
175 .max_by_key(|local| {
176 (
177 self.field_paths(*local).len(),
178 usize::MAX - local.as_usize(),
179 )
180 })
181 }
182}
183
184fn stable_local_query(tcx: TyCtxt<'_>, method: DefId) -> bool {
185 if !has_method_body(tcx, method) {
186 return false;
187 }
188 let sig = tcx.fn_sig(method).skip_binder();
189 let inputs = sig.inputs().skip_binder();
190 if inputs.len() != 1
191 || !matches!(inputs[0].kind(), TyKind::Ref(_, pointee, rustc_middle::ty::Mutability::Not) if matches!(pointee.kind(), TyKind::Adt(..)))
192 || !matches!(
193 sig.output().skip_binder().kind(),
194 TyKind::Uint(_) | TyKind::Bool
195 )
196 {
197 return false;
198 }
199 stable_query_body(tcx, method)
200}
201
202pub(super) fn stable_contract_query(tcx: TyCtxt<'_>, method: DefId) -> bool {
203 if !has_method_body(tcx, method) {
204 return false;
205 }
206 let sig = tcx.fn_sig(method).skip_binder();
207 let inputs = sig.inputs().skip_binder();
208 if inputs.is_empty()
209 || !matches!(inputs[0].kind(), TyKind::Ref(_, pointee, rustc_middle::ty::Mutability::Not) if matches!(pointee.kind(), TyKind::Adt(..)))
210 || inputs[1..].iter().any(|ty| !matches!(ty.kind(), TyKind::Uint(_) | TyKind::Int(_) | TyKind::Bool))
211 || !matches!(sig.output().skip_binder().kind(), TyKind::Uint(_) | TyKind::Int(_) | TyKind::Bool)
212 {
213 return false;
214 }
215 stable_query_body(tcx, method)
216}
217
218fn has_method_body(tcx: TyCtxt<'_>, method: DefId) -> bool {
219 method.is_local()
220 && matches!(tcx.def_kind(method), DefKind::Fn | DefKind::AssocFn)
221 && tcx.is_mir_available(method)
222}
223
224fn stable_query_body(tcx: TyCtxt<'_>, method: DefId) -> bool {
225 let body = tcx.optimized_mir(method);
226 for block in body.basic_blocks.iter() {
227 for statement in &block.statements {
228 match &statement.kind {
229 StatementKind::Assign(assign) => {
230 if !plain_local(&assign.0) || !stable_rvalue(&assign.1) {
231 return false;
232 }
233 }
234 StatementKind::StorageLive(_)
235 | StatementKind::StorageDead(_)
236 | StatementKind::Nop
237 | StatementKind::FakeRead(..) => {}
238 _ => return false,
239 }
240 }
241 match &block.terminator().kind {
242 TerminatorKind::Goto { .. } | TerminatorKind::Return | TerminatorKind::Unreachable => {}
243 TerminatorKind::SwitchInt { discr, .. } => {
244 if !stable_operand(discr) {
245 return false;
246 }
247 }
248 TerminatorKind::Call {
249 func,
250 args,
251 destination,
252 ..
253 } => {
254 if !plain_local(destination)
255 || args.iter().any(|arg| !stable_operand(&arg.node))
256 || !mir_utils::dep_callee_def_id(func)
257 .is_some_and(|callee| stable_query(tcx, callee))
258 {
259 return false;
260 }
261 }
262 _ => return false,
263 }
264 }
265 true
266}
267
268fn plain_local(place: &Place<'_>) -> bool {
269 place.projection.is_empty()
270}
271
272fn stable_place(place: &Place<'_>) -> bool {
273 place.projection.is_empty()
274 || (place.local == Local::from_usize(1)
275 && place.projection.len() == 2
276 && matches!(place.projection[0], ProjectionElem::Deref)
277 && matches!(place.projection[1], ProjectionElem::Field(..)))
278}
279
280fn stable_operand(operand: &Operand<'_>) -> bool {
281 match operand {
282 Operand::Copy(place) | Operand::Move(place) => stable_place(place),
283 Operand::Constant(_) => true,
284 _ => false,
285 }
286}
287
288fn stable_rvalue(rvalue: &Rvalue<'_>) -> bool {
289 match rvalue {
290 Rvalue::Use(operand, ..) | Rvalue::UnaryOp(_, operand) => stable_operand(operand),
291 Rvalue::BinaryOp(_, operands) => stable_operand(&operands.0) && stable_operand(&operands.1),
292 Rvalue::Cast(_, operand, _, ..) => stable_operand(operand),
293 _ => false,
294 }
295}
296
297fn stable_query(tcx: TyCtxt<'_>, callee: DefId) -> bool {
298 if diagnostic_api::is_mem_size_or_align_of(tcx, callee)
299 || pointer_semantics::is_benign_origin_use(tcx, Some(callee))
300 || def_ids::is_intrinsic_ptr_offset_from(tcx, Some(callee))
301 {
302 return true;
303 }
304 if intrinsic_api::intrinsic_name(tcx, Some(callee))
305 .is_some_and(|name| name.as_str() == "transmute")
306 {
307 return true;
308 }
309 tcx.crate_name(callee.krate).as_str() == "core"
310 && tcx
311 .opt_associated_item(callee)
312 .is_some_and(|item| item.name().as_str() == "offset_from_unsigned")
313 && tcx
314 .fn_sig(callee)
315 .skip_binder()
316 .inputs()
317 .skip_binder()
318 .first()
319 .is_some_and(|ty| matches!(ty.kind(), TyKind::RawPtr(..)))
320}