Skip to main content

rapx/analysis/dataflow/
call_read.rs

1//! Trace returned values read through raw pointers to call arguments.
2
3use std::collections::HashSet;
4
5use rustc_hir::def_id::DefId;
6use rustc_middle::{
7    mir::{Operand, ProjectionElem, RETURN_PLACE, Rvalue, StatementKind},
8    ty::{TyCtxt, TyKind},
9};
10
11use crate::def_ids::diagnostic_api;
12
13use super::pointer_flow;
14
15/// Argument supplying the pointer read to produce the return value.
16pub(crate) fn read_source_arg(tcx: TyCtxt<'_>, callee: DefId) -> Option<usize> {
17    if diagnostic_api::is_ptr_read(tcx, callee) {
18        return Some(0);
19    }
20    if !tcx.is_mir_available(callee) {
21        return None;
22    }
23    let body = tcx.optimized_mir(callee);
24    let mut source = None;
25    for block in body.basic_blocks.iter() {
26        for statement in &block.statements {
27            let StatementKind::Assign(assign) = &statement.kind else {
28                continue;
29            };
30            let (destination, value) = &**assign;
31            if destination.local != RETURN_PLACE || !destination.projection.is_empty() {
32                continue;
33            }
34            let Rvalue::Use(Operand::Copy(place), _) = value else {
35                return None;
36            };
37            if !matches!(place.projection.first(), Some(ProjectionElem::Deref))
38                || !matches!(body.local_decls[place.local].ty.kind(), TyKind::RawPtr(..))
39            {
40                return None;
41            }
42            let candidate =
43                pointer_flow::trace_source_arg(tcx, body, place.local, &mut HashSet::new(), 5)?;
44            if source.is_some_and(|previous| previous != candidate) {
45                return None;
46            }
47            source = Some(candidate);
48        }
49    }
50    source
51}