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};
89/// 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> {
12pub(crate) cond: Operand<'tcx>,
13pub(crate) assert_kind: Box<AssertKind<Operand<'tcx>>>,
14}
1516/// 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}
2425/// 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
51F: 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.
63if tcx.lang_items().get(LangItem::PanicImpl).is_none() {
64return;
65 }
6667let typing_env = body.typing_env(tcx);
68let basic_blocks = body.basic_blocks.as_mut();
69let local_decls = &mut body.local_decls;
7071// 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.
75for block in basic_blocks.indices().rev() {
76for statement_index in (0..basic_blocks[block].statements.len()).rev() {
77let location = Location { block, statement_index };
78let statement = &basic_blocks[block].statements[statement_index];
79let source_info = statement.source_info;
8081let 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);
8990for (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);
9293let 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.
97let pointer_check = on_finding(
98 tcx,
99 local,
100 ty,
101 context,
102 local_decls,
103&mut block_data.statements,
104 source_info,
105 );
106let 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
112target: 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.
118unwind: UnwindAction::Unreachable,
119 },
120 };
121122// Terminate the split block with the new terminator
123 // and return the original terminator
124std::mem::replace(&mut block_data.terminator, new_terminator)
125 };
126127 basic_blocks.push_with(|new_block_idx, basic_blocks| {
128let block_data = &mut basic_blocks[location.block];
129130// Drain every statement after this one
131let remaining_stmts = block_data.statements.split_off(location.statement_index);
132133// insert the check (push statements and replace old terminator)
134let old_terminator = insert_check(block_data, new_block_idx);
135136// move the rest to a new block
137BasicBlockData::new_stmts(
138 remaining_stmts,
139 old_terminator,
140 block_data.is_cleanup,
141 )
142 });
143 }
144 }
145 }
146}
147148struct 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}
156157impl<'a, 'tcx> PointerFinder<'a, 'tcx> {
158fn 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 {
165PointerFinder {
166tcx,
167local_decls,
168typing_env,
169excluded_pointees,
170 pointers: Vec::new(),
171field_projection_mode,
172 }
173 }
174175fn into_found_pointers(self) -> Vec<(Place<'tcx>, Ty<'tcx>, PlaceContext)> {
176self.pointers
177 }
178179/// 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.
183fn should_visit_place(&self, context: PlaceContext) -> bool {
184match context {
185 PlaceContext::MutatingUse(
186 MutatingUseContext::Store187 | MutatingUseContext::Call188 | MutatingUseContext::Yield189 | MutatingUseContext::Drop190 | MutatingUseContext::Borrow,
191 ) => true,
192 PlaceContext::NonMutatingUse(
193 NonMutatingUseContext::Copy194 | NonMutatingUseContext::Move195 | NonMutatingUseContext::SharedBorrow,
196 ) => true,
197_ => false,
198 }
199 }
200}
201202impl<'a, 'tcx> Visitor<'tcx> for PointerFinder<'a, 'tcx> {
203fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
204if !self.should_visit_place(context) || !place.is_indirect() {
205return;
206 }
207208// Get the place and type we visit.
209let pointer = Place::from(place.local);
210let pointer_ty = pointer.ty(self.local_decls, self.tcx).ty;
211212// We only want to check places based on raw pointers
213let &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);
215return;
216 };
217218// 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.
220if #[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.
228pointee_ty = place.ty(self.local_decls, self.tcx).ty;
229 }
230231// Ideally we'd support this in the future, but for now we are limited to sized types.
232if !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);
234return;
235 }
236237// We don't need to look for slices, we already rejected unsized types above.
238let 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.
243if 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);
245return;
246 }
247248self.pointers.push((pointer, pointee_ty, context));
249250self.super_place(place, context, location);
251 }
252}