Skip to content

Commit 099e0f1

Browse files
authored
Unrolled build for #143046
Rollup merge of #143046 - RalfJung:zst-unsafe-cell, r=lcnr,oli-obk const validation: properly ignore zero-sized UnsafeCell Fixes #142948 r? `@oli-obk`
2 parents bdaba05 + 7de39f5 commit 099e0f1

File tree

10 files changed

+42
-22
lines changed

10 files changed

+42
-22
lines changed

compiler/rustc_const_eval/src/interpret/eval_context.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -383,7 +383,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
383383
/// Returns the actual dynamic size and alignment of the place at the given type.
384384
/// Only the "meta" (metadata) part of the place matters.
385385
/// This can fail to provide an answer for extern types.
386-
pub(super) fn size_and_align_of(
386+
pub(super) fn size_and_align_from_meta(
387387
&self,
388388
metadata: &MemPlaceMeta<M::Provenance>,
389389
layout: &TyAndLayout<'tcx>,
@@ -409,7 +409,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
409409
// adjust alignment and size for them?
410410
let field = layout.field(self, layout.fields.count() - 1);
411411
let Some((unsized_size, mut unsized_align)) =
412-
self.size_and_align_of(metadata, &field)?
412+
self.size_and_align_from_meta(metadata, &field)?
413413
else {
414414
// A field with an extern type. We don't know the actual dynamic size
415415
// or the alignment.
@@ -471,11 +471,11 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
471471
}
472472
}
473473
#[inline]
474-
pub fn size_and_align_of_mplace(
474+
pub fn size_and_align_of_val(
475475
&self,
476-
mplace: &MPlaceTy<'tcx, M::Provenance>,
476+
val: &impl Projectable<'tcx, M::Provenance>,
477477
) -> InterpResult<'tcx, Option<(Size, Align)>> {
478-
self.size_and_align_of(&mplace.meta(), &mplace.layout)
478+
self.size_and_align_from_meta(&val.meta(), &val.layout())
479479
}
480480

481481
/// Jump to the given block.

compiler/rustc_const_eval/src/interpret/intrinsics.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
125125
// dereferenceable!
126126
let place = self.ref_to_mplace(&self.read_immediate(&args[0])?)?;
127127
let (size, align) = self
128-
.size_and_align_of_mplace(&place)?
128+
.size_and_align_of_val(&place)?
129129
.ok_or_else(|| err_unsup_format!("`extern type` does not have known layout"))?;
130130

131131
let result = match intrinsic_name {

compiler/rustc_const_eval/src/interpret/place.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -470,7 +470,7 @@ where
470470
) -> InterpResult<'tcx, Option<AllocRef<'_, 'tcx, M::Provenance, M::AllocExtra, M::Bytes>>>
471471
{
472472
let (size, _align) = self
473-
.size_and_align_of_mplace(mplace)?
473+
.size_and_align_of_val(mplace)?
474474
.unwrap_or((mplace.layout.size, mplace.layout.align.abi));
475475
// We check alignment separately, and *after* checking everything else.
476476
// If an access is both OOB and misaligned, we want to see the bounds error.
@@ -486,7 +486,7 @@ where
486486
) -> InterpResult<'tcx, Option<AllocRefMut<'_, 'tcx, M::Provenance, M::AllocExtra, M::Bytes>>>
487487
{
488488
let (size, _align) = self
489-
.size_and_align_of_mplace(mplace)?
489+
.size_and_align_of_val(mplace)?
490490
.unwrap_or((mplace.layout.size, mplace.layout.align.abi));
491491
// We check alignment separately, and raise that error *after* checking everything else.
492492
// If an access is both OOB and misaligned, we want to see the bounds error.
@@ -888,11 +888,11 @@ where
888888
trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout().ty);
889889

890890
let dest = dest.force_mplace(self)?;
891-
let Some((dest_size, _)) = self.size_and_align_of_mplace(&dest)? else {
891+
let Some((dest_size, _)) = self.size_and_align_of_val(&dest)? else {
892892
span_bug!(self.cur_span(), "copy_op needs (dynamically) sized values")
893893
};
894894
if cfg!(debug_assertions) {
895-
let src_size = self.size_and_align_of_mplace(&src)?.unwrap().0;
895+
let src_size = self.size_and_align_of_val(&src)?.unwrap().0;
896896
assert_eq!(src_size, dest_size, "Cannot copy differently-sized data");
897897
} else {
898898
// As a cheap approximation, we compare the fixed parts of the size.
@@ -980,7 +980,7 @@ where
980980
kind: MemoryKind<M::MemoryKind>,
981981
meta: MemPlaceMeta<M::Provenance>,
982982
) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
983-
let Some((size, align)) = self.size_and_align_of(&meta, &layout)? else {
983+
let Some((size, align)) = self.size_and_align_from_meta(&meta, &layout)? else {
984984
span_bug!(self.cur_span(), "cannot allocate space for `extern` type, size is not known")
985985
};
986986
let ptr = self.allocate_ptr(size, align, kind, AllocInit::Uninit)?;

compiler/rustc_const_eval/src/interpret/projection.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ where
168168
// Re-use parent metadata to determine dynamic field layout.
169169
// With custom DSTS, this *will* execute user-defined code, but the same
170170
// happens at run-time so that's okay.
171-
match self.size_and_align_of(&base_meta, &field_layout)? {
171+
match self.size_and_align_from_meta(&base_meta, &field_layout)? {
172172
Some((_, align)) => {
173173
// For packed types, we need to cap alignment.
174174
let align = if let ty::Adt(def, _) = base.layout().ty.kind()

compiler/rustc_const_eval/src/interpret/validity.rs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -494,7 +494,7 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> {
494494
}
495495
// Make sure this is dereferenceable and all.
496496
let size_and_align = try_validation!(
497-
self.ecx.size_and_align_of_mplace(&place),
497+
self.ecx.size_and_align_of_val(&place),
498498
self.path,
499499
Ub(InvalidMeta(msg)) => match msg {
500500
InvalidMetaKind::SliceTooBig => InvalidMetaSliceTooLarge { ptr_kind },
@@ -906,7 +906,7 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> {
906906
let (_prov, start_offset) = mplace.ptr().into_parts();
907907
let (size, _align) = self
908908
.ecx
909-
.size_and_align_of_mplace(&mplace)?
909+
.size_and_align_of_val(&mplace)?
910910
.unwrap_or((mplace.layout.size, mplace.layout.align.abi));
911911
// If there is no padding at all, we can skip the rest: check for
912912
// a single data range covering the entire value.
@@ -1086,8 +1086,10 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValueVisitor<'tcx, M> for ValidityVisitor<'rt,
10861086
) -> InterpResult<'tcx> {
10871087
// Special check for CTFE validation, preventing `UnsafeCell` inside unions in immutable memory.
10881088
if self.ctfe_mode.is_some_and(|c| !c.allow_immutable_unsafe_cell()) {
1089-
if !val.layout.is_zst() && !val.layout.ty.is_freeze(*self.ecx.tcx, self.ecx.typing_env)
1090-
{
1089+
// Unsized unions are currently not a thing, but let's keep this code consistent with
1090+
// the check in `visit_value`.
1091+
let zst = self.ecx.size_and_align_of_val(val)?.is_some_and(|(s, _a)| s.bytes() == 0);
1092+
if !zst && !val.layout.ty.is_freeze(*self.ecx.tcx, self.ecx.typing_env) {
10911093
if !self.in_mutable_memory(val) {
10921094
throw_validation_failure!(self.path, UnsafeCellInImmutable);
10931095
}
@@ -1131,7 +1133,10 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValueVisitor<'tcx, M> for ValidityVisitor<'rt,
11311133

11321134
// Special check preventing `UnsafeCell` in the inner part of constants
11331135
if self.ctfe_mode.is_some_and(|c| !c.allow_immutable_unsafe_cell()) {
1134-
if !val.layout.is_zst()
1136+
// Exclude ZST values. We need to compute the dynamic size/align to properly
1137+
// handle slices and trait objects.
1138+
let zst = self.ecx.size_and_align_of_val(val)?.is_some_and(|(s, _a)| s.bytes() == 0);
1139+
if !zst
11351140
&& let Some(def) = val.layout.ty.ty_adt_def()
11361141
&& def.is_unsafe_cell()
11371142
{

compiler/rustc_mir_transform/src/gvn.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1625,7 +1625,7 @@ fn op_to_prop_const<'tcx>(
16251625
// If this constant is already represented as an `Allocation`,
16261626
// try putting it into global memory to return it.
16271627
if let Either::Left(mplace) = op.as_mplace_or_imm() {
1628-
let (size, _align) = ecx.size_and_align_of_mplace(&mplace).discard_err()??;
1628+
let (size, _align) = ecx.size_and_align_of_val(&mplace).discard_err()??;
16291629

16301630
// Do not try interning a value that contains provenance.
16311631
// Due to https://github.com/rust-lang/rust/issues/79738, doing so could lead to bugs.

src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -814,7 +814,7 @@ trait EvalContextPrivExt<'tcx, 'ecx>: crate::MiriInterpCxExt<'tcx> {
814814
info: RetagInfo, // diagnostics info about this retag
815815
) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
816816
let this = self.eval_context_mut();
817-
let size = this.size_and_align_of_mplace(place)?.map(|(size, _)| size);
817+
let size = this.size_and_align_of_val(place)?.map(|(size, _)| size);
818818
// FIXME: If we cannot determine the size (because the unsized tail is an `extern type`),
819819
// bail out -- we cannot reasonably figure out which memory range to reborrow.
820820
// See https://github.com/rust-lang/unsafe-code-guidelines/issues/276.

src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -469,7 +469,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
469469
// - if the pointer is not reborrowed (raw pointer) then we override the size
470470
// to do a zero-length reborrow.
471471
let reborrow_size = this
472-
.size_and_align_of_mplace(place)?
472+
.size_and_align_of_val(place)?
473473
.map(|(size, _)| size)
474474
.unwrap_or(place.layout.size);
475475
trace!("Creating new permission: {:?} with size {:?}", new_perm, reborrow_size);

src/tools/miri/src/helpers.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -489,7 +489,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
489489
trace!("visit_frozen(place={:?}, size={:?})", *place, size);
490490
debug_assert_eq!(
491491
size,
492-
this.size_and_align_of_mplace(place)?
492+
this.size_and_align_of_val(place)?
493493
.map(|(size, _)| size)
494494
.unwrap_or_else(|| place.layout.size)
495495
);
@@ -530,7 +530,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
530530
trace!("unsafe_cell_action on {:?}", place.ptr());
531531
// We need a size to go on.
532532
let unsafe_cell_size = this
533-
.size_and_align_of_mplace(place)?
533+
.size_and_align_of_val(place)?
534534
.map(|(size, _)| size)
535535
// for extern types, just cover what we can
536536
.unwrap_or_else(|| place.layout.size);
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
//! Ensure we do not complain about zero-sized `UnsafeCell` in a const in any form.
2+
//! See <https://github.com/rust-lang/rust/issues/142948>.
3+
4+
//@ check-pass
5+
use std::cell::UnsafeCell;
6+
7+
const X1: &mut UnsafeCell<[i32; 0]> = UnsafeCell::from_mut(&mut []);
8+
9+
const X2: &mut UnsafeCell<[i32]> = UnsafeCell::from_mut(&mut []);
10+
11+
trait Trait {}
12+
impl Trait for [i32; 0] {}
13+
const X3: &mut UnsafeCell<dyn Trait> = UnsafeCell::from_mut(&mut []);
14+
15+
fn main() {}

0 commit comments

Comments
 (0)