Skip to main content

rapx/util/
mir_scan.rs

1use rustc_hir::{Safety, def_id::DefId};
2use rustc_middle::{
3    mir::{
4        Body, Local, Operand, Place, ProjectionElem, Rvalue, StatementKind,
5        TerminatorKind,
6    },
7    ty::{TyCtxt, TyKind},
8};
9use std::collections::{HashMap, HashSet};
10
11use super::mir_utils::dep_callee_def_id;
12
13/// Returns the [`Safety`] (`Safe`/`Unsafe`) of a function's signature.
14pub fn get_fn_safety(tcx: TyCtxt<'_>, def_id: DefId) -> Safety {
15    let poly_fn_sig = tcx.fn_sig(def_id);
16    let fn_sig = poly_fn_sig.skip_binder();
17    fn_sig.safety()
18}
19
20/// Helper checking if a [`Place`] involves raw pointer dereference.
21pub(crate) fn place_has_raw_deref<'tcx>(body: &Body<'tcx>, place: &Place<'tcx>) -> bool {
22    let local = place.local;
23    for proj in place.projection.iter() {
24        if let ProjectionElem::Deref = proj.kind() {
25            let ty = body.local_decls[local].ty;
26            if let TyKind::RawPtr(_, _) = ty.kind() {
27                return true;
28            }
29        }
30    }
31    false
32}
33
34/// Analyzes the MIR of the given function to collect all local variables
35/// that are involved in dereferencing raw pointers (`*const T` or `*mut T`).
36pub fn get_rawptr_deref(tcx: TyCtxt<'_>, def_id: DefId) -> HashSet<Local> {
37    let mut raw_ptrs = HashSet::new();
38    if tcx.is_mir_available(def_id) {
39        let body = tcx.optimized_mir(def_id);
40        for bb in body.basic_blocks.iter() {
41            for stmt in &bb.statements {
42                if let StatementKind::Assign(assign) = &stmt.kind {
43                    let (lhs, rhs) = &**assign;
44                    if place_has_raw_deref(body, lhs) {
45                        raw_ptrs.insert(lhs.local);
46                    }
47                    if let Rvalue::Use(op, ..) = rhs {
48                        match op {
49                            Operand::Copy(place) | Operand::Move(place)
50                                if place_has_raw_deref(body, place) => {
51                                    raw_ptrs.insert(place.local);
52                                }
53                            _ => {}
54                        }
55                    }
56                    if let Rvalue::Ref(_, _, place) = rhs
57                        && place_has_raw_deref(body, place) {
58                            raw_ptrs.insert(place.local);
59                        }
60                }
61            }
62            if let Some(terminator) = &bb.terminator
63                && let rustc_middle::mir::TerminatorKind::Call { args, .. } = &terminator.kind {
64                    for arg in args {
65                        match arg.node {
66                            Operand::Copy(place) | Operand::Move(place)
67                                if place_has_raw_deref(body, &place) => {
68                                    raw_ptrs.insert(place.local);
69                                }
70                            _ => {}
71                        }
72                    }
73                }
74        }
75    }
76    raw_ptrs
77}
78
79/// Collects pairs of global static variables and their corresponding local variables
80/// within a function's MIR that are assigned from statics.
81pub fn collect_global_local_pairs(tcx: TyCtxt<'_>, def_id: DefId) -> HashMap<DefId, Vec<Local>> {
82    let mut globals: HashMap<DefId, Vec<Local>> = HashMap::new();
83
84    if !tcx.is_mir_available(def_id) {
85        return globals;
86    }
87
88    let body = tcx.optimized_mir(def_id);
89
90    for bb in body.basic_blocks.iter() {
91        for stmt in &bb.statements {
92            if let StatementKind::Assign(assign) = &stmt.kind {
93                let (lhs, rhs) = &**assign;
94                if let Rvalue::Use(Operand::Constant(c), ..) = rhs
95                    && let Some(static_def_id) = c.check_static_ptr(tcx) {
96                        globals.entry(static_def_id).or_default().push(lhs.local);
97                    }
98            }
99        }
100    }
101
102    globals
103}
104
105/// Scans MIR for calls to unsafe functions and returns the set of callee DefIds.
106pub fn get_unsafe_callees(tcx: TyCtxt<'_>, def_id: DefId) -> HashSet<DefId> {
107    let mut unsafe_callees = HashSet::new();
108    if tcx.is_mir_available(def_id) {
109        let body = tcx.optimized_mir(def_id);
110        for bb in body.basic_blocks.iter() {
111            if let TerminatorKind::Call { func, .. } = &bb.terminator().kind
112                && let Some(callee_def_id) = dep_callee_def_id(func)
113                    && get_fn_safety(tcx, callee_def_id) == Safety::Unsafe {
114                        unsafe_callees.insert(callee_def_id);
115                    }
116        }
117    }
118    unsafe_callees
119}