From 84ff4da7267bc9fdb3a423a25cb7947333388ead Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Tue, 12 Jul 2022 09:41:47 -0400 Subject: [PATCH 1/2] mem::uninitialized: mitigate many incorrect uses of this function --- library/core/src/lib.rs | 1 + library/core/src/mem/mod.rs | 10 +++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index bd256cec8a147..b4c9f443cacad 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -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)] diff --git a/library/core/src/mem/mod.rs b/library/core/src/mem/mod.rs index ecd2b75ae4427..1e665896a5ace 100644 --- a/library/core/src/mem/mod.rs +++ b/library/core/src/mem/mod.rs @@ -683,7 +683,15 @@ pub unsafe fn uninitialized() -> T { // SAFETY: the caller must guarantee that an uninitialized value is valid for `T`. unsafe { intrinsics::assert_uninit_valid::(); - MaybeUninit::uninit().assume_init() + let mut val = MaybeUninit::::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() } } From 7b4149474b2fdf8b30cb99fdd17303b94746ebce Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Tue, 12 Jul 2022 11:56:35 -0400 Subject: [PATCH 2/2] mention mitigation in the docs --- library/core/src/mem/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/library/core/src/mem/mod.rs b/library/core/src/mem/mod.rs index 1e665896a5ace..31f44e371180b 100644 --- a/library/core/src/mem/mod.rs +++ b/library/core/src/mem/mod.rs @@ -654,6 +654,8 @@ pub unsafe fn zeroed() -> T { /// produce a value of type `T`, while doing nothing at all. /// /// **This function is deprecated.** Use [`MaybeUninit`] instead. +/// It also might be slower than using `MaybeUninit` due to mitigations that were put in place to +/// limit the potential harm caused by incorrect use of this function in legacy code. /// /// The reason for deprecation is that the function basically cannot be used /// correctly: it has the same effect as [`MaybeUninit::uninit().assume_init()`][uninit].