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

never construct value on stack in new_box_zeroed #1601

Merged
merged 1 commit into from
Sep 3, 2024
Merged
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
22 changes: 21 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2128,7 +2128,27 @@ 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());
// Construct the `Box` from a dangling pointer to avoid calling
// `Self::new_zeroed`. This ensures that stack space is never
// allocated for `Self` even on lower opt-levels where this branch
// might not get optimized out.

// SAFETY: Per [1], when `T` is a ZST, `Box<T>`'s only validity
// requirements are that the pointer is non-null and sufficiently
// aligned. Per [2], `NonNull::dangling` produces a pointer which
// is sufficiently aligned. Since the produced pointer is a
// `NonNull`, it is non-null.
//
// [1] Per https://doc.rust-lang.org/nightly/std/boxed/index.html#memory-layout:
//
// For zero-sized values, the `Box` pointer has to be non-null and sufficiently aligned.
//
// [2] Per https://doc.rust-lang.org/std/ptr/struct.NonNull.html#method.dangling:
//
// Creates a new `NonNull` that is dangling, but well-aligned.
unsafe {
return Box::from_raw(NonNull::dangling().as_ptr());
}
Comment on lines +2149 to +2151
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you also add a comment that explains why we do this instead of Box::new(Self::new_zeroed())? The argument in your commit message makes sense, but I don't think it's obvious enough that we should expect future readers to figure it out from context.

}

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