Skip to main content

rapx/analysis/dataflow/
pointer_flow.rs

1//! Trace pointer-preserving return values to a callee argument.
2
3use std::collections::HashSet;
4
5use rustc_hir::{def::DefKind, def_id::DefId};
6#[cfg(rapx_box_deref_transmute)]
7use rustc_middle::mir::CastKind;
8use rustc_middle::{
9    mir::{Body, Local, Rvalue, StatementKind, TerminatorKind},
10    ty::{TyCtxt, TyKind},
11};
12
13use crate::def_ids::type_ids;
14use crate::util::mir_utils;
15
16/// Whether a raw pointer or `NonNull` return value traces to the first argument.
17pub(crate) fn return_traces_first_arg(tcx: TyCtxt<'_>, callee: Option<DefId>) -> bool {
18    callee.is_some_and(|id| return_source_arg(tcx, id) == Some(0) || is_nonnull_view(tcx, id))
19}
20
21pub(crate) fn return_source_arg(tcx: TyCtxt<'_>, callee: DefId) -> Option<usize> {
22    if !tcx.is_mir_available(callee) {
23        return None;
24    }
25    let body = tcx.optimized_mir(callee);
26    let result = rustc_middle::mir::RETURN_PLACE;
27    if !matches!(body.local_decls[result].ty.kind(), TyKind::RawPtr(..)) {
28        return None;
29    }
30    trace_source_arg(tcx, body, result, &mut HashSet::new(), 5)
31}
32
33/// Trace a returned reference to the argument from which it was derived.
34pub(crate) fn return_reference_source_arg(tcx: TyCtxt<'_>, callee: DefId) -> Option<usize> {
35    if !tcx.is_mir_available(callee) {
36        return None;
37    }
38    let body = tcx.optimized_mir(callee);
39    let result = rustc_middle::mir::RETURN_PLACE;
40    if !matches!(body.local_decls[result].ty.kind(), TyKind::Ref(..)) {
41        return None;
42    }
43    trace_source_arg(tcx, body, result, &mut HashSet::new(), 5)
44}
45
46/// Mutability of a reference returned from a standard `NonNull<T>` receiver.
47pub(crate) fn nonnull_ref_return(
48    tcx: TyCtxt<'_>,
49    callee: DefId,
50) -> Option<rustc_middle::mir::Mutability> {
51    if !matches!(tcx.def_kind(callee), DefKind::Fn | DefKind::AssocFn)
52        || !tcx.is_mir_available(callee)
53    {
54        return None;
55    }
56    let sig = tcx.fn_sig(callee).skip_binder();
57    let [receiver] = sig.inputs().skip_binder() else {
58        return None;
59    };
60    let TyKind::Ref(_, inner, _) = receiver.kind() else {
61        return None;
62    };
63    let TyKind::Adt(adt, args) = inner.kind() else {
64        return None;
65    };
66    if !type_ids::is_std_nonnull(adt.did()) {
67        return None;
68    }
69    let pointee = args.first().and_then(|arg| arg.as_type())?;
70    let output = sig.output().skip_binder();
71    let TyKind::Ref(_, returned, mutability) = output.kind() else {
72        return None;
73    };
74    (*returned == pointee && return_reference_source_arg(tcx, callee) == Some(0))
75        .then_some(*mutability)
76}
77
78/// A `NonNull` result that still points into its sole `NonNull` argument.
79pub(crate) fn is_nonnull_view(tcx: TyCtxt<'_>, callee: DefId) -> bool {
80    if !matches!(tcx.def_kind(callee), DefKind::Fn | DefKind::AssocFn)
81        || !tcx.is_mir_available(callee)
82    {
83        return false;
84    }
85    let sig = tcx.fn_sig(callee).skip_binder();
86    let [input] = sig.inputs().skip_binder() else {
87        return false;
88    };
89    let output = sig.output().skip_binder();
90    let is_nonnull = |ty: rustc_middle::ty::Ty<'_>| matches!(ty.kind(), TyKind::Adt(adt, _) if type_ids::is_std_nonnull(adt.did()));
91    is_nonnull(*input)
92        && is_nonnull(output)
93        && return_source_arg_with_depth(tcx, callee, 5) == Some(0)
94}
95
96/// Trace a returned reference to interior mutable storage back to its input.
97pub(crate) fn interior_mutable_borrow_source_arg(tcx: TyCtxt<'_>, callee: DefId) -> Option<usize> {
98    if !tcx.is_mir_available(callee) {
99        return None;
100    }
101    let body = tcx.optimized_mir(callee);
102    let result = rustc_middle::mir::RETURN_PLACE;
103    let TyKind::Ref(_, pointee, _) = body.local_decls[result].ty.kind() else {
104        return None;
105    };
106    if !contains_unsafe_cell(tcx, *pointee, 4) {
107        return None;
108    }
109    trace_source_arg(tcx, body, result, &mut HashSet::new(), 5)
110}
111
112fn contains_unsafe_cell<'tcx>(
113    tcx: TyCtxt<'tcx>,
114    ty: rustc_middle::ty::Ty<'tcx>,
115    depth: usize,
116) -> bool {
117    if depth == 0 {
118        return false;
119    }
120    let TyKind::Adt(adt, args) = ty.kind() else {
121        return false;
122    };
123    if tcx.is_lang_item(adt.did(), crate::def_ids::lang_api::LangItem::UnsafeCell) {
124        return true;
125    }
126    !adt.is_enum()
127        && adt.non_enum_variant().fields.iter().any(|field| {
128            contains_unsafe_cell(tcx, mir_utils::field_ty(tcx, field, args), depth - 1)
129        })
130}
131
132/// Follow pointer-preserving MIR values through fields and calls to an input.
133pub(crate) fn trace_source_arg<'tcx>(
134    tcx: TyCtxt<'tcx>,
135    body: &Body<'tcx>,
136    local: Local,
137    seen: &mut HashSet<Local>,
138    depth: usize,
139) -> Option<usize> {
140    if !seen.insert(local) {
141        return None;
142    }
143    let index = local.as_usize();
144    if index > 0 && index <= body.arg_count {
145        return Some(index - 1);
146    }
147    let mut source = None;
148    for data in body.basic_blocks.iter() {
149        for stmt in &data.statements {
150            let StatementKind::Assign(assign) = &stmt.kind else {
151                continue;
152            };
153            let (dest, value) = &**assign;
154            if dest.local != local || !dest.projection.is_empty() {
155                continue;
156            }
157            let candidate = match value {
158                Rvalue::Use(operand, _) => {
159                    mir_utils::operand_mir_place(operand).and_then(|place| {
160                        trace_source_arg(tcx, body, place.local, &mut seen.clone(), depth)
161                    })
162                }
163                #[cfg(rapx_box_deref_transmute)]
164                Rvalue::Cast(CastKind::BoxDerefTransmute, operand, _) => {
165                    mir_utils::operand_mir_place(operand).and_then(|place| {
166                        trace_source_arg(tcx, body, place.local, &mut seen.clone(), depth)
167                    })
168                }
169                Rvalue::Cast(_, operand, _) => mir_utils::operand_mir_place(operand)
170                    .filter(|place| mir_utils::pointee_ty(place.ty(body, tcx).ty).is_some())
171                    .and_then(|place| {
172                        trace_source_arg(tcx, body, place.local, &mut seen.clone(), depth)
173                    }),
174                Rvalue::RawPtr(_, place) | Rvalue::Ref(_, _, place) => {
175                    trace_source_arg(tcx, body, place.local, &mut seen.clone(), depth)
176                }
177                Rvalue::Aggregate(kind, operands)
178                    if matches!(&**kind, rustc_middle::mir::AggregateKind::RawPtr(..)) =>
179                {
180                    operands
181                        .iter()
182                        .next()
183                        .and_then(mir_utils::operand_mir_place)
184                        .and_then(|place| {
185                            trace_source_arg(tcx, body, place.local, &mut seen.clone(), depth)
186                        })
187                }
188                _ => None,
189            }?;
190            if source.is_some_and(|old| old != candidate) {
191                return None;
192            }
193            source = Some(candidate);
194        }
195    }
196    if depth > 0 {
197        for data in body.basic_blocks.iter() {
198            let TerminatorKind::Call {
199                func,
200                args,
201                destination,
202                ..
203            } = &data.terminator().kind
204            else {
205                continue;
206            };
207            if destination.local != local || !destination.projection.is_empty() {
208                continue;
209            }
210            let callee = mir_utils::dep_callee_def_id(func)?;
211            let arg_index = return_source_arg_with_depth(tcx, callee, depth - 1)?;
212            let arg = args.get(arg_index)?;
213            let candidate = mir_utils::operand_mir_place(&arg.node).and_then(|place| {
214                trace_source_arg(tcx, body, place.local, &mut seen.clone(), depth)
215            })?;
216            if source.is_some_and(|old| old != candidate) {
217                return None;
218            }
219            source = Some(candidate);
220        }
221    }
222    source
223}
224
225fn return_source_arg_with_depth(tcx: TyCtxt<'_>, callee: DefId, depth: usize) -> Option<usize> {
226    if !tcx.is_mir_available(callee) {
227        return None;
228    }
229    let body = tcx.optimized_mir(callee);
230    let result = rustc_middle::mir::RETURN_PLACE;
231    trace_source_arg(tcx, body, result, &mut HashSet::new(), depth)
232}