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

[Merged by Bors] - Ensure Ptr/PtrMut/OwningPtr are aligned when casting in debug builds #7117

Closed
wants to merge 14 commits into from
62 changes: 57 additions & 5 deletions crates/bevy_ptr/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,15 @@ impl<'a> Ptr<'a> {

/// Transforms this [`Ptr<T>`] into a `&T` with the same lifetime
///
/// # Panics
/// In debug builds, this function will panic if the pointer is not properly
/// aligned for `T`.
///
/// # Safety
/// Must point to a valid `T`
#[inline]
pub unsafe fn deref<T>(self) -> &'a T {
&*self.as_ptr().cast()
&*self.as_ptr().cast::<T>().ensure_aligned()
}

/// Gets the underlying pointer, erasing the associated lifetime.
Expand Down Expand Up @@ -160,11 +164,15 @@ impl<'a> PtrMut<'a> {

/// Transforms this [`PtrMut<T>`] into a `&mut T` with the same lifetime
///
/// # Panics
/// In debug builds, this function will panic if the pointer is not properly
/// aligned for `T`.
///
/// # Safety
/// Must point to a valid `T`
#[inline]
pub unsafe fn deref_mut<T>(self) -> &'a mut T {
&mut *self.as_ptr().cast()
&mut *self.as_ptr().cast::<T>().ensure_aligned()
}

/// Gets the underlying pointer, erasing the associated lifetime.
Expand Down Expand Up @@ -213,20 +221,28 @@ impl<'a> OwningPtr<'a> {

/// Consumes the [`OwningPtr`] to obtain ownership of the underlying data of type `T`.
///
/// # Panics
/// In debug builds, this function will panic if the pointer is not properly
/// aligned for `T`.
///
/// # Safety
/// Must point to a valid `T`.
#[inline]
pub unsafe fn read<T>(self) -> T {
self.as_ptr().cast::<T>().read()
self.as_ptr().cast::<T>().ensure_aligned().read()
}

/// Consumes the [`OwningPtr`] to drop the underlying data of type `T`.
///
/// # Panics
/// In debug builds, this function will panic if the pointer is not properly
/// aligned for `T`.
///
/// # Safety
/// Must point to a valid `T`.
#[inline]
pub unsafe fn drop_as<T>(self) {
self.as_ptr().cast::<T>().drop_in_place();
self.as_ptr().cast::<T>().ensure_aligned().drop_in_place();
}

/// Gets the underlying pointer, erasing the associated lifetime.
Expand Down Expand Up @@ -292,9 +308,10 @@ impl<'a, T> Copy for ThinSlicePtr<'a, T> {}
impl<'a, T> From<&'a [T]> for ThinSlicePtr<'a, T> {
#[inline]
fn from(slice: &'a [T]) -> Self {
let ptr = slice.as_ptr() as *mut T;
Self {
// SAFETY: a reference can never be null
ptr: unsafe { NonNull::new_unchecked(slice.as_ptr() as *mut T) },
ptr: unsafe { NonNull::new_unchecked(ptr.ensure_aligned()) },
#[cfg(debug_assertions)]
len: slice.len(),
_marker: PhantomData,
Expand All @@ -305,6 +322,7 @@ impl<'a, T> From<&'a [T]> for ThinSlicePtr<'a, T> {
/// Creates a dangling pointer with specified alignment.
/// See [`NonNull::dangling`].
pub fn dangling_with_align(align: NonZeroUsize) -> NonNull<u8> {
assert!(align.is_power_of_two(), "Alignment must be power of two.");
james7132 marked this conversation as resolved.
Show resolved Hide resolved
// SAFETY: The pointer will not be null, since it was created
// from the address of a `NonZeroUsize`.
unsafe { NonNull::new_unchecked(align.get() as *mut u8) }
Expand Down Expand Up @@ -357,3 +375,37 @@ impl<'a, T> UnsafeCellDeref<'a, T> for &'a UnsafeCell<T> {
self.get().read()
}
}

trait EnsureAligned {
fn ensure_aligned(self) -> Self;
}

// Disable this for miri runs as it already checks if pointer to reference
// casts are properly aligned.
#[cfg(all(debug_assertions, not(miri)))]
impl<T: Sized> EnsureAligned for *mut T {
#[track_caller]
fn ensure_aligned(self) -> Self {
james7132 marked this conversation as resolved.
Show resolved Hide resolved
let align = core::mem::align_of::<T>();
// Implemenation shamelessly borrowed from the currently unstable
// ptr.is_aligned_to.
//
// Replace once https://github.com/rust-lang/rust/issues/96284 is stable.
assert!(
self as usize & (align - 1) == 0,
"pointer is not aligned. Address {:p} does not have alignemnt {} for type {}",
self,
align,
core::any::type_name::<T>(),
);
self
}
}

#[cfg(any(not(debug_assertions), miri))]
impl<T: Sized> EnsureAligned for *mut T {
#[inline(always)]
fn ensure_aligned(self) -> Self {
self
}
}