Skip to content

Commit 503026b

Browse files
committed
mem::zeroed/uninit: panic on types that do not permit zero-initialization
1 parent 55aee8d commit 503026b

File tree

10 files changed

+280
-137
lines changed

10 files changed

+280
-137
lines changed

src/libcore/intrinsics.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,16 @@ extern "rust-intrinsic" {
721721
/// This will statically either panic, or do nothing.
722722
pub fn panic_if_uninhabited<T>();
723723

724+
/// A guard for unsafe functions that cannot ever be executed if `T` does not permit
725+
/// zero-initialization: This will statically either panic, or do nothing.
726+
#[cfg(not(bootstrap))]
727+
pub fn panic_if_zero_invalid<T>();
728+
729+
/// A guard for unsafe functions that cannot ever be executed if `T` has invalid
730+
/// bit patterns: This will statically either panic, or do nothing.
731+
#[cfg(not(bootstrap))]
732+
pub fn panic_if_any_invalid<T>();
733+
724734
/// Gets a reference to a static `Location` indicating where it was called.
725735
#[rustc_const_unstable(feature = "const_caller_location", issue = "47809")]
726736
pub fn caller_location() -> &'static crate::panic::Location<'static>;

src/libcore/mem/mod.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,9 @@ pub const fn needs_drop<T>() -> bool {
495495
#[allow(deprecated)]
496496
#[rustc_diagnostic_item = "mem_zeroed"]
497497
pub unsafe fn zeroed<T>() -> T {
498+
#[cfg(not(bootstrap))]
499+
intrinsics::panic_if_zero_invalid::<T>();
500+
#[cfg(bootstrap)]
498501
intrinsics::panic_if_uninhabited::<T>();
499502
intrinsics::init()
500503
}
@@ -528,6 +531,9 @@ pub unsafe fn zeroed<T>() -> T {
528531
#[allow(deprecated)]
529532
#[rustc_diagnostic_item = "mem_uninitialized"]
530533
pub unsafe fn uninitialized<T>() -> T {
534+
#[cfg(not(bootstrap))]
535+
intrinsics::panic_if_any_invalid::<T>();
536+
#[cfg(bootstrap)]
531537
intrinsics::panic_if_uninhabited::<T>();
532538
intrinsics::uninit()
533539
}

src/librustc/ty/layout.rs

Lines changed: 0 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1907,36 +1907,6 @@ impl<'tcx, T: HasTyCtxt<'tcx>> HasTyCtxt<'tcx> for LayoutCx<'tcx, T> {
19071907
}
19081908
}
19091909

1910-
pub trait MaybeResult<T> {
1911-
type Error;
1912-
1913-
fn from(x: Result<T, Self::Error>) -> Self;
1914-
fn to_result(self) -> Result<T, Self::Error>;
1915-
}
1916-
1917-
impl<T> MaybeResult<T> for T {
1918-
type Error = !;
1919-
1920-
fn from(x: Result<T, Self::Error>) -> Self {
1921-
let Ok(x) = x;
1922-
x
1923-
}
1924-
fn to_result(self) -> Result<T, Self::Error> {
1925-
Ok(self)
1926-
}
1927-
}
1928-
1929-
impl<T, E> MaybeResult<T> for Result<T, E> {
1930-
type Error = E;
1931-
1932-
fn from(x: Result<T, Self::Error>) -> Self {
1933-
x
1934-
}
1935-
fn to_result(self) -> Result<T, Self::Error> {
1936-
self
1937-
}
1938-
}
1939-
19401910
pub type TyLayout<'tcx> = ::rustc_target::abi::TyLayout<'tcx, Ty<'tcx>>;
19411911

19421912
impl<'tcx> LayoutOf for LayoutCx<'tcx, TyCtxt<'tcx>> {

src/librustc_codegen_ssa/mir/block.rs

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -521,11 +521,36 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
521521
}
522522

523523
// Emit a panic or a no-op for `panic_if_uninhabited`.
524-
if intrinsic == Some("panic_if_uninhabited") {
524+
// These are intrinsics that compile to panics so that we can get a message
525+
// which mentions the offending type, even from a const context.
526+
#[derive(Debug, PartialEq)]
527+
enum PanicIntrinsic { IfUninhabited, IfZeroInvalid, IfAnyInvalid };
528+
let panic_intrinsic = intrinsic.and_then(|i| match i {
529+
"panic_if_uninhabited" => Some(PanicIntrinsic::IfUninhabited),
530+
"panic_if_zero_invalid" => Some(PanicIntrinsic::IfZeroInvalid),
531+
"panic_if_any_invalid" => Some(PanicIntrinsic::IfAnyInvalid),
532+
_ => None
533+
});
534+
if let Some(intrinsic) = panic_intrinsic {
535+
use PanicIntrinsic::*;
525536
let ty = instance.unwrap().substs.type_at(0);
526537
let layout = bx.layout_of(ty);
527-
if layout.abi.is_uninhabited() {
528-
let msg_str = format!("Attempted to instantiate uninhabited type {}", ty);
538+
let do_panic = match intrinsic {
539+
IfUninhabited => layout.abi.is_uninhabited(),
540+
IfZeroInvalid => // We unwrap as the error type is `!`.
541+
!layout.might_permit_raw_init(&bx, /*zero:*/ true).unwrap(),
542+
IfAnyInvalid => // We unwrap as the error type is `!`.
543+
!layout.might_permit_raw_init(&bx, /*zero:*/ false).unwrap(),
544+
};
545+
if do_panic {
546+
let msg_str = if layout.abi.is_uninhabited() {
547+
// Use this error even for the other intrinsics as it is more precise.
548+
format!("attempted to instantiate uninhabited type `{}`", ty)
549+
} else if intrinsic == IfZeroInvalid {
550+
format!("attempted to zero-initialize type `{}`, which is invalid", ty)
551+
} else {
552+
format!("attempted to leave type `{}` uninitialized, which is invalid", ty)
553+
};
529554
let msg = bx.const_str(Symbol::intern(&msg_str));
530555
let location = self.get_caller_location(&mut bx, span).immediate();
531556

src/librustc_index/vec.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ macro_rules! newtype_index {
196196

197197
#[inline]
198198
fn index(self) -> usize {
199-
usize::from(self)
199+
self.as_usize()
200200
}
201201
}
202202

src/librustc_target/abi/mod.rs

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -919,6 +919,7 @@ impl<'a, Ty> Deref for TyLayout<'a, Ty> {
919919
}
920920
}
921921

922+
/// Trait for context types that can compute layouts of things.
922923
pub trait LayoutOf {
923924
type Ty;
924925
type TyLayout;
@@ -929,6 +930,39 @@ pub trait LayoutOf {
929930
}
930931
}
931932

933+
/// The `TyLayout` above will always be a `MaybeResult<TyLayout<'_, Self>>`.
934+
/// We can't add the bound due to the lifetime, but this trait is still useful when
935+
/// writing code that's generic over the `LayoutOf` impl.
936+
pub trait MaybeResult<T> {
937+
type Error;
938+
939+
fn from(x: Result<T, Self::Error>) -> Self;
940+
fn to_result(self) -> Result<T, Self::Error>;
941+
}
942+
943+
impl<T> MaybeResult<T> for T {
944+
type Error = !;
945+
946+
fn from(x: Result<T, Self::Error>) -> Self {
947+
let Ok(x) = x;
948+
x
949+
}
950+
fn to_result(self) -> Result<T, Self::Error> {
951+
Ok(self)
952+
}
953+
}
954+
955+
impl<T, E> MaybeResult<T> for Result<T, E> {
956+
type Error = E;
957+
958+
fn from(x: Result<T, Self::Error>) -> Self {
959+
x
960+
}
961+
fn to_result(self) -> Result<T, Self::Error> {
962+
self
963+
}
964+
}
965+
932966
#[derive(Copy, Clone, PartialEq, Eq)]
933967
pub enum PointerKind {
934968
/// Most general case, we know no restrictions to tell LLVM.
@@ -969,13 +1003,17 @@ impl<'a, Ty> TyLayout<'a, Ty> {
9691003
{
9701004
Ty::for_variant(self, cx, variant_index)
9711005
}
1006+
1007+
/// Callers might want to use `C: LayoutOf<Ty=Ty, TyLayout: MaybeResult<Self>>`
1008+
/// to allow recursion (see `might_permit_zero_init` below for an example).
9721009
pub fn field<C>(self, cx: &C, i: usize) -> C::TyLayout
9731010
where
9741011
Ty: TyLayoutMethods<'a, C>,
9751012
C: LayoutOf<Ty = Ty>,
9761013
{
9771014
Ty::field(self, cx, i)
9781015
}
1016+
9791017
pub fn pointee_info_at<C>(self, cx: &C, offset: Size) -> Option<PointeeInfo>
9801018
where
9811019
Ty: TyLayoutMethods<'a, C>,
@@ -999,4 +1037,81 @@ impl<'a, Ty> TyLayout<'a, Ty> {
9991037
Abi::Aggregate { sized } => sized && self.size.bytes() == 0,
10001038
}
10011039
}
1040+
1041+
/// Determines if this type permits "raw" initialization by just transmuting some
1042+
/// memory into an instance of `T`.
1043+
/// `zero` indicates if the memory is zero-initialized, or alternatively
1044+
/// left entirely uninitialized.
1045+
/// This is conservative: in doubt, it will answer `true`.
1046+
pub fn might_permit_raw_init<C, E>(
1047+
self,
1048+
cx: &C,
1049+
zero: bool,
1050+
) -> Result<bool, E>
1051+
where
1052+
Self: Copy,
1053+
Ty: TyLayoutMethods<'a, C>,
1054+
C: LayoutOf<Ty = Ty, TyLayout: MaybeResult<Self, Error = E>>
1055+
{
1056+
let scalar_allows_raw_init = move |s: &Scalar| -> bool {
1057+
let range = &s.valid_range;
1058+
if zero {
1059+
// The range must contain 0.
1060+
range.contains(&0) ||
1061+
(*range.start() > *range.end()) // wrap-around allows 0
1062+
} else {
1063+
// The range must include all values.
1064+
*range.start() == range.end().wrapping_add(1)
1065+
}
1066+
};
1067+
1068+
// Abi is the most informative here.
1069+
let res = match &self.abi {
1070+
Abi::Uninhabited => false, // definitely UB
1071+
Abi::Scalar(s) => scalar_allows_raw_init(s),
1072+
Abi::ScalarPair(s1, s2) =>
1073+
scalar_allows_raw_init(s1) && scalar_allows_raw_init(s2),
1074+
Abi::Vector { element: s, count } =>
1075+
*count == 0 || scalar_allows_raw_init(s),
1076+
Abi::Aggregate { .. } => {
1077+
match self.variants {
1078+
Variants::Multiple { .. } =>
1079+
if zero {
1080+
// FIXME: could we identify the variant with discriminant 0, check that?
1081+
true
1082+
} else {
1083+
// FIXME: This needs to have some sort of discriminant,
1084+
// which cannot be undef. But for now we are conservative.
1085+
true
1086+
},
1087+
Variants::Single { .. } => {
1088+
// For aggregates, recurse.
1089+
match self.fields {
1090+
FieldPlacement::Union(..) => true, // An all-0 unit is fine.
1091+
FieldPlacement::Array { .. } =>
1092+
// FIXME: The widely use smallvec 0.6 creates uninit arrays
1093+
// with any element type, so let us not (yet) complain about that.
1094+
// count == 0 ||
1095+
// self.field(cx, 0).to_result()?.might_permit_raw_init(cx, zero)?
1096+
true,
1097+
FieldPlacement::Arbitrary { ref offsets, .. } => {
1098+
let mut res = true;
1099+
// Check that all fields accept zero-init.
1100+
for idx in 0..offsets.len() {
1101+
let field = self.field(cx, idx).to_result()?;
1102+
if !field.might_permit_raw_init(cx, zero)? {
1103+
res = false;
1104+
break;
1105+
}
1106+
}
1107+
res
1108+
}
1109+
}
1110+
}
1111+
}
1112+
}
1113+
};
1114+
trace!("might_permit_raw_init({:?}, zero={}) = {}", self.details, zero, res);
1115+
Ok(res)
1116+
}
10021117
}

src/librustc_target/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@
1010
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
1111
#![feature(bool_to_option)]
1212
#![feature(nll)]
13+
#![feature(never_type)]
14+
#![feature(associated_type_bounds)]
15+
#![feature(exhaustive_patterns)]
1316

1417
#[macro_use]
1518
extern crate log;

src/librustc_typeck/check/intrinsic.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,10 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) {
147147
),
148148
"rustc_peek" => (1, vec![param(0)], param(0)),
149149
"caller_location" => (0, vec![], tcx.caller_location_ty()),
150-
"panic_if_uninhabited" => (1, Vec::new(), tcx.mk_unit()),
150+
"panic_if_uninhabited" |
151+
"panic_if_zero_invalid" |
152+
"panic_if_any_invalid" =>
153+
(1, Vec::new(), tcx.mk_unit()),
151154
"init" => (1, Vec::new(), param(0)),
152155
"uninit" => (1, Vec::new(), param(0)),
153156
"forget" => (1, vec![param(0)], tcx.mk_unit()),

0 commit comments

Comments
 (0)