From 074ee4ec598bbeb10174ab5800f2164faeb7edad Mon Sep 17 00:00:00 2001 From: Tom Dohrmann Date: Thu, 29 Aug 2024 07:31:21 +0000 Subject: [PATCH] never construct value on stack in new_box_zeroed 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. --- src/lib.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 7e38f882eb..13db915dbd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2128,7 +2128,12 @@ pub unsafe trait FromZeros: TryFromBytes { // no allocation, but `Box` does require a correct dangling pointer. let layout = Layout::new::(); 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`.