mem::uninitialized: mitigate many incorrect uses of this function

This commit is contained in:
Ralf Jung 2022-07-12 09:41:47 -04:00
parent b3f4c31199
commit 84ff4da726
2 changed files with 10 additions and 1 deletions

View File

@ -163,6 +163,7 @@
#![feature(allow_internal_unstable)]
#![feature(associated_type_bounds)]
#![feature(auto_traits)]
#![feature(cfg_sanitize)]
#![feature(cfg_target_has_atomic)]
#![feature(cfg_target_has_atomic_equal_alignment)]
#![feature(const_fn_floating_point_arithmetic)]

View File

@ -683,7 +683,15 @@ pub unsafe fn uninitialized<T>() -> T {
// SAFETY: the caller must guarantee that an uninitialized value is valid for `T`.
unsafe {
intrinsics::assert_uninit_valid::<T>();
MaybeUninit::uninit().assume_init()
let mut val = MaybeUninit::<T>::uninit();
// Fill memory with 0x01, as an imperfect mitigation for old code that uses this function on
// bool, nonnull, and noundef types. But don't do this if we actively want to detect UB.
if !cfg!(any(miri, sanitize = "memory")) {
val.as_mut_ptr().write_bytes(0x01, 1);
}
val.assume_init()
}
}