Skip to main content

rapx/verify/
alias.rs

1//! Alias checks combining VM provenance with MIR hazard analysis.
2//!
3//! Trace a pointer's allocation back to its source, then check whether a
4//! reference view, ownership transfer, read, or copy violates Alias.
5
6use crate::analysis::alias::hazard::{self as alias_hazard, AliasProducer, HazardKind};
7use crate::analysis::alias::FieldOrigin;
8use crate::analysis::dataflow::pointer_flow;
9use crate::compat::GenericArgsRef;
10use crate::def_ids::type_ids;
11use crate::util::def_use::PlaceKey;
12use crate::util::mir_utils;
13use crate::verify::checkpoint::Checkpoint;
14use crate::vm::state::{VmExecutor, VmValue};
15use rustc_hir::def_id::DefId;
16use rustc_middle::mir::{Local, Operand, ProjectionElem, Rvalue, StatementKind};
17
18/// Information about a value's ultimate origin.
19#[derive(Clone, Debug)]
20pub(crate) struct VmOrigin {
21    /// The local (parameter or stack variable) that is the root source.
22    pub local: Local,
23    /// The type of the origin local (Ref/MutRef/RawPtr/Adt/...).
24    pub kind: VmOriginKind,
25}
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub(crate) enum VmOriginKind {
29    MutRef,
30    SharedRef,
31    /// A raw pointer (`*const T` / `*mut T`). The const/mut distinction is
32    /// compile-time-only (the casts are safe in both directions), so both are
33    /// treated as one origin kind for alias analysis.
34    RawPtr,
35    Owned(DefId),
36    Unknown,
37}
38
39impl VmOrigin {
40    /// Whether this origin is a `&mut T` reference — safe to create a unique view from.
41    pub(crate) fn is_mut_ref(&self) -> bool {
42        matches!(self.kind, VmOriginKind::MutRef)
43    }
44
45    /// Whether this origin is a `&T` reference — safe to create a shared view from.
46    pub(crate) fn is_shared_ref(&self) -> bool {
47        matches!(self.kind, VmOriginKind::SharedRef)
48    }
49
50    /// Whether this origin is an owned type (Box, Vec) transferred to this function.
51    pub(crate) fn is_owned(&self) -> bool {
52        matches!(self.kind, VmOriginKind::Owned(_))
53    }
54}
55
56impl<'z3, 'tcx> VmExecutor<'z3, 'tcx> {
57    /// Trace the origin of a pointer value through VM provenance.
58    ///
59    /// Given a VmValue (extracted from a checkpoint argument), follows
60    /// its provenance back to determine where the allocation came from.
61    pub(crate) fn resolve_origin(&self, value: &VmValue<'z3, 'tcx>) -> Option<VmOrigin> {
62        let Some(prov) = &value.provenance else {
63            return None;
64        };
65
66        let alloc_id = prov.alloc_id;
67        let mut best: Option<VmOrigin> = None;
68        for (local, val) in self.all_local_values() {
69            let Some(val_prov) = &val.provenance else {
70                continue;
71            };
72            if val_prov.alloc_id != alloc_id {
73                continue;
74            }
75
76            let kind = self.classify_local(&local);
77            let candidate = VmOrigin { local, kind };
78            let is_param = local.as_usize() >= 1 && local.as_usize() <= self.body().arg_count;
79            let is_owned = candidate.is_owned();
80            match &best {
81                None => best = Some(candidate),
82                Some(existing) => {
83                    let ex_is_param = existing.local.as_usize() >= 1
84                        && existing.local.as_usize() <= self.body().arg_count;
85                    let ex_is_owned = existing.is_owned();
86                    let rank = |p: bool, o: bool| {
87                        if p {
88                            0
89                        } else if o {
90                            1
91                        } else {
92                            2
93                        }
94                    };
95                    let cand_rank = rank(is_param, is_owned);
96                    let ex_rank = rank(ex_is_param, ex_is_owned);
97                    if cand_rank < ex_rank
98                        || (cand_rank == ex_rank && local.as_usize() < existing.local.as_usize())
99                    {
100                        best = Some(candidate);
101                    }
102                }
103            }
104        }
105
106        best
107    }
108
109    /// Classify a local by its type.
110    fn classify_local(&self, local: &Local) -> VmOriginKind {
111        let ty = self.body().local_decls[*local].ty;
112        match ty.kind() {
113            rustc_middle::ty::TyKind::Ref(_, _, rustc_middle::ty::Mutability::Mut) => {
114                VmOriginKind::MutRef
115            }
116            rustc_middle::ty::TyKind::Ref(_, _, rustc_middle::ty::Mutability::Not) => {
117                VmOriginKind::SharedRef
118            }
119            rustc_middle::ty::TyKind::RawPtr(..) => VmOriginKind::RawPtr,
120            rustc_middle::ty::TyKind::Adt(adt_def, _) => VmOriginKind::Owned(adt_def.did()),
121            _ => VmOriginKind::Unknown,
122        }
123    }
124}
125
126/// Result of an Alias check using VM state.
127pub(crate) enum VmAliasResult {
128    Proved,
129    Failed(String),
130    Unknown,
131}
132
133fn origin_alias_hazard_accepted<'z3, 'tcx>(
134    vm_state: &VmExecutor<'z3, 'tcx>,
135    origin_val: &VmValue<'z3, 'tcx>,
136) -> bool {
137    origin_val.provenance_alloc_id().is_some_and(|alloc_id| vm_state.has_alias_hazard(alloc_id))
138}
139
140/// Flow-sensitive shared-XOR-mutable check for a view-producing checkpoint.
141/// Walks the VM's *current* locals (not a static derivation tree), grouping a
142/// live reference view as conflicting when it names the same allocation, or a
143/// sub-allocation of it (`root_alloc` — `from_raw_parts`/`split_at` keep a
144/// `parent` edge), with the opposite mutability.
145fn flow_xor_violation<'z3, 'tcx>(
146    vm_state: &VmExecutor<'z3, 'tcx>,
147    checkpoint: &Checkpoint<'tcx>,
148    unique: bool,
149    stmt_index: usize,
150) -> Option<String> {
151    let origin_arg = checkpoint.args.first()?;
152    let origin_place = alias_hazard::operand_mir_place(origin_arg)?;
153    let origin_local = origin_place.local;
154    let origin_alloc = vm_state.value_of_operand(origin_arg).provenance_alloc_id()?;
155    let origin_root = vm_state.root_alloc(origin_alloc);
156    let live = alias_hazard::live_locals_at(
157        vm_state.tcx,
158        checkpoint.caller,
159        checkpoint.block,
160        stmt_index,
161        false,
162        false,
163    );
164    let body = vm_state.body();
165    for (local, val) in &vm_state.all_local_values() {
166        if *local == origin_local {
167            continue;
168        }
169        if !live.contains(local) {
170            continue;
171        }
172        let Some(prov) = &val.provenance else {
173            continue;
174        };
175        let mutability = match body.local_decls[*local].ty.kind() {
176            rustc_middle::ty::TyKind::Ref(_, _, m) => *m,
177            _ => continue,
178        };
179        let same_alloc = prov.alloc_id == origin_alloc;
180        let same_root = vm_state.root_alloc(prov.alloc_id) == origin_root;
181        if !same_alloc && !same_root {
182            continue;
183        }
184        let view_mut = mutability == rustc_middle::ty::Mutability::Mut;
185        let conflicts = if unique { !view_mut } else { view_mut };
186        if conflicts {
187            let produced = if unique { "&mut" } else { "&" };
188            let live_kind = if view_mut { "&mut" } else { "&" };
189            return Some(format!("producing {produced} while a live {live_kind} aliases the same data"));
190        }
191    }
192    None
193}
194
195fn escaped_parameter_origin<'z3, 'tcx>(
196    vm_state: &VmExecutor<'z3, 'tcx>,
197    checkpoint: &Checkpoint<'tcx>,
198    origin_arg: &Operand<'tcx>,
199) -> Option<(usize, Vec<usize>)> {
200    if !alias_hazard::destination_flows_to_return(vm_state.tcx, checkpoint.caller, checkpoint.destination) {
201        return None;
202    }
203    let origin = mir_utils::operand_mir_place(origin_arg)?;
204    let (root, fields) = crate::analysis::alias::tree::AliasTree::build(vm_state.tcx, checkpoint.caller)
205        .resolve_local_to_root(origin.local);
206    (root >= 1 && root <= vm_state.body().arg_count).then_some((root, fields))
207}
208
209/// Run the full alias hazard check for the VM backend.
210///
211/// This is the function the `PropertyChecker::check_alias` delegates to.
212pub(crate) fn check_alias_vm<'z3, 'tcx>(vm_state: &VmExecutor<'z3, 'tcx>, checkpoint: &Checkpoint<'tcx>) -> VmAliasResult {
213    let callee = match checkpoint.callee {
214        Some(c) => c,
215        None => {
216            let Some(origin_arg) = checkpoint.args.first() else {
217                return VmAliasResult::Unknown;
218            };
219            let origin_val = vm_state.value_of_operand(origin_arg);
220            // Step 4 (forward check): while the produced view is live, a later
221            // raw access through the same origin violates shared-XOR-mutable.
222            if let Some(origin_place) = alias_hazard::operand_place(origin_arg) {
223                let kind = if checkpoint.is_mut_ref {
224                    HazardKind::UniqueView
225                } else {
226                    HazardKind::SharedView
227                };
228                if let Some(reason) = alias_hazard::local_hazard_violation(
229                    vm_state.tcx,
230                    checkpoint.caller,
231                    checkpoint.block,
232                    checkpoint.destination,
233                    &[origin_place],
234                    kind,
235                    None,
236                ) {
237                    return VmAliasResult::Failed(reason);
238                }
239            }
240            if let Some(origin) = vm_state.resolve_origin(&origin_val) {
241                // Step 3 (callsite check): unless an `Alias`/`Ptr2Ref` precondition
242                // discharges the hazard, the deref must not violate shared-XOR-mutable
243                // against a live alias of the opposite mutability (tree-based,
244                // grouped by root or allocation).
245                if !origin_alias_hazard_accepted(vm_state, &origin_val)
246                    && let Some(reason) = flow_xor_violation(
247                        vm_state,
248                        checkpoint,
249                        checkpoint.is_mut_ref,
250                        checkpoint.stmt_index,
251                    )
252                {
253                    return VmAliasResult::Failed(reason);
254                }
255                if origin.is_mut_ref() {
256                    // A mut view produced through a raw field of a reference
257                    // parameter (`(*self).next`). When it escapes, trace to the
258                    // root parameter and reject a shared-reference origin.
259                    if let Some((root, fields)) = escaped_parameter_origin(vm_state, checkpoint, origin_arg) {
260                        if !fields.is_empty() {
261                            let root_ty = vm_state.body().local_decls[Local::from_usize(root)].ty;
262                            if let rustc_middle::ty::TyKind::Ref(
263                                _,
264                                _,
265                                rustc_middle::ty::Mutability::Not,
266                            ) = root_ty.kind()
267                                && checkpoint.is_mut_ref
268                            {
269                                return VmAliasResult::Failed("&mut deref through a shared reference writes immutable data".into());
270                            }
271                        }
272                    }
273                    return VmAliasResult::Proved;
274                }
275                if origin.is_shared_ref() {
276                    if checkpoint.is_mut_ref {
277                        return VmAliasResult::Failed("&mut deref through a shared reference writes immutable data".into());
278                    }
279                    // A shared view (`&*self.next`) produced through a raw field
280                    // of a reference parameter. When the view escapes (flows to
281                    // the return place), deep-resolve to that field and apply the
282                    // same encapsulation check used by the view-producer path: a
283                    // public or safe-code-exposed raw field cannot uphold the
284                    // returned `&T`.
285                    if let Some((root, fields)) = escaped_parameter_origin(vm_state, checkpoint, origin_arg) {
286                        if !fields.is_empty() {
287                            let resolved = PlaceKey::from_origin(root, fields);
288                            if let Some(sfo) = alias_hazard::self_field_origin(vm_state.tcx, checkpoint.caller, &resolved) {
289                                // A caller that already declares an `Alias`
290                                // precondition (e.g. `Ptr2Ref`) relies on its
291                                // caller rather than field encapsulation, so the
292                                // encapsulation check must not fire there.
293                                if !origin_alias_hazard_accepted(vm_state, &origin_val) {
294                                    return check_escaped_field(vm_state.tcx, checkpoint.caller, &sfo, HazardKind::SharedView);
295                                }
296                            }
297                        } else {
298                            // A direct shared-reference parameter whose view
299                            // escapes to the return must not claim a region that
300                            // outlives its own (e.g. returning a `&'b str` as
301                            // `&'a str` when `'a: 'b`).
302                            if let Some(reason) = escape_region_violation(vm_state.tcx, checkpoint.caller, root) {
303                                return VmAliasResult::Failed(reason);
304                            }
305                        }
306                    }
307                    return VmAliasResult::Proved;
308                }
309                if origin.is_owned() {
310                    return VmAliasResult::Proved;
311                }
312                // An *independent* raw-pointer *parameter* (`*const T` / `*mut T`)
313                // carries no borrow information. An `Alias`/`Ptr2Ref` precondition
314                // discharges the hazard (the caller guarantees no aliasing), and a
315                // local (non-escaping) view is safe; an escaping view without such
316                // a precondition is an undeclared aliasing hazard — not a hard
317                // violation, because the caller is an `unsafe fn` whose contract
318                // (`Alias`/`Ptr2Ref` requires) carries the obligation. A
319                // raw-pointer *field copy* (`_tmp = self.head`) is a temp local
320                // above `arg_count`, derived from a borrow field — it falls
321                // through to the field-type-aware check below.
322                if matches!(origin.kind, VmOriginKind::RawPtr)
323                    && origin.local.as_usize() <= vm_state.body().arg_count
324                {
325                    if origin_alias_hazard_accepted(vm_state, &origin_val) {
326                        return VmAliasResult::Proved;
327                    }
328                    let escapes = alias_hazard::destination_flows_to_return(vm_state.tcx, checkpoint.caller, checkpoint.destination);
329                    if !escapes {
330                        return VmAliasResult::Proved;
331                    }
332                    return VmAliasResult::Unknown;
333                }
334            }
335            // A raw-pointer deref in a method whose `self` is a *by-value*
336            // `NonNull<T>` is safe: consuming the `NonNull` transfers exclusive
337            // ownership of its pointer (e.g. `NonNull::as_uninit_mut(self)`).
338            // A *by-reference* `&NonNull<T>` / `&mut NonNull<T>` self is equally
339            // safe (`NonNull::as_ref`/`as_mut`): the reference carries the borrow
340            // (shared or exclusive) over the `NonNull`, whose pointer is the only
341            // source of the deref.
342            if vm_state.body().arg_count >= 1 {
343                let self_ty = vm_state.body().local_decls[Local::from_usize(1)].ty;
344                let nonnull_adt = match self_ty.kind() {
345                    rustc_middle::ty::TyKind::Adt(adt_def, _) => Some(*adt_def),
346                    rustc_middle::ty::TyKind::Ref(_, pointee, _) => match pointee.kind() {
347                        rustc_middle::ty::TyKind::Adt(adt_def, _) => Some(*adt_def),
348                        _ => None,
349                    },
350                    _ => None,
351                };
352                if nonnull_adt.is_some_and(|adt| type_ids::is_std_nonnull(adt.did())) {
353                    return VmAliasResult::Proved;
354                }
355            }
356            if let Some(prov) = &origin_val.provenance {
357                let is_external = vm_state.alloc(prov.alloc_id).is_external();
358                if !is_external {
359                    return VmAliasResult::Proved;
360                }
361                // External provenance: safe for shared ref, unsafe for mut ref.
362                let has_shared_ref = vm_state.body().local_decls.iter().any(|d| {
363                    matches!(
364                        d.ty.kind(),
365                        rustc_middle::ty::TyKind::Ref(_, _, rustc_middle::ty::Mutability::Not)
366                    )
367                });
368                if has_shared_ref {
369                    return VmAliasResult::Proved;
370                }
371            }
372            if origin_val.provenance.is_none() {
373                for decl in &vm_state.body().local_decls {
374                    if matches!(decl.ty.kind(), rustc_middle::ty::TyKind::Ref(..)) {
375                        return VmAliasResult::Proved;
376                    }
377                }
378            }
379            // Field-type-aware check: if the raw-ptr-deref operand traces to a
380            // struct field and that field is a shared reference, the view is safe.
381            let tcx = vm_state.tcx;
382            let caller = checkpoint.caller;
383            let arg_place = alias_hazard::operand_mir_place(origin_arg).map(PlaceKey::from_mir_place);
384            if let Some(mir_place) = arg_place {
385                let tree = crate::analysis::alias::tree::AliasTree::build(tcx, caller);
386                let local = mir_place.local().unwrap_or(Local::from_usize(1));
387                let (root, fields) = tree.resolve_local_to_root(local);
388                if !fields.is_empty() {
389                    // A raw-pointer field of a *by-value* `self` is exclusively
390                    // owned by this call only when the `self` was *moved* (not
391                    // copied), so re-borrowing it (`&mut *self.v`) cannot alias
392                    // any live reference. A `Copy` by-value `self` is copied —
393                    // the caller's copy still aliases the raw target — so it
394                    // must not be treated as exclusive. A `&`/`&mut self` is
395                    // handled by the shared/mut-ref origin paths above.
396                    let root_ty = vm_state.body().local_decls[Local::from_usize(root)].ty;
397                    if !matches!(root_ty.kind(), rustc_middle::ty::TyKind::Ref(..)) {
398                        let typing_env = rustc_middle::ty::TypingEnv::post_analysis(tcx, caller);
399                        if !tcx.type_is_copy_modulo_regions(typing_env, root_ty) {
400                            return VmAliasResult::Proved;
401                        }
402                    }
403                    let resolved = PlaceKey::from_origin(root, fields);
404                    let sfo = alias_hazard::self_field_origin(tcx, caller, &resolved);
405                    if let Some(sfo) = sfo
406                        && let Some(is_shared) = is_self_field_shared_ref(tcx, caller, &sfo)
407                            && is_shared {
408                                return VmAliasResult::Proved;
409                            }
410                }
411            }
412            return VmAliasResult::Unknown;
413        }
414    };
415
416    // NonNull::as_ref / as_mut fast-path (formerly part of Ptr2Ref checking):
417    // NonNull guarantees non-null + aligned + initialized by construction, so
418    // the only remaining question is whether the produced reference escapes.
419    // An escaping `&mut` (as_mut) is a confirmed shared-XOR-mut violation — the
420    // exclusive view is derived from a raw pointer with no borrow information,
421    // so it cannot be exclusive while the enclosing `&mut self` is still live.
422    // An escaping `&` (as_ref) is only a *possible* hazard → Unknown.
423    if let Some(mutability) = pointer_flow::nonnull_ref_return(vm_state.tcx, callee) {
424        let ret_ty = vm_state.body().local_decls[rustc_middle::mir::RETURN_PLACE].ty;
425        if mir_utils::type_contains_reference(ret_ty) {
426            if mutability == rustc_middle::mir::Mutability::Mut {
427                return VmAliasResult::Failed("escaping `&mut` derived from a raw pointer without borrow information".into());
428            }
429            return VmAliasResult::Unknown;
430        }
431        return VmAliasResult::Proved;
432    }
433
434    let Some(producer) = alias_hazard::alias_producer(vm_state.tcx, callee) else {
435        return VmAliasResult::Unknown;
436    };
437
438    match producer {
439        AliasProducer::View(kind, source_arg) => check_view_alias(vm_state, checkpoint, kind, source_arg),
440        AliasProducer::OwnershipTransfer(source_arg) => check_ownership_transfer_alias(vm_state, checkpoint, source_arg),
441        AliasProducer::ReadMemory(source_arg) => check_read_memory_alias(vm_state, checkpoint, source_arg),
442        AliasProducer::CopyMemory(source_arg) => check_copy_memory_alias(vm_state, checkpoint, source_arg),
443    }
444}
445
446fn check_view_alias<'z3, 'tcx>(
447    vm_state: &VmExecutor<'z3, 'tcx>,
448    checkpoint: &Checkpoint<'tcx>,
449    kind: HazardKind,
450    source_arg: usize,
451) -> VmAliasResult {
452    let Some(origin_arg) = checkpoint.args.get(source_arg) else {
453        return VmAliasResult::Unknown;
454    };
455    let origin_val = vm_state.value_of_operand(origin_arg);
456
457    let tcx = vm_state.tcx;
458    let caller = checkpoint.caller;
459    let call_block = checkpoint.block;
460    let destination = checkpoint.destination;
461
462    // Tree-based shared-XOR-mutable: producing a view must not conflict with a
463    // *live* opposite-mutability view of the same allocation. This runs before
464    // the `Owned`/`MutRef`/`SharedRef` fast-paths below, which otherwise prove
465    // without checking — e.g. two raw pointers split from one owned `Vec`, then
466    // `&` and `&mut` views of each while the first is still live. An
467    // `Alias`/`Ptr2Ref` precondition discharges the obligation.
468    if !origin_alias_hazard_accepted(vm_state, &origin_val)
469        && let Some(reason) = flow_xor_violation(
470            vm_state,
471            checkpoint,
472            kind == HazardKind::UniqueView,
473            usize::MAX,
474        )
475    {
476        return VmAliasResult::Failed(reason);
477    }
478
479    let origin_place = alias_hazard::operand_place(origin_arg).unwrap_or_else(|| {
480        PlaceKey::from_origin(mir_utils::extract_local(origin_arg).map(|l| l.as_usize()).unwrap_or(1), vec![])
481    });
482
483    // Trace through local origins to resolve intermediate copies/casts.
484    // e.g. `_tmp = self.ptr` → trace to `_1.0`
485    let resolved_origin = resolve_origin_place_mir(tcx, caller, &origin_place);
486    let mut origins = vec![origin_place.clone()];
487    if resolved_origin != origin_place {
488        origins.push(resolved_origin.clone());
489    }
490
491    // Also try to extract field projections from the checkpoint arg's MIR place.
492    // If the arg directly references a struct field (e.g., `(*_1).0`), capture it.
493    let mir_place_from_arg = alias_hazard::operand_mir_place(origin_arg);
494    if let Some(place) = mir_place_from_arg
495        && !place.projection.is_empty()
496        && place.local == Local::from_usize(1)
497    {
498        let field_key = PlaceKey::from_mir_place(place);
499        if !field_key.fields.is_empty() && !origins.contains(&field_key) {
500            origins.push(field_key);
501        }
502    }
503
504    if let Some(origin) = vm_state.resolve_origin(&origin_val) {
505        match (kind, origin.kind) {
506            (HazardKind::UniqueView, VmOriginKind::MutRef) => return VmAliasResult::Proved,
507            (HazardKind::SharedView, VmOriginKind::SharedRef) => {
508                // Aliasing-safe, but if the view escapes to the return, its
509                // claimed region must not outlive the source reference's region.
510                if let Some(reason) = shared_view_escape_region_violation(tcx, caller, destination, origin.local.as_usize()) {
511                    return VmAliasResult::Failed(reason);
512                }
513                return VmAliasResult::Proved;
514            }
515            (HazardKind::UniqueView, VmOriginKind::SharedRef) => {
516                // `&T` → `&mut T` violates shared-XOR-mutable regardless of
517                // field encapsulation: the caller can re-enter the method and
518                // obtain a second `&mut` to the same data.
519                return VmAliasResult::Failed("shared reference cannot produce a unique mutable view".into());
520            }
521            _ => {}
522        }
523        if origin.is_owned() {
524            let check = alias_hazard::alias_proved_for_param_local(
525                tcx,
526                caller,
527                origin.local.as_usize(),
528                kind,
529            );
530            // Skip the early Safe return for Vec/CString (reallocatable) types,
531            // so MIR-level hazard scanning can detect reallocation hazards.
532            let is_reallocatable = match &origin.kind {
533                VmOriginKind::Owned(def_id) => {
534                    type_ids::is_std_vec(*def_id) || type_ids::is_std_cstring(*def_id)
535                }
536                _ => false,
537            };
538            if matches!(check, alias_hazard::HazardCheck::Safe(_)) && !is_reallocatable {
539                return VmAliasResult::Proved;
540            }
541        }
542    }
543
544    let view_len_place = if source_arg == 0 {
545        checkpoint.args.get(1).and_then(alias_hazard::operand_place)
546    } else {
547        None
548    };
549
550    if let Some(reason) = alias_hazard::local_hazard_violation(
551        tcx,
552        caller,
553        call_block,
554        destination,
555        &origins,
556        kind,
557        view_len_place,
558    ) {
559        return VmAliasResult::Failed(reason);
560    }
561
562    let origin_pk = alias_hazard::resolve_param_origin(tcx, caller, &origin_place);
563    if let Some(local_index) = origin_pk {
564        if let alias_hazard::HazardCheck::Safe(_) = alias_hazard::alias_proved_for_param_local(tcx, caller, local_index, kind)
565        {
566            return VmAliasResult::Proved;
567        }
568    }
569
570    let dest_escapes = alias_hazard::destination_flows_to_return(tcx, caller, destination);
571    if dest_escapes {
572        let field_origin = resolve_escaped_field_origin(tcx, caller, &resolved_origin, &origin_place, checkpoint);
573        if let Some(sfo) = field_origin {
574            return check_escaped_field(tcx, caller, &sfo, kind);
575        }
576        let any_field = alias_hazard::any_struct_field_origin(tcx, caller, &resolved_origin)
577            .or_else(|| alias_hazard::any_struct_field_origin(tcx, caller, &origin_place));
578        if let Some(sfo) = any_field {
579            return check_escaped_field(tcx, caller, &sfo, kind);
580        }
581        if let Some(reason) = alias_hazard::private_fn_callsite_delegation(tcx, caller, &origin_place, kind)
582        {
583            return VmAliasResult::Failed(reason);
584        }
585        if kind == HazardKind::SharedView {
586            let param_origin = alias_hazard::resolve_param_origin(tcx, caller, &origin_place);
587            if let Some(local) = param_origin
588                && alias_hazard::is_origin_a_reference(
589                    tcx,
590                    caller,
591                    &PlaceKey::from_origin(local, vec![]),
592                )
593            {
594                // The returned reference must not claim a region that outlives
595                // the source reference's region: a shared view re-borrowed from
596                // `&'b str` cannot be returned as `&'a str` when `'a: 'b` (the
597                // source is only valid for the shorter `'b`).
598                if let Some(reason) = escape_region_violation(tcx, caller, local) {
599                    return VmAliasResult::Failed(reason);
600                }
601                return VmAliasResult::Proved;
602            }
603        }
604    }
605
606    if !dest_escapes {
607        return VmAliasResult::Proved;
608    }
609
610    // A unique view that escapes with a raw-pointer origin not backed by a
611    // private struct field is a hazard.
612    if kind == HazardKind::UniqueView {
613        let body = tcx.optimized_mir(caller);
614        if body.arg_count >= 1 {
615            let self_ty = body.local_decls[Local::from_usize(1)].ty;
616            // A `NonNull<T>` consumed by value (e.g. `NonNull::as_uninit_mut(self)`)
617            // transfers exclusive ownership of its pointer, so producing a unique
618            // view is safe even though the receiver is not a `&mut self`.
619            if let rustc_middle::ty::TyKind::Adt(adt_def, _) = self_ty.kind()
620                && type_ids::is_std_nonnull(adt_def.did()) {
621                    return VmAliasResult::Proved;
622                }
623        }
624        return VmAliasResult::Failed(format!(
625            "returned unique view escapes while the original pointer is not owned by a private self field [origin={:?}]",
626            origin_place
627        ));
628    }
629
630    VmAliasResult::Proved
631}
632
633/// A shared view re-borrowed from the reference parameter `local` and returned
634/// must not claim a region that outlives the parameter's own region. Returns a
635/// violation reason when `local`'s region does not outlive the return region.
636fn shared_view_escape_region_violation(
637    tcx: rustc_middle::ty::TyCtxt<'_>,
638    caller: DefId,
639    destination: Option<Local>,
640    local: usize,
641) -> Option<String> {
642    if !alias_hazard::destination_flows_to_return(tcx, caller, destination) {
643        return None;
644    }
645    escape_region_violation(tcx, caller, local)
646}
647
648/// Check whether the shared view's claimed return region outlives the source
649/// reference `local`'s region. Returns a violation reason when it does.
650fn escape_region_violation(
651    tcx: rustc_middle::ty::TyCtxt<'_>,
652    caller: DefId,
653    local: usize,
654) -> Option<String> {
655    // MIR `local_decls` erases lifetime regions (`ReErased`), so take the
656    // precise (late-bound-liberated) regions from the function signature.
657    let src_region =
658        crate::vm::region::fn_arg_ty(tcx, caller, local - 1).and_then(|ty| match ty.kind() {
659            rustc_middle::ty::TyKind::Ref(region, _, _) => Some(*region),
660            _ => None,
661        })?;
662    let ret_region = crate::vm::region::fn_return_region(tcx, caller)?;
663    if !crate::vm::region::region_outlives(tcx, caller, src_region, ret_region) {
664        return Some(format!(
665            "returned region `{ret_region:?}` outlives the source reference's region `{src_region:?}`"
666        ));
667    }
668    None
669}
670
671fn self_field_origin(
672    tcx: rustc_middle::ty::TyCtxt<'_>,
673    struct_def_id: DefId,
674    field_index: usize,
675) -> Option<FieldOrigin> {
676    let field = tcx.adt_def(struct_def_id).all_fields().nth(field_index)?;
677    Some(FieldOrigin {
678        struct_def_id,
679        field_index,
680        field_name: field.name.to_string(),
681    })
682}
683
684/// Find a self field origin through the checkpoint argument or a copied local.
685fn find_struct_field_origin_for_param<'tcx>(
686    tcx: rustc_middle::ty::TyCtxt<'tcx>,
687    caller: DefId,
688    checkpoint: &Checkpoint<'tcx>,
689) -> Option<FieldOrigin> {
690    let body = tcx.optimized_mir(caller);
691    let (adt_def, _) = self_adt(tcx, caller)?;
692
693    let arg0 = checkpoint.args.first()?;
694    let arg_place = match arg0 {
695        Operand::Copy(p) | Operand::Move(p) => p,
696        _ => return None,
697    };
698
699    if !arg_place.projection.is_empty() && arg_place.local == Local::from_usize(1) {
700        let field_index = arg_place
701            .projection
702            .iter()
703            .find_map(|p| match p {
704                ProjectionElem::Field(idx, _) => Some(idx.as_usize()),
705                _ => None,
706            });
707        if let Some(field_index) = field_index {
708            return self_field_origin(tcx, adt_def, field_index);
709        }
710    }
711
712    let arg_local = arg_place.local;
713    if arg_place.projection.is_empty() && arg_local != Local::from_usize(1) {
714        for block in body.basic_blocks.iter() {
715            for stmt in &block.statements {
716                let StatementKind::Assign(assign) = &stmt.kind else {
717                    continue;
718                };
719                let (target, rvalue) = assign.as_ref();
720                if target.local != arg_local {
721                    continue;
722                }
723                let source = match rvalue {
724                    Rvalue::Use(Operand::Copy(p) | Operand::Move(p), ..) => p,
725                    Rvalue::CopyForDeref(p) => p,
726                    _ => continue,
727                };
728                if source.local != Local::from_usize(1) {
729                    continue;
730                }
731                let field_index = source
732                    .projection
733                    .iter()
734                    .find_map(|p| match p {
735                        ProjectionElem::Field(idx, _) => Some(idx.as_usize()),
736                        _ => None,
737                    });
738                let Some(field_index) = field_index else {
739                    continue;
740                };
741                return self_field_origin(tcx, adt_def, field_index);
742            }
743        }
744    }
745
746    None
747}
748
749/// Check whether a self field's type is a shared reference (`&T` or `&[T]`).
750/// Used by raw-ptr-deref alias checks to prove shared views are safe when the
751/// underlying field is a shared reference.
752fn is_self_field_shared_ref(
753    tcx: rustc_middle::ty::TyCtxt<'_>,
754    caller: DefId,
755    origin: &FieldOrigin,
756) -> Option<bool> {
757    let (adt_def, args) = self_adt(tcx, caller)?;
758    if adt_def != origin.struct_def_id {
759        return Some(false);
760    }
761    let adt = tcx.adt_def(adt_def);
762    let field = adt.all_fields().nth(origin.field_index)?;
763    let field_ty = mir_utils::field_ty(tcx, field, args);
764    Some(matches!(field_ty.kind(), rustc_middle::ty::TyKind::Ref(_, _, rustc_middle::ty::Mutability::Not)))
765}
766
767/// Shared escape + field-encapsulation check: a view that escapes and traces to
768/// a struct field is safe only if the field is private and not written/exposed
769/// by safe code. A unique (`&mut`) view escaping through a private raw field is
770/// still unsound — the caller can re-enter and obtain a second `&mut`.
771fn check_escaped_field(
772    tcx: rustc_middle::ty::TyCtxt<'_>,
773    caller: DefId,
774    sfo: &FieldOrigin,
775    kind: HazardKind,
776) -> VmAliasResult {
777    if let Some(reason) = alias_hazard::escaped_self_field_violation(tcx, caller, sfo) {
778        return VmAliasResult::Failed(reason);
779    }
780    if kind == HazardKind::UniqueView {
781        return VmAliasResult::Failed("unique view escapes through a private raw field".into());
782    }
783    VmAliasResult::Proved
784}
785
786/// Resolve the struct field an escaping view came from: try the derivation tree
787/// first (via the resolved and raw origins), then fall back to self-type
788/// heuristics when tree resolution fails to reach a field.
789fn resolve_escaped_field_origin<'tcx>(
790    tcx: rustc_middle::ty::TyCtxt<'tcx>,
791    caller: DefId,
792    resolved_origin: &PlaceKey,
793    origin_place: &PlaceKey,
794    checkpoint: &Checkpoint<'tcx>,
795) -> Option<FieldOrigin> {
796    alias_hazard::self_field_origin(tcx, caller, resolved_origin)
797        .or_else(|| alias_hazard::self_field_origin(tcx, caller, origin_place))
798        .or_else(|| find_struct_field_origin_for_param(tcx, caller, checkpoint))
799}
800
801/// Trace a local through copies and casts (e.g. `_tmp = self.ptr` → `_1.0`).
802fn resolve_origin_place_mir(
803    tcx: rustc_middle::ty::TyCtxt<'_>,
804    caller: DefId,
805    place: &PlaceKey,
806) -> PlaceKey {
807    let Some(local) = place.local() else {
808        return place.clone();
809    };
810    let tree = crate::analysis::alias::tree::AliasTree::build(tcx, caller);
811    let (root_local, mut root_fields) = tree.resolve_local_to_root(local);
812
813    if root_local == local.as_usize() && root_fields.is_empty() && !place.fields.is_empty() {
814        root_fields = place.fields.clone();
815    }
816
817    // Combine: root's fields + any additional projections from the resolved chain
818    // (e.g. if place = _tmp, root = _1 with fields [0], keep fields [0])
819    if root_fields.is_empty() && !place.fields.is_empty() {
820        return place.clone();
821    }
822
823    PlaceKey::from_origin(root_local, root_fields)
824}
825
826/// Extract the `&self`/`&mut self` receiver's ADT (peeling one reference layer),
827/// or `None` for non-ADT receivers.  Shared by the struct-field origin heuristics.
828fn self_adt<'tcx>(
829    tcx: rustc_middle::ty::TyCtxt<'tcx>,
830    caller: DefId,
831) -> Option<(DefId, GenericArgsRef<'tcx>)> {
832    let body = tcx.optimized_mir(caller);
833    if body.arg_count == 0 {
834        return None;
835    }
836    let self_ty = body.local_decls[Local::from_usize(1)].ty;
837    let inner = match self_ty.kind() {
838        rustc_middle::ty::TyKind::Ref(_, inner, _) => *inner,
839        _ => return None,
840    };
841    crate::analysis::alias::adt_from_ty(inner)
842}
843
844fn check_ownership_transfer_alias<'z3, 'tcx>(
845    vm_state: &VmExecutor<'z3, 'tcx>,
846    checkpoint: &Checkpoint<'tcx>,
847    source_arg: usize,
848) -> VmAliasResult {
849    let Some(origin_arg) = checkpoint.args.get(source_arg) else {
850        return VmAliasResult::Unknown;
851    };
852
853    let tcx = vm_state.tcx;
854    let caller = checkpoint.caller;
855    let call_block = checkpoint.block;
856    let destination = checkpoint.destination;
857
858    let origin_place = alias_hazard::operand_place(origin_arg);
859    let Some(origin_place) = origin_place else {
860        return VmAliasResult::Unknown;
861    };
862
863    if let Some(reason) = alias_hazard::ownership_transfer_violation(
864        tcx,
865        caller,
866        call_block,
867        destination,
868        &origin_place,
869    ) {
870        return VmAliasResult::Failed(reason);
871    }
872
873    VmAliasResult::Proved
874}
875
876fn check_read_memory_alias<'z3, 'tcx>(
877    vm_state: &VmExecutor<'z3, 'tcx>,
878    checkpoint: &Checkpoint<'tcx>,
879    source_arg: usize,
880) -> VmAliasResult {
881    let Some(origin_arg) = checkpoint.args.get(source_arg) else {
882        return VmAliasResult::Unknown;
883    };
884
885    let origin_val = vm_state.value_of_operand(origin_arg);
886
887    // If the enclosing function accepted the structural-alias hazard for *this*
888    // origin's allocation (via `Alias(self, ret)` in its contract), the read is
889    // the accepted hazard rather than a violation.
890    if let Some(alloc_id) = origin_val.provenance_alloc_id()
891        && vm_state.has_alias_hazard(alloc_id)
892    {
893        return VmAliasResult::Proved;
894    }
895
896    if let rustc_middle::ty::TyKind::RawPtr(pointee, _) = origin_val.ty.kind() {
897        let tcx = vm_state.tcx;
898        let typing_env = rustc_middle::ty::TypingEnv::post_analysis(tcx, checkpoint.caller);
899        if tcx.type_is_copy_modulo_regions(typing_env, *pointee) {
900            return VmAliasResult::Proved;
901        }
902    }
903
904    let tcx = vm_state.tcx;
905    let destination = checkpoint.destination;
906    if !alias_hazard::destination_flows_to_return(tcx, checkpoint.caller, destination) {
907        return VmAliasResult::Proved;
908    }
909
910    VmAliasResult::Failed("read API value escapes while the source pointer persists — structural alias hazard".into())
911}
912
913fn check_copy_memory_alias<'z3, 'tcx>(
914    vm_state: &VmExecutor<'z3, 'tcx>,
915    checkpoint: &Checkpoint<'tcx>,
916    source_arg: usize,
917) -> VmAliasResult {
918    let Some(origin_arg) = checkpoint.args.get(source_arg) else {
919        return VmAliasResult::Unknown;
920    };
921    let origin_val = vm_state.value_of_operand(origin_arg);
922    if let Some(alloc_id) = origin_val.provenance_alloc_id()
923        && vm_state.has_alias_hazard(alloc_id)
924    {
925        return VmAliasResult::Proved;
926    }
927    if let rustc_middle::ty::TyKind::RawPtr(pointee, _) = origin_val.ty.kind() {
928        let typing_env = rustc_middle::ty::TypingEnv::post_analysis(vm_state.tcx, checkpoint.caller);
929        if vm_state.tcx.type_is_copy_modulo_regions(typing_env, *pointee) {
930            return VmAliasResult::Proved;
931        }
932    }
933    VmAliasResult::Unknown
934}