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

UB-check for alignment of ptr to Box::from_raw{,_in} #137325

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
39 changes: 34 additions & 5 deletions library/alloc/src/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1017,7 +1017,7 @@ impl<T: ?Sized> Box<T> {
/// resulting `Box`. Specifically, the `Box` destructor will call
/// the destructor of `T` and free the allocated memory. For this
/// to be safe, the memory must have been allocated in accordance
/// with the [memory layout] used by `Box` .
/// with the [memory layout] used by `Box`.
///
/// # Safety
///
Expand Down Expand Up @@ -1056,8 +1056,25 @@ impl<T: ?Sized> Box<T> {
#[stable(feature = "box_raw", since = "1.4.0")]
#[inline]
#[must_use = "call `drop(Box::from_raw(ptr))` if you intend to drop the `Box`"]
pub unsafe fn from_raw(raw: *mut T) -> Self {
unsafe { Self::from_raw_in(raw, Global) }
pub unsafe fn from_raw(ptr: *mut T) -> Self {
core::assert_unsafe_precondition!(
check_language_ub,
"Box::from_raw requires that its pointer argument is properly aligned and not null",
(
ptr: *const () = ptr as *const (),
align: usize = align_of::<T>(),
) => core::intrinsics::const_eval_select!(
@capture { ptr: *const (), align: usize } -> bool:
if const {
!ptr.is_null()
} else {
ptr.is_aligned_to(align) && !ptr.is_null()
}
)
Comment on lines +1067 to +1073
Copy link
Member

Choose a reason for hiding this comment

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

We have maybe_is_aligned_and_not_null as a helper for this, why not use that?

Copy link
Member Author

@hkBst hkBst Feb 23, 2025

Choose a reason for hiding this comment

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

I can't use that, because impl<T: ?Sized> Box<T> means that I cannot use T::IS_ZST, which means I don't know how to call maybe_is_aligned_and_not_null.

);

//assert_pointer_is_aligned_and_not_null!("Box::from_raw", ptr, align_of::<T>(), T::IS_ZST);
unsafe { Self::from_raw_in(ptr, Global) }
}

/// Constructs a box from a `NonNull` pointer.
Expand Down Expand Up @@ -1111,6 +1128,12 @@ impl<T: ?Sized> Box<T> {
#[inline]
#[must_use = "call `drop(Box::from_non_null(ptr))` if you intend to drop the `Box`"]
pub unsafe fn from_non_null(ptr: NonNull<T>) -> Self {
/*assert_pointer_is_aligned_and_not_null!(
"Box::from_non_null",
ptr,
align_of::<T>(),
T::IS_ZST
);*/
unsafe { Self::from_raw(ptr.as_ptr()) }
}
}
Expand Down Expand Up @@ -1166,8 +1189,14 @@ impl<T: ?Sized, A: Allocator> Box<T, A> {
#[unstable(feature = "allocator_api", issue = "32838")]
#[rustc_const_unstable(feature = "const_box", issue = "92521")]
#[inline]
pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
Box(unsafe { Unique::new_unchecked(raw) }, alloc)
pub const unsafe fn from_raw_in(ptr: *mut T, alloc: A) -> Self {
/*assert_pointer_is_aligned_and_not_null!(
"Box::from_raw_in",
ptr,
align_of::<T>(),
T::IS_ZST
);*/
Box(unsafe { Unique::new_unchecked(ptr) }, alloc)
}

/// Constructs a box from a `NonNull` pointer in the given allocator.
Expand Down
1 change: 1 addition & 0 deletions library/alloc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@
#![feature(try_trait_v2)]
#![feature(try_with_capacity)]
#![feature(tuple_trait)]
#![feature(ub_checks)]
#![feature(unicode_internals)]
#![feature(unsize)]
#![feature(unwrap_infallible)]
Expand Down
4 changes: 2 additions & 2 deletions library/core/src/intrinsics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3839,7 +3839,7 @@ where
/// markes as `#[inline]`.
///
/// See [`const_eval_select()`] for the rules and requirements around that intrinsic.
pub(crate) macro const_eval_select {
pub macro const_eval_select {
(
@capture$([$($binders:tt)*])? { $($arg:ident : $ty:ty = $val:expr),* $(,)? } $( -> $ret:ty )? :
if const
Expand Down Expand Up @@ -4169,7 +4169,7 @@ pub const fn size_of<T>() -> usize {
#[rustc_intrinsic_const_stable_indirect]
#[rustc_intrinsic]
#[rustc_intrinsic_must_be_overridden]
pub const fn min_align_of<T>() -> usize {
pub const fn min_align_of<T: ?Sized>() -> usize {
unreachable!()
}

Expand Down
2 changes: 1 addition & 1 deletion library/core/src/mem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,7 @@ pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_align_of", since = "1.24.0")]
pub const fn align_of<T>() -> usize {
pub const fn align_of<T: ?Sized>() -> usize {
intrinsics::min_align_of::<T>()
}

Expand Down
15 changes: 14 additions & 1 deletion library/core/src/ub_checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ pub use intrinsics::ub_checks as check_library_ub;
/// language UB checks which generally produce better errors.
#[inline]
#[rustc_allow_const_fn_unstable(const_eval_select)]
pub(crate) const fn check_language_ub() -> bool {
pub const fn check_language_ub() -> bool {
// Only used for UB checks so we may const_eval_select.
intrinsics::ub_checks()
&& const_eval_select!(
Expand Down Expand Up @@ -129,6 +129,19 @@ pub(crate) const fn maybe_is_aligned_and_not_null(
)
}

/// Specialized version of `assert_unsafe_precondition` for checking that a pointer is properly aligned and not null
#[macro_export]
#[unstable(feature = "ub_checks", issue = "none")]
macro_rules! assert_pointer_is_aligned_and_not_null {
($function_name: literal, $ptr: expr, $align: expr, $is_zst: expr) => {
::core::assert_unsafe_precondition!(
check_language_ub,
concat!($function_name, " requires that its pointer argument is properly aligned and not null"),
() => ::core::ub_checks::maybe_is_aligned_and_not_null(ptr as *const (), $align, $is_zst)
);
}
}

#[inline]
pub(crate) const fn is_valid_allocation_size(size: usize, len: usize) -> bool {
let max_len = if size == 0 { usize::MAX } else { isize::MAX as usize / size };
Expand Down
Loading