Skip to content

Commit

Permalink
never construct value on stack in new_box_zeroed
Browse files Browse the repository at this point in the history
On lower opt-levels the compiler might not optimize out the
`layout.size() == 0` branch and emits code for the if-body. This will
cause a stack allocation for `Self`. Avoid calling new_zeroed() and
directly construct the Box from a dangling pointer instead.
  • Loading branch information
Freax13 committed Aug 29, 2024
1 parent 51c17a3 commit 074ee4e
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2128,7 +2128,12 @@ pub unsafe trait FromZeros: TryFromBytes {
// no allocation, but `Box` does require a correct dangling pointer.
let layout = Layout::new::<Self>();
if layout.size() == 0 {
return Box::new(Self::new_zeroed());
// SAFETY: Contructing a Box to a ZST from a dangling pointer is
// explicitly allowed:
// https://doc.rust-lang.org/std/boxed/index.html#memory-layout
unsafe {
return Box::from_raw(NonNull::dangling().as_ptr());
}
}

// TODO(#429): Add a "SAFETY" comment and remove this `allow`.
Expand Down

0 comments on commit 074ee4e

Please sign in to comment.