Skip to main content

rapx/analysis/dataflow/call_summary/
pointer_semantics.rs

1//! VM rules for pointer-preserving calls and owner lifetimes.
2
3use std::collections::HashMap;
4
5use rustc_hir::def_id::DefId;
6use rustc_middle::{
7    mir::{Body, Operand, ProjectionElem, StatementKind, TerminatorKind},
8    ty::{Ty, TyCtxt, TyKind},
9};
10
11use crate::analysis::dataflow::pointer_flow::{is_nonnull_view, return_source_arg};
12use crate::util::mir_utils;
13
14/// Whether MIR shows a read-only pointer view of the first argument.
15pub(crate) fn is_benign_origin_use(tcx: TyCtxt<'_>, callee: Option<DefId>) -> bool {
16    callee.is_some_and(|did| is_read_only_return(tcx, did) || is_read_only_nonnull_view(tcx, did))
17}
18
19/// A `NonNull` view that leaves its input allocation unchanged.
20pub(crate) fn is_read_only_nonnull_view(tcx: TyCtxt<'_>, callee: DefId) -> bool {
21    is_nonnull_view(tcx, callee) && single_block_without_effects(tcx.optimized_mir(callee))
22}
23
24/// A pointer result from a single, side-effect-free MIR block is safe to use
25/// while tracking an existing pointer origin.
26pub(crate) fn is_read_only_return(tcx: TyCtxt<'_>, callee: DefId) -> bool {
27    if return_source_arg(tcx, callee) != Some(0) {
28        return false;
29    }
30    let inputs = tcx.fn_sig(callee).skip_binder().inputs().skip_binder();
31    if !inputs
32        .first()
33        .is_some_and(|ty| mir_utils::pointee_ty(*ty).is_some())
34    {
35        return false;
36    }
37    single_block_without_effects(tcx.optimized_mir(callee))
38}
39
40/// A consumed owner remains allocated when a side-effect-free MIR body
41/// returns its pointer without running a destructor.
42pub(crate) fn returns_undropped_arg(tcx: TyCtxt<'_>, callee: DefId, arg: usize) -> bool {
43    return_source_arg(tcx, callee) == Some(arg)
44        && single_block_without_effects(tcx.optimized_mir(callee))
45}
46
47/// A single return block with no writes through a dereferenced place.
48pub(crate) fn single_block_without_effects(body: &Body<'_>) -> bool {
49    let [block] = &body.basic_blocks[..] else {
50        return false;
51    };
52    matches!(block.terminator().kind, TerminatorKind::Return)
53        && block.statements.iter().all(|stmt| match &stmt.kind {
54            StatementKind::Assign(assign) => !assign
55                .0
56                .projection
57                .iter()
58                .any(|p| matches!(p, rustc_middle::mir::ProjectionElem::Deref)),
59            StatementKind::StorageLive(_) | StatementKind::StorageDead(_) | StatementKind::Nop => {
60                true
61            }
62            _ => false,
63        })
64}
65
66/// Whether a callee can replace a pointer stored in one of its objects.
67/// This follows MIR calls rather than identifying container methods by name.
68pub(crate) fn callsite_replaces_pointer_field(tcx: TyCtxt<'_>, func: &Operand<'_>) -> bool {
69    let Some(callee) = mir_utils::dep_callee_def_id(func) else {
70        return false;
71    };
72    replaces_pointer_field_rec(tcx, callee, 0, &mut HashMap::new())
73}
74
75fn replaces_pointer_field_rec(
76    tcx: TyCtxt<'_>,
77    callee: DefId,
78    depth: usize,
79    visited: &mut HashMap<DefId, usize>,
80) -> bool {
81    if depth > 10
82        || !tcx.is_mir_available(callee)
83        || visited
84            .get(&callee)
85            .is_some_and(|&previous| previous <= depth)
86    {
87        return false;
88    }
89    visited.insert(callee, depth);
90    let body = tcx.optimized_mir(callee);
91    for block in body.basic_blocks.iter() {
92        for statement in &block.statements {
93            let StatementKind::Assign(assign) = &statement.kind else {
94                continue;
95            };
96            let place = assign.0;
97            if place.projection.first() == Some(&ProjectionElem::Deref)
98                && place
99                    .projection
100                    .iter()
101                    .any(|elem| matches!(elem, ProjectionElem::Field(..)))
102                && is_pointer_storage_ty(tcx, place.ty(body, tcx).ty, 0)
103            {
104                return true;
105            }
106        }
107        if let Some(terminator) = &block.terminator
108            && let TerminatorKind::Call { func, .. } | TerminatorKind::TailCall { func, .. } =
109                &terminator.kind
110            && let Some(nested) = mir_utils::dep_callee_def_id(func)
111            && replaces_pointer_field_rec(tcx, nested, depth + 1, visited)
112        {
113            return true;
114        }
115    }
116    false
117}
118
119fn is_pointer_storage_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, depth: usize) -> bool {
120    match ty.kind() {
121        TyKind::RawPtr(..) => true,
122        TyKind::Pat(inner, _) => is_pointer_storage_ty(tcx, *inner, depth + 1),
123        TyKind::Adt(adt, args) if depth < 2 && adt.repr().transparent() && !adt.is_enum() => {
124            adt.non_enum_variant().fields.iter().any(|field| {
125                is_pointer_storage_ty(tcx, mir_utils::field_ty(tcx, field, args), depth + 1)
126            })
127        }
128        _ => false,
129    }
130}