Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 2 commits into from
Jul 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions library/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
12 changes: 11 additions & 1 deletion library/core/src/mem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -654,6 +654,8 @@ pub unsafe fn zeroed<T>() -> T {
/// produce a value of type `T`, while doing nothing at all.
///
/// **This function is deprecated.** Use [`MaybeUninit<T>`] instead.
/// It also might be slower than using `MaybeUninit<T>` 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].
Expand Down Expand Up @@ -683,7 +685,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()
}
}

Expand Down