Skip to main content

rustc_mir_transform/
check_pointers.rs

1use rustc_attr_ir::lang_items::LangItem;
2use rustc_data_structures::thin_vec::ThinVec;
3use rustc_index::IndexVec;
4use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor};
5use rustc_middle::mir::*;
6use rustc_middle::ty::{self, Ty, TyCtxt};
7use tracing::{debug, trace};
8
9/// Details of a pointer check, the condition on which we decide whether to
10/// fail the assert and an [AssertKind] that defines the behavior on failure.
11pub(crate) struct PointerCheck<'tcx> {
12    pub(crate) cond: Operand<'tcx>,
13    pub(crate) assert_kind: Box<AssertKind<Operand<'tcx>>>,
14}
15
16/// When checking for borrows of field projections (`&(*ptr).a`), we might want
17/// to check for the field type (type of `.a` in the example). This enum defines
18/// the variations (pass the pointer [Ty] or the field [Ty]).
19#[derive(#[automatically_derived]impl ::core::marker::Copy for
    BorrowedFieldProjectionMode {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for BorrowedFieldProjectionMode {
}
#[automatically_derived]impl ::core::clone::Clone for
    BorrowedFieldProjectionMode {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone)]
20pub(crate) enum BorrowedFieldProjectionMode {
21    FollowProjections,
22    NoFollowProjections,
23}
24
25/// Utility for adding a check for read/write on every sized, raw pointer.
26///
27/// Visits every read/write access to a [Sized], raw pointer and inserts a
28/// new basic block directly before the pointer access. (Read/write accesses
29/// are determined by the `PlaceContext` of the MIR visitor.) Then calls
30/// `on_finding` to insert the actual logic for a pointer check (e.g. check for
31/// alignment). A check can choose to follow borrows of field projections via
32/// the `field_projection_mode` parameter.
33///
34/// This utility takes care of the right order of blocks, the only thing a
35/// caller must do in `on_finding` is:
36/// - Append [Statement]s to `stmts`.
37/// - Append [LocalDecl]s to `local_decls`.
38/// - Return a [PointerCheck] that contains the condition and an [AssertKind].
39///   The AssertKind must be a panic with `#[rustc_nounwind]`. The condition
40///   should always return the boolean `is_ok`, so evaluate to true in case of
41///   success and fail the check otherwise.
42/// This utility will insert a terminator block that asserts on the condition
43/// and panics on failure.
44pub(crate) fn check_pointers<'tcx, F>(
45    tcx: TyCtxt<'tcx>,
46    body: &mut Body<'tcx>,
47    excluded_pointees: &[Ty<'tcx>],
48    on_finding: F,
49    field_projection_mode: BorrowedFieldProjectionMode,
50) where
51    F: Fn(
52        /* tcx: */ TyCtxt<'tcx>,
53        /* pointer: */ Place<'tcx>,
54        /* pointee_ty: */ Ty<'tcx>,
55        /* context: */ PlaceContext,
56        /* local_decls: */ &mut IndexVec<Local, LocalDecl<'tcx>>,
57        /* stmts: */ &mut ThinVec<Statement<'tcx>>,
58        /* source_info: */ SourceInfo,
59    ) -> PointerCheck<'tcx>,
60{
61    // This pass emits new panics. If for whatever reason we do not have a panic
62    // implementation, running this pass may cause otherwise-valid code to not compile.
63    if tcx.lang_items().get(LangItem::PanicImpl).is_none() {
64        return;
65    }
66
67    let typing_env = body.typing_env(tcx);
68    let basic_blocks = body.basic_blocks.as_mut();
69    let local_decls = &mut body.local_decls;
70
71    // This operation inserts new blocks. Each insertion changes the Location for all
72    // statements/blocks after. Iterating or visiting the MIR in order would require updating
73    // our current location after every insertion. By iterating backwards, we dodge this issue:
74    // The only Locations that an insertion changes have already been handled.
75    for block in basic_blocks.indices().rev() {
76        for statement_index in (0..basic_blocks[block].statements.len()).rev() {
77            let location = Location { block, statement_index };
78            let statement = &basic_blocks[block].statements[statement_index];
79            let source_info = statement.source_info;
80
81            let mut finder = PointerFinder::new(
82                tcx,
83                local_decls,
84                typing_env,
85                excluded_pointees,
86                field_projection_mode,
87            );
88            finder.visit_statement(statement, location);
89
90            for (local, ty, context) in finder.into_found_pointers() {
91                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/check_pointers.rs:91",
                        "rustc_mir_transform::check_pointers",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/check_pointers.rs"),
                        ::tracing_core::__macro_support::Option::Some(91u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::check_pointers"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Inserting check for {0:?}",
                                                    ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Inserting check for {:?}", ty);
92
93                let mut insert_check = |block_data: &mut BasicBlockData<'tcx>, new_block_idx| {
94                    // Invoke `on_finding` which appends to `local_decls` and the
95                    // blocks statements. It returns information about the assert
96                    // we're performing in the Terminator.
97                    let pointer_check = on_finding(
98                        tcx,
99                        local,
100                        ty,
101                        context,
102                        local_decls,
103                        &mut block_data.statements,
104                        source_info,
105                    );
106                    let new_terminator = Terminator {
107                        source_info,
108                        kind: TerminatorKind::Assert {
109                            cond: pointer_check.cond,
110                            expected: true,
111                            // new_block_idx will contain the rest of the original block
112                            target: new_block_idx,
113                            msg: pointer_check.assert_kind,
114                            // This calls a panic function associated with the pointer check, which
115                            // is #[rustc_nounwind]. We never want to insert an unwind into unsafe
116                            // code, because unwinding could make a failing UB check turn into much
117                            // worse UB when we start unwinding.
118                            unwind: UnwindAction::Unreachable,
119                        },
120                    };
121
122                    // Terminate the split block with the new terminator
123                    // and return the original terminator
124                    std::mem::replace(&mut block_data.terminator, new_terminator)
125                };
126
127                basic_blocks.push_with(|new_block_idx, basic_blocks| {
128                    let block_data = &mut basic_blocks[location.block];
129
130                    // Drain every statement after this one
131                    let remaining_stmts = block_data.statements.split_off(location.statement_index);
132
133                    // insert the check (push statements and replace old terminator)
134                    let old_terminator = insert_check(block_data, new_block_idx);
135
136                    // move the rest to a new block
137                    BasicBlockData::new_stmts(
138                        remaining_stmts,
139                        old_terminator,
140                        block_data.is_cleanup,
141                    )
142                });
143            }
144        }
145    }
146}
147
148struct PointerFinder<'a, 'tcx> {
149    tcx: TyCtxt<'tcx>,
150    local_decls: &'a mut LocalDecls<'tcx>,
151    typing_env: ty::TypingEnv<'tcx>,
152    pointers: Vec<(Place<'tcx>, Ty<'tcx>, PlaceContext)>,
153    excluded_pointees: &'a [Ty<'tcx>],
154    field_projection_mode: BorrowedFieldProjectionMode,
155}
156
157impl<'a, 'tcx> PointerFinder<'a, 'tcx> {
158    fn new(
159        tcx: TyCtxt<'tcx>,
160        local_decls: &'a mut LocalDecls<'tcx>,
161        typing_env: ty::TypingEnv<'tcx>,
162        excluded_pointees: &'a [Ty<'tcx>],
163        field_projection_mode: BorrowedFieldProjectionMode,
164    ) -> Self {
165        PointerFinder {
166            tcx,
167            local_decls,
168            typing_env,
169            excluded_pointees,
170            pointers: Vec::new(),
171            field_projection_mode,
172        }
173    }
174
175    fn into_found_pointers(self) -> Vec<(Place<'tcx>, Ty<'tcx>, PlaceContext)> {
176        self.pointers
177    }
178
179    /// Whether or not we should visit a [Place] with [PlaceContext].
180    ///
181    /// We generally only visit Reads/Writes to a place and only Borrows if
182    /// requested.
183    fn should_visit_place(&self, context: PlaceContext) -> bool {
184        match context {
185            PlaceContext::MutatingUse(
186                MutatingUseContext::Store
187                | MutatingUseContext::Call
188                | MutatingUseContext::Yield
189                | MutatingUseContext::Drop
190                | MutatingUseContext::Borrow,
191            ) => true,
192            PlaceContext::NonMutatingUse(
193                NonMutatingUseContext::Copy
194                | NonMutatingUseContext::Move
195                | NonMutatingUseContext::SharedBorrow,
196            ) => true,
197            _ => false,
198        }
199    }
200}
201
202impl<'a, 'tcx> Visitor<'tcx> for PointerFinder<'a, 'tcx> {
203    fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
204        if !self.should_visit_place(context) || !place.is_indirect() {
205            return;
206        }
207
208        // Get the place and type we visit.
209        let pointer = Place::from(place.local);
210        let pointer_ty = pointer.ty(self.local_decls, self.tcx).ty;
211
212        // We only want to check places based on raw pointers
213        let &ty::RawPtr(mut pointee_ty, _) = pointer_ty.kind() else {
214            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/check_pointers.rs:214",
                        "rustc_mir_transform::check_pointers",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/check_pointers.rs"),
                        ::tracing_core::__macro_support::Option::Some(214u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::check_pointers"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Indirect, but not based on an raw ptr, not checking {0:?}",
                                                    place) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("Indirect, but not based on an raw ptr, not checking {:?}", place);
215            return;
216        };
217
218        // If we see a borrow of a field projection, we want to pass the field type to the
219        // check and not the pointee type.
220        if #[allow(non_exhaustive_omitted_patterns)] match self.field_projection_mode {
    BorrowedFieldProjectionMode::FollowProjections => true,
    _ => false,
}matches!(self.field_projection_mode, BorrowedFieldProjectionMode::FollowProjections)
221            && #[allow(non_exhaustive_omitted_patterns)] match context {
    PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow) |
        PlaceContext::MutatingUse(MutatingUseContext::Borrow) => true,
    _ => false,
}matches!(
222                context,
223                PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow)
224                    | PlaceContext::MutatingUse(MutatingUseContext::Borrow)
225            )
226        {
227            // Naturally, the field type is type of the initial place we look at.
228            pointee_ty = place.ty(self.local_decls, self.tcx).ty;
229        }
230
231        // Ideally we'd support this in the future, but for now we are limited to sized types.
232        if !pointee_ty.is_sized(self.tcx, self.typing_env) {
233            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/check_pointers.rs:233",
                        "rustc_mir_transform::check_pointers",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/check_pointers.rs"),
                        ::tracing_core::__macro_support::Option::Some(233u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::check_pointers"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Raw pointer, but pointee is not known to be sized: {0:?}",
                                                    pointer_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("Raw pointer, but pointee is not known to be sized: {:?}", pointer_ty);
234            return;
235        }
236
237        // We don't need to look for slices, we already rejected unsized types above.
238        let element_ty = match pointee_ty.kind() {
239            ty::Array(ty, _) => *ty,
240            _ => pointee_ty,
241        };
242        // Check if we excluded this pointee type from the check.
243        if self.excluded_pointees.contains(&element_ty) {
244            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/check_pointers.rs:244",
                        "rustc_mir_transform::check_pointers",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/check_pointers.rs"),
                        ::tracing_core::__macro_support::Option::Some(244u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::check_pointers"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Skipping pointer for type: {0:?}",
                                                    pointee_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("Skipping pointer for type: {:?}", pointee_ty);
245            return;
246        }
247
248        self.pointers.push((pointer, pointee_ty, context));
249
250        self.super_place(place, context, location);
251    }
252}