Skip to main content

rapx/verify/
checkpoint.rs

1//! Verification checkpoint types and their MIR collection.
2//!
3//! A [`Checkpoint`] is a point in a function body that must be verified: an
4//! unsafe call, a MIR intrinsic, a raw-pointer dereference, or a `static mut` access.  The
5//! `collect_*` functions scan MIR and attach safety requirements; the rest of
6//! the verifier consumes the resulting records.
7
8use crate::def_ids::intrinsic_api;
9#[cfg(not(rapx_box_deref_transmute))]
10use crate::def_ids::lang_api::{self, LangItem};
11use crate::util::{
12    mir_scan::{get_fn_safety, place_has_raw_deref},
13    mir_utils::pointee_ty,
14    name::get_cleaned_def_path_name,
15};
16
17use rustc_hir::{def_id::DefId, Safety};
18use rustc_middle::{
19    mir::{
20        BasicBlock, Body, Local, NonDivergingIntrinsic, Operand, Place, ProjectionElem, Rvalue,
21        StatementKind, TerminatorKind,
22    },
23    ty::{self, List, Ty, TyCtxt},
24};
25#[cfg(rapx_box_deref_transmute)]
26use rustc_middle::mir::CastKind;
27#[cfg(not(rapx_box_deref_transmute))]
28use rustc_middle::ty::TyKind;
29use std::collections::HashSet;
30
31use crate::contract::{
32    ContractExpr, ContractKind, ContractPlace, PlaceBase, Property, PropertyArg, PropertyKind,
33};
34
35/// MIR block containing a verification checkpoint.
36///
37/// # Agent Rules
38/// Do not add new fields to this struct.
39#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
40pub struct CheckpointLocation {
41    /// Function containing the operation.
42    pub caller: DefId,
43    /// Basic block containing the operation.
44    pub block: BasicBlock,
45}
46
47/// Kind of an unsafe verification checkpoint inside a function body.
48///
49/// # Agent Rules
50/// Do not add new variants to this enum.
51#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
52pub enum CheckpointKind {
53    /// An unsafe call, including one lowered to a MIR intrinsic statement.
54    UnsafeCall,
55    /// A raw pointer dereference.
56    RawPtrDeref,
57    /// A mutable static variable access.
58    StaticMutAccess,
59}
60
61/// A point in a function's MIR whose safety requirements are checked.
62///
63/// Most checkpoints are unsafe function calls. Calls lowered to MIR intrinsics,
64/// raw-pointer dereferences, and `static mut` accesses use the same representation
65/// and follow the same path extraction and verification pipeline.
66///
67/// # Agent Rules
68/// Do not add new fields to this struct.
69#[derive(Clone, Debug)]
70pub(crate) struct Checkpoint<'tcx> {
71    // Function and operation data.
72    pub(super) caller: DefId,
73    pub(super) callee: Option<DefId>,
74    pub(super) args: Vec<Operand<'tcx>>,
75    /// Local produced by this operation, if any.
76    pub(super) destination: Option<Local>,
77
78    // Position in the caller's MIR.
79    pub(super) block: BasicBlock,
80    /// Position of this checkpoint within the MIR block.
81    pub(super) stmt_index: usize,
82
83    // Verification semantics.
84    pub(super) kind: CheckpointKind,
85    /// Requirements attached directly to this MIR operation.
86    pub(super) requires: Vec<Property<'tcx>>,
87
88    // Variant-specific metadata.
89    /// For `RawPtrDeref` checkpoints: whether the deref produces a mutable
90    /// reference (`&mut *ptr`) rather than a shared one (`&*ptr`).
91    pub(super) is_mut_ref: bool,
92}
93
94impl<'tcx> Checkpoint<'tcx> {
95    /// Return the MIR location that identifies this checkpoint inside the verifier.
96    pub fn location(&self) -> CheckpointLocation {
97        CheckpointLocation {
98            caller: self.caller,
99            block: self.block,
100        }
101    }
102
103    /// Return a human-readable label for diagnostics.
104    pub fn callee_name(&self, tcx: TyCtxt<'tcx>) -> String {
105        match self.callee {
106            Some(def_id) => get_cleaned_def_path_name(tcx, def_id),
107            None => match self.kind {
108                CheckpointKind::RawPtrDeref => "raw-ptr-deref".to_string(),
109                CheckpointKind::StaticMutAccess => "static-mut-access".to_string(),
110                CheckpointKind::UnsafeCall => {
111                    let body = tcx.optimized_mir(self.caller);
112                    match body.basic_blocks[self.block]
113                        .statements
114                        .get(self.stmt_index)
115                        .map(|statement| &statement.kind)
116                    {
117                        Some(StatementKind::Intrinsic(intrinsic)) => {
118                            intrinsic_api::lowered_mir_path(intrinsic).to_string()
119                        }
120                        _ => "unknown-callee".to_string(),
121                    }
122                }
123            },
124        }
125    }
126}
127
128/// Collect unsafe calls in `def_id`'s optimized MIR as verification checkpoints.
129///
130/// This includes unsafe `Call` and `TailCall` terminators and calls to `assume`
131/// or `copy_nonoverlapping` that rustc lowered to intrinsic statements. A direct
132/// call records its `DefId`; an unsafe function-pointer call has no known callee
133/// and records `None`. Each checkpoint retains the call arguments and MIR position
134/// for later contract lookup and path analysis. Functions without MIR yield no
135/// checkpoints. Raw-pointer dereferences and `static mut` accesses are collected
136/// separately.
137///
138/// # Agent Rules
139/// Do not modify this function without human permission.
140pub fn collect_unsafe_callsites<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Vec<Checkpoint<'tcx>> {
141    let mut checkpoints = Vec::new();
142    if !tcx.is_mir_available(def_id) {
143        return checkpoints;
144    }
145
146    let body = tcx.optimized_mir(def_id);
147    for (bb, data) in body.basic_blocks.iter_enumerated() {
148        for (stmt_index, statement) in data.statements.iter().enumerate() {
149            if let StatementKind::Intrinsic(intrinsic) = &statement.kind {
150                let args = match &**intrinsic {
151                    NonDivergingIntrinsic::CopyNonOverlapping(copy) => {
152                        vec![copy.src.clone(), copy.dst.clone(), copy.count.clone()]
153                    }
154                    NonDivergingIntrinsic::Assume(condition) => vec![condition.clone()],
155                };
156                checkpoints.push(Checkpoint {
157                    caller: def_id,
158                    callee: intrinsic_api::lowered_mir_def_id(tcx, intrinsic),
159                    block: bb,
160                    args,
161                    kind: CheckpointKind::UnsafeCall,
162                    requires: Vec::new(),
163                    destination: None,
164                    is_mut_ref: false,
165                    stmt_index,
166                });
167            }
168        }
169
170        let (func, args, destination) = match &data.terminator().kind {
171            TerminatorKind::Call {
172                func,
173                args,
174                destination,
175                ..
176            } => (func, args, Some(destination.local)),
177            TerminatorKind::TailCall { func, args, .. } => (func, args, None),
178            _ => continue,
179        };
180
181        let func_ty = match func {
182            Operand::Constant(func_constant) => func_constant.const_.ty(),
183            Operand::Copy(place) | Operand::Move(place) => place.ty(body, tcx).ty,
184            Operand::RuntimeChecks(_) => continue,
185        };
186        let ty::FnDef(callee_def_id, _) = func_ty.kind() else {
187            if let ty::FnPtr(_, header) = func_ty.kind()
188                && header.safety() == Safety::Unsafe
189            {
190                checkpoints.push(Checkpoint {
191                    caller: def_id,
192                    callee: None,
193                    block: bb,
194                    args: args.iter().map(|arg| arg.node.clone()).collect(),
195                    kind: CheckpointKind::UnsafeCall,
196                    requires: Vec::new(),
197                    destination,
198                    is_mut_ref: false,
199                    stmt_index: data.statements.len(),
200                });
201            }
202            continue;
203        };
204        if get_fn_safety(tcx, *callee_def_id) != Safety::Unsafe {
205            continue;
206        }
207
208        checkpoints.push(Checkpoint {
209            caller: def_id,
210            callee: Some(*callee_def_id),
211            block: bb,
212            args: args.iter().map(|arg| arg.node.clone()).collect(),
213            kind: CheckpointKind::UnsafeCall,
214            requires: Vec::new(),
215            destination,
216            is_mut_ref: false,
217            stmt_index: data.statements.len(),
218        });
219    }
220
221    checkpoints
222}
223
224/// Locals that hold the result of the compiler's safe `*box` deref lowering
225/// (directly, or through copies and pointer casts). The compiler lowers `*box`
226/// to a raw-pointer deref of a pointer produced by casting the box's inner
227/// field to a raw pointer, and that deref is safe by the `Box` invariant, so it
228/// is not a raw-pointer-deref checkpoint.
229fn box_deref_transmute_locals<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> HashSet<Local> {
230    let mut result = HashSet::new();
231    let mut changed = true;
232    while changed {
233        changed = false;
234        for bb in body.basic_blocks.iter() {
235            for stmt in &bb.statements {
236                let StatementKind::Assign(assign) = &stmt.kind else {
237                    continue;
238                };
239                let (target, rhs) = &**assign;
240                if !target.projection.is_empty() {
241                    continue;
242                }
243                let from_box = if is_box_deref_cast(tcx, body, rhs) {
244                    true
245                } else if let Rvalue::Use(Operand::Copy(p) | Operand::Move(p), ..)
246                | Rvalue::Cast(_, Operand::Copy(p) | Operand::Move(p), _) = rhs
247                {
248                    p.projection.is_empty() && result.contains(&p.local)
249                } else {
250                    false
251                };
252                if from_box && result.insert(target.local) {
253                    changed = true;
254                }
255            }
256        }
257    }
258    result
259}
260
261/// Whether `rvalue` is the compiler's lowering of the safe `*box` deref.
262///
263/// On recent nightlies the compiler tags this cast `BoxDerefTransmute` — a
264/// precise, dedicated marker, so match it exactly and never treat other casts
265/// of a `Box`-typed local (e.g. `transmute::<Box<T>, *mut T>`) as safe. On older
266/// toolchains that lower `*box` to a plain `Transmute` of the `Unique`/`NonNull`
267/// field, fall back to checking the cast source base local's type.
268fn is_box_deref_cast(tcx: TyCtxt<'_>, body: &Body<'_>, rvalue: &Rvalue<'_>) -> bool {
269    #[cfg(rapx_box_deref_transmute)]
270    {
271        let _ = (tcx, body);
272        matches!(rvalue, Rvalue::Cast(CastKind::BoxDerefTransmute, _, _))
273    }
274    #[cfg(not(rapx_box_deref_transmute))]
275    {
276        let Rvalue::Cast(_, Operand::Copy(p) | Operand::Move(p), _) = rvalue else {
277            return false;
278        };
279        // The safe `*box` deref casts the box's `Unique`/`NonNull` *field* (a
280        // projection); casting the whole box value is `transmute::<Box<T>, *mut
281        // T>`, an explicit unsafe transmute that must not be skipped.
282        if p.projection.is_empty() {
283            return false;
284        }
285        let base_ty = body.local_decls[p.local].ty;
286        matches!(
287            base_ty.kind(),
288            TyKind::Adt(adt, _) if lang_api::matches(tcx, adt.did(), LangItem::OwnedBox)
289        )
290    }
291}
292
293#[derive(Clone, Copy, PartialEq, Eq)]
294enum RawPtrAccess {
295    Write,
296    Read,
297    SharedRef,
298    MutRef,
299}
300
301/// Collect raw pointer dereferences and their safety requirements.
302pub fn collect_raw_ptr_deref_checkpoints<'tcx>(
303    tcx: TyCtxt<'tcx>,
304    def_id: DefId,
305) -> Vec<Checkpoint<'tcx>> {
306    let mut checkpoints = Vec::new();
307    if !tcx.is_mir_available(def_id) {
308        return checkpoints;
309    }
310
311    let body = tcx.optimized_mir(def_id);
312    // The compiler lowers `*box` to a raw-pointer deref of the pointer produced
313    // by casting the box's inner field to a raw pointer; that deref is safe by
314    // the `Box` invariant, so it is not a raw-pointer-deref checkpoint.
315    let box_derefs = box_deref_transmute_locals(tcx, body);
316    // Filter out inlined library code, but keep macro expansions invoked from
317    // this function's source file.
318    let fn_span = tcx.def_span(def_id);
319    let source_map = tcx.sess.source_map();
320    let local_file = source_map.lookup_char_pos(fn_span.lo()).file;
321    let in_fn_file = |span: rustc_span::Span| {
322        let file = source_map.lookup_char_pos(span.source_callsite().lo()).file;
323        std::sync::Arc::ptr_eq(&file, &local_file)
324    };
325
326    for (bb, data) in body.basic_blocks.iter_enumerated() {
327        let mut push_deref = |place: &Place<'tcx>, stmt_index, access, destination| {
328            // Skip safe `*box` derefs (see `box_deref_transmute_locals`).
329            if !place_has_raw_deref(body, place) || box_derefs.contains(&place.local) {
330                return;
331            }
332            let Some(ptr) = ptr_operand_for_deref_place(place) else {
333                return;
334            };
335            let Some(pointee_ty) = pointee_ty(body.local_decls[place.local].ty) else {
336                return;
337            };
338            checkpoints.push(Checkpoint {
339                caller: def_id,
340                callee: None,
341                block: bb,
342                args: vec![ptr],
343                kind: CheckpointKind::RawPtrDeref,
344                requires: raw_ptr_deref_requirements(pointee_ty, access),
345                is_mut_ref: access == RawPtrAccess::MutRef,
346                destination,
347                stmt_index,
348            });
349        };
350
351        for (stmt_index, stmt) in data.statements.iter().enumerate() {
352            if !in_fn_file(stmt.source_info.span) {
353                continue;
354            }
355            let StatementKind::Assign(assign) = &stmt.kind else {
356                continue;
357            };
358            let (lhs, rhs) = &**assign;
359
360            let is_write = place_has_raw_deref(body, lhs);
361            if is_write {
362                push_deref(lhs, stmt_index, RawPtrAccess::Write, None);
363            }
364            let destination = (!is_write).then_some(lhs.local);
365            match rhs {
366                Rvalue::Use(Operand::Copy(place) | Operand::Move(place), ..)
367                | Rvalue::Discriminant(place) => {
368                    push_deref(place, stmt_index, RawPtrAccess::Read, destination);
369                }
370                Rvalue::Ref(_, borrow_kind, place) => {
371                    let access = if matches!(borrow_kind, rustc_middle::mir::BorrowKind::Mut { .. }) {
372                        RawPtrAccess::MutRef
373                    } else {
374                        RawPtrAccess::SharedRef
375                    };
376                    push_deref(place, stmt_index, access, destination);
377                }
378                _ => {}
379            }
380        }
381
382        let terminator = data.terminator();
383        if !in_fn_file(terminator.source_info.span) {
384            continue;
385        }
386        let TerminatorKind::Drop { place, .. } = &terminator.kind else {
387            continue;
388        };
389        push_deref(place, data.statements.len(), RawPtrAccess::Read, None);
390    }
391
392    checkpoints
393}
394
395fn raw_ptr_deref_requirements<'tcx>(
396    pointee: Ty<'tcx>,
397    access: RawPtrAccess,
398) -> Vec<Property<'tcx>> {
399    let target = PropertyArg::Expr(ContractExpr::Place(ContractPlace {
400        base: PlaceBase::Arg(0),
401        projections: vec![],
402    }));
403    let ty = PropertyArg::Ty(pointee);
404    let count = PropertyArg::Expr(ContractExpr::Const(1));
405    let range_args = || vec![target.clone(), ty.clone(), count.clone()];
406
407    let is_ref = matches!(access, RawPtrAccess::SharedRef | RawPtrAccess::MutRef);
408    let mut properties = Vec::new();
409    if is_ref {
410        properties.push(Property::new_atom(PropertyKind::Init, range_args()));
411        properties.push(Property::new_atom(
412            PropertyKind::NonNull,
413            vec![target.clone()],
414        ));
415    }
416    properties.extend([
417        Property::new_atom(PropertyKind::Allocated, range_args()),
418        Property::new_atom(PropertyKind::InBound, range_args()),
419        Property::new_atom(PropertyKind::Align, vec![target.clone(), ty.clone()]),
420    ]);
421    if is_ref {
422        let mut alias = Property::new_atom(PropertyKind::Alias, vec![target.clone()]);
423        alias.set_contract_kind(ContractKind::Hazard);
424        properties.push(alias);
425    }
426    if access == RawPtrAccess::Read {
427        properties.push(Property::new_atom(PropertyKind::Typed, vec![target, ty]));
428    }
429    properties
430}
431
432/// Extract the pointer operand from a dereference place.
433fn ptr_operand_for_deref_place<'tcx>(place: &Place<'tcx>) -> Option<Operand<'tcx>> {
434    let first_deref_idx = place
435        .projection
436        .iter()
437        .position(|p| matches!(p.kind(), ProjectionElem::Deref));
438
439    if let Some(idx) = first_deref_idx
440        && idx > 0
441    {
442        return None;
443    }
444
445    Some(Operand::Copy(Place {
446        local: place.local,
447        projection: List::empty(),
448    }))
449}
450
451/// Collect checkpoints for mutable static accesses in `def_id`.
452///
453/// Mutable statics appear as `Constant` operands whose `check_static_ptr` points
454/// to a `static mut` item.  Both reads and writes are detected here; the
455/// conservative `Init` property will be checked regardless of direction.
456pub fn collect_static_mut_checkpoints<'tcx>(
457    tcx: TyCtxt<'tcx>,
458    def_id: DefId,
459) -> Vec<Checkpoint<'tcx>> {
460    let mut checkpoints = Vec::new();
461    if !tcx.is_mir_available(def_id) {
462        return checkpoints;
463    }
464
465    let body = tcx.optimized_mir(def_id);
466    for (bb, data) in body.basic_blocks.iter_enumerated() {
467        for (stmt_index, stmt) in data.statements.iter().enumerate() {
468            if let StatementKind::Assign(assign) = &stmt.kind {
469                let (_lhs, rhs) = &**assign;
470                if let Rvalue::Use(op @ Operand::Constant(c), ..) = rhs
471                    && let Some(static_id) = c.check_static_ptr(tcx)
472                    && matches!(tcx.static_mutability(static_id), Some(m) if m.is_mut())
473                {
474                    checkpoints.push(static_mut_checkpoint(
475                        tcx, def_id, bb, stmt_index, op.clone(), static_id,
476                    ));
477                }
478            }
479        }
480
481        if let Some(terminator) = &data.terminator
482            && let TerminatorKind::Call { args, .. } | TerminatorKind::TailCall { args, .. } =
483                &terminator.kind
484        {
485            for arg in args {
486                if let op @ Operand::Constant(c) = &arg.node
487                    && let Some(static_id) = c.check_static_ptr(tcx)
488                    && matches!(tcx.static_mutability(static_id), Some(m) if m.is_mut())
489                {
490                    checkpoints.push(static_mut_checkpoint(
491                        tcx, def_id, bb, data.statements.len(), op.clone(), static_id,
492                    ));
493                }
494            }
495        }
496    }
497
498    checkpoints
499}
500
501fn static_mut_checkpoint<'tcx>(
502    tcx: TyCtxt<'tcx>,
503    caller: DefId,
504    block: BasicBlock,
505    stmt_index: usize,
506    operand: Operand<'tcx>,
507    static_id: DefId,
508) -> Checkpoint<'tcx> {
509    let ty = PropertyArg::Ty(tcx.type_of(static_id).skip_binder());
510    let target = PropertyArg::Expr(ContractExpr::Place(ContractPlace {
511        base: PlaceBase::Arg(0),
512        projections: vec![],
513    }));
514    let count = PropertyArg::Expr(ContractExpr::Const(1));
515    Checkpoint {
516        caller,
517        callee: None,
518        args: vec![operand],
519        destination: None,
520        block,
521        stmt_index,
522        kind: CheckpointKind::StaticMutAccess,
523        requires: vec![
524            Property::new_atom(
525                PropertyKind::Allocated,
526                vec![target.clone(), ty.clone(), count.clone()],
527            ),
528            Property::new_atom(
529                PropertyKind::InBound,
530                vec![target.clone(), ty.clone(), count.clone()],
531            ),
532            Property::new_atom(PropertyKind::Align, vec![target.clone(), ty.clone()]),
533            Property::new_atom(PropertyKind::Init, vec![target, ty, count]),
534        ],
535        is_mut_ref: false,
536    }
537}