Skip to content
Open
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 60 additions & 24 deletions compiler/rustc_const_eval/src/util/alignment.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use rustc_abi::Align;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, TyCtxt};
use rustc_middle::ty::{self, Ty, TyCtxt};
use tracing::debug;

/// Returns `true` if this place is allowed to be less aligned
/// than its containing struct (because it is within a packed
/// struct).
pub fn is_disaligned<'tcx, L>(
pub fn is_potentially_misaligned<'tcx, L>(
tcx: TyCtxt<'tcx>,
local_decls: &L,
typing_env: ty::TypingEnv<'tcx>,
Expand All @@ -15,38 +15,74 @@ pub fn is_disaligned<'tcx, L>(
where
L: HasLocalDecls<'tcx>,
{
debug!("is_disaligned({:?})", place);
debug!("is_potentially_misaligned({:?})", place);
let Some(pack) = is_within_packed(tcx, local_decls, place) else {
debug!("is_disaligned({:?}) - not within packed", place);
debug!("is_potentially_misaligned({:?}) - not within packed", place);
return false;
};

let ty = place.ty(local_decls, tcx).ty;
let unsized_tail = || tcx.struct_tail_for_codegen(ty, typing_env);

match tcx.layout_of(typing_env.as_query_input(ty)) {
Ok(layout)
Ok(layout) => {
if layout.align.abi <= pack
&& (layout.is_sized()
|| matches!(unsized_tail().kind(), ty::Slice(..) | ty::Str)) =>
{
// If the packed alignment is greater or equal to the field alignment, the type won't be
// further disaligned.
// However we need to ensure the field is sized; for unsized fields, `layout.align` is
// just an approximation -- except when the unsized tail is a slice, where the alignment
// is fully determined by the type.
debug!(
"is_disaligned({:?}) - align = {}, packed = {}; not disaligned",
place,
layout.align.abi.bytes(),
pack.bytes()
);
false
&& (layout.is_sized() || matches!(unsized_tail().kind(), ty::Slice(..) | ty::Str))
{
// If the packed alignment is greater or equal to the field alignment, the type won't be
// further disaligned.
// However we need to ensure the field is sized; for unsized fields, `layout.align` is
// just an approximation -- except when the unsized tail is a slice, where the alignment
// is fully determined by the type.
debug!(
"is_potentially_misaligned({:?}) - align = {}, packed = {}; not disaligned",
place,
layout.align.abi.bytes(),
pack.bytes()
);
false
} else {
true
}
}
Err(_) => {
// Soundness: For any `T`, the ABI alignment requirement of `[T]` equals that of `T`.
// Proof sketch:
// (1) From `&[T]` we can obtain `&T`, hence align([T]) >= align(T).
// (2) Using `std::array::from_ref(&T)` we can obtain `&[T; 1]` (and thus `&[T]`),
// hence align(T) >= align([T]).
// Therefore align([T]) == align(T). Length does not affect alignment.

// Try to determine alignment from the type structure
if let Some(element_align) = get_element_alignment(tcx, ty) {
element_align > pack
} else {
// If we still can't determine alignment, conservatively assume disaligned
true
}
}
_ => {
// We cannot figure out the layout. Conservatively assume that this is disaligned.
debug!("is_disaligned({:?}) - true", place);
true
}
}

/// Try to determine the alignment of an array element type
fn get_element_alignment<'tcx>(_tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<Align> {
match ty.kind() {
ty::Array(element_ty, _) | ty::Slice(element_ty) => {
// Only allow u8 and i8 arrays when layout computation fails
// Other types are conservatively assumed to be misaligned
match element_ty.kind() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

properly compute the of the element_ty here, limiting it to only u8 and i8 feels unnecessary 🤔

ty::Uint(ty::UintTy::U8) | ty::Int(ty::IntTy::I8) => {
// For u8 and i8, we know their alignment is 1
Some(Align::from_bytes(1).unwrap())
}
_ => {
// For other types, we cannot safely determine alignment
// Conservatively return None to indicate potential misalignment
None
}
}
}
_ => None,
}
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_const_eval/src/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ mod check_validity_requirement;
mod compare_types;
mod type_name;

pub use self::alignment::{is_disaligned, is_within_packed};
pub use self::alignment::{is_potentially_misaligned, is_within_packed};
pub use self::check_validity_requirement::check_validity_requirement;
pub(crate) use self::check_validity_requirement::validate_scalar_in_layout;
pub use self::compare_types::{relate_types, sub_types};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ impl<'tcx> crate::MirPass<'tcx> for AddMovesForPackedDrops {

match terminator.kind {
TerminatorKind::Drop { place, .. }
if util::is_disaligned(tcx, body, typing_env, place) =>
if util::is_potentially_misaligned(tcx, body, typing_env, place) =>
{
add_move_for_packed_drop(
tcx,
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_mir_transform/src/check_packed_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ impl<'tcx> Visitor<'tcx> for PackedRefChecker<'_, 'tcx> {
}

fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
if context.is_borrow() && util::is_disaligned(self.tcx, self.body, self.typing_env, *place)
if context.is_borrow()
&& util::is_potentially_misaligned(self.tcx, self.body, self.typing_env, *place)
{
let def_id = self.body.source.instance.def_id();
if let Some(impl_def_id) = self.tcx.impl_of_assoc(def_id)
Expand Down
19 changes: 19 additions & 0 deletions tests/ui/packed/packed-array-const-generic.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//@ check-pass
#![allow(dead_code)]

#[repr(C, packed)]
struct PascalString<const CAP: usize> {
len: u8,
buf: [u8; CAP],
}

fn bar<const CAP: usize>(s: &PascalString<CAP>) -> &str {
// Goal: this line should not trigger E0793
std::str::from_utf8(&s.buf[0..s.len as usize]).unwrap()
}

fn main() {
let p = PascalString::<10> { len: 3, buf: *b"abc\0\0\0\0\0\0\0" };
let s = bar(&p);
assert_eq!(s, "abc");
}
19 changes: 19 additions & 0 deletions tests/ui/packed/packed-array-i8-const-generic.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//@ check-pass
#![allow(dead_code)]

#[repr(C, packed)]
struct PascalStringI8<const CAP: usize> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please merge this into a single test and use generic-length instead of const-generic in the file name

len: u8,
buf: [i8; CAP],
}

fn bar<const CAP: usize>(s: &PascalStringI8<CAP>) -> &[i8] {
// Goal: this line should not trigger E0793 for i8 arrays
&s.buf[0..s.len as usize]
}

fn main() {
let p = PascalStringI8::<10> { len: 3, buf: [1, 2, 3, 0, 0, 0, 0, 0, 0, 0] };
let s = bar(&p);
assert_eq!(s, &[1, 2, 3]);
}
Loading