Skip to content

Commit

Permalink
mem::uninitialized: mitigate many incorrect uses of this function
Browse files Browse the repository at this point in the history
  • Loading branch information
RalfJung committed Jul 12, 2022
1 parent b3f4c31 commit 84ff4da
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
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
10 changes: 9 additions & 1 deletion library/core/src/mem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
}

Expand Down

0 comments on commit 84ff4da

Please sign in to comment.