Skip to content

Commit 84ff4da

Browse files
committed
mem::uninitialized: mitigate many incorrect uses of this function
1 parent b3f4c31 commit 84ff4da

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

library/core/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@
163163
#![feature(allow_internal_unstable)]
164164
#![feature(associated_type_bounds)]
165165
#![feature(auto_traits)]
166+
#![feature(cfg_sanitize)]
166167
#![feature(cfg_target_has_atomic)]
167168
#![feature(cfg_target_has_atomic_equal_alignment)]
168169
#![feature(const_fn_floating_point_arithmetic)]

library/core/src/mem/mod.rs

+9-1
Original file line numberDiff line numberDiff line change
@@ -683,7 +683,15 @@ pub unsafe fn uninitialized<T>() -> T {
683683
// SAFETY: the caller must guarantee that an uninitialized value is valid for `T`.
684684
unsafe {
685685
intrinsics::assert_uninit_valid::<T>();
686-
MaybeUninit::uninit().assume_init()
686+
let mut val = MaybeUninit::<T>::uninit();
687+
688+
// Fill memory with 0x01, as an imperfect mitigation for old code that uses this function on
689+
// bool, nonnull, and noundef types. But don't do this if we actively want to detect UB.
690+
if !cfg!(any(miri, sanitize = "memory")) {
691+
val.as_mut_ptr().write_bytes(0x01, 1);
692+
}
693+
694+
val.assume_init()
687695
}
688696
}
689697

0 commit comments

Comments
 (0)