Extend the alignment check to borrows

The current alignment check does not include checks for creating
misaligned references from raw pointers, which is now added in this
patch.

When inserting the check we need to be careful with references to
field projections (e.g. `&(*ptr).a`), in which case the resulting
reference must be aligned according to the field type and not the
type of the pointer.
This commit is contained in:
Bastian Kersting
2025-03-03 13:28:41 +00:00
parent 862156d6f2
commit a3e7c699bc
7 changed files with 89 additions and 28 deletions

View File

@@ -6,7 +6,7 @@ use rustc_middle::mir::*;
use rustc_middle::ty::{Ty, TyCtxt};
use rustc_session::Session;
use crate::check_pointers::{BorrowCheckMode, PointerCheck, check_pointers};
use crate::check_pointers::{BorrowedFieldProjectionMode, PointerCheck, check_pointers};
pub(super) struct CheckAlignment;
@@ -19,15 +19,15 @@ impl<'tcx> crate::MirPass<'tcx> for CheckAlignment {
// Skip trivially aligned place types.
let excluded_pointees = [tcx.types.bool, tcx.types.i8, tcx.types.u8];
// We have to exclude borrows here: in `&x.field`, the exact
// requirement is that the final reference must be aligned, but
// `check_pointers` would check that `x` is aligned, which would be wrong.
// When checking the alignment of references to field projections (`&(*ptr).a`),
// we need to make sure that the reference is aligned according to the field type
// and not to the pointer type.
check_pointers(
tcx,
body,
&excluded_pointees,
insert_alignment_check,
BorrowCheckMode::ExcludeBorrows,
BorrowedFieldProjectionMode::FollowProjections,
);
}