Skip to content

Commit

Permalink
Fix UPtr
Browse files Browse the repository at this point in the history
Casting a T pointer to a usize and misalign it causes undefined
behavior. See rust-lang/rust#126866
  • Loading branch information
tgeng committed Jun 24, 2024
1 parent 12828f3 commit b0809fc
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,7 @@ strum_macros = "0.25.3"
enum-map = "2.7.3"
home = "0.5.9"
itertools = "0.12.0"
enum-ordinalize = "4.3.0"
enum-ordinalize = "4.3.0"

[profile.dev]
opt-level = 0
12 changes: 7 additions & 5 deletions runtime/src/types.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};

// TODO: I need to figure out a way to force function pointers to be 4-byte aligned. This is true
Expand Down Expand Up @@ -79,11 +80,12 @@ impl UniformPtr<*const usize> for usize {
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct UPtr<T> (T);
#[repr(C, align(8))]
pub struct UPtr<T> (*const u8, PhantomData<T>);

impl<'a, T> UPtr<&'a T> {
pub fn as_uniform(&self) -> usize {
self.0 as *const T as usize
self.0 as usize
}
}

Expand All @@ -92,7 +94,7 @@ impl<'a, T> Deref for UPtr<&'a T> {

fn deref(&self) -> &Self::Target {
unsafe {
let ptr = self.0 as *const T as usize;
let ptr = self.0 as usize;
let ptr = ptr & POINTER_MASK;
&*(ptr as *const T)
}
Expand All @@ -104,7 +106,7 @@ impl<'a, T> Deref for UPtr<&'a mut T> {

fn deref(&self) -> &Self::Target {
unsafe {
let ptr = self.0 as *const T as usize;
let ptr = self.0 as usize;
let ptr = ptr & POINTER_MASK;
&*(ptr as *const T)
}
Expand All @@ -114,7 +116,7 @@ impl<'a, T> Deref for UPtr<&'a mut T> {
impl<'a, T> DerefMut for UPtr<&'a mut T> {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe {
let ptr = self.0 as *mut T as usize;
let ptr = self.0 as usize;
let ptr = ptr & POINTER_MASK;
&mut *(ptr as *mut T)
}
Expand Down

0 comments on commit b0809fc

Please sign in to comment.