Skip to content

Fix bug in Box implementation - #704

Merged
sgued merged 3 commits into
rust-embedded:mainfrom
sgued:box-bug
Nov 17, 2026
Merged

sgued merged 3 commits into
rust-embedded:mainfrom
sgued:box-bug

Conversation

@sgued

@sgued sgued commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #554

@sgued
sgued force-pushed the box-bug branch 2 times, most recently from 017358d to 79ecad4 Compare November 11, 2026 10:28
@sgued

sgued commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

So we do have to use addr_of!. I love when I can guess the unsoundness before miri checks it!

@sgued sgued mentioned this pull request Nov 11, 2026
@sgued
sgued force-pushed the box-bug branch 5 times, most recently from d2f9b3c to d1d91d5 Compare November 12, 2026 17:32
@sgued
sgued marked this pull request as ready for review November 12, 2026 17:32
@sgued
sgued requested a review from a team November 12, 2026 17:32
@sgued
sgued force-pushed the box-bug branch 2 times, most recently from 0e89818 to b055714 Compare November 12, 2026 20:07
Comment thread src/pool/treiber.rs
pub data: UnsafeCell<MaybeUninit<T>>,
}

#[repr(C)]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Again this is a datatype I don't have a lot of experience maintaining in heapless, please take that into account when reading my comments.

I think the repr(C) on UnionNode was propping up some functions in boxed.rs and arc.rs that cast the node pointer to a payload pointer.

Example test that will fail, similar to the existing into_raw_from_raw with a smaller data type that rustc re-orders. I imagine this may not panic on all systems, but it panics for me on rustc 1.99.1 (58cf8f9c3 2026-10-13) and x86_64 Linux.

    #[test]
    fn into_raw_from_raw_small_type() {
        box_pool!(MyBoxPool: u8);

        MyBoxPool.manage(std::boxed::Box::leak(std::boxed::Box::new(BoxBlock::new())));

        let raw = Box::into_raw(MyBoxPool.alloc(0xAB).unwrap());
        let roundtrip = Box::into_raw(unsafe { Box::<MyBoxPool>::from_raw(raw) }) as usize;
        assert_eq!(roundtrip, raw as usize, "from_raw moved the pointer by offsetof(Node, data)");
    }

That said, I don't think re-adding repr(C) is the right solution, the code shouldn't access the payload via pointer arithmetic, it should use the data field accesses derived from the correct offset wherever the compiler chooses to place it. Example patch:

diff --git a/src/pool/arc.rs b/src/pool/arc.rs
index b48d6c6c..66ccbadf 100644
--- a/src/pool/arc.rs
+++ b/src/pool/arc.rs
@@ -177,7 +177,11 @@ impl<T> ArcPoolImpl<T> {
                 data: value,
                 strong: AtomicUsize::new(1),
             };
-            unsafe { node_ptr.as_ptr().cast::<ArcInner<T>>().write(inner) }
+            unsafe {
+                ptr::addr_of_mut!((*node_ptr.as_ptr()).data)
+                    .cast::<ArcInner<T>>()
+                    .write(inner)
+            }
 
             Ok(node_ptr)
         } else {
@@ -212,7 +216,7 @@ where
     P: ArcPool,
 {
     fn inner(&self) -> &ArcInner<P::Data> {
-        unsafe { &*self.node_ptr.as_ptr().cast::<ArcInner<P::Data>>() }
+        unsafe { &*ptr::addr_of!((*self.node_ptr.as_ptr()).data).cast::<ArcInner<P::Data>>() }
     }
 
     fn from_inner(node_ptr: NonNullPtr<Node<MaybeUninit<ArcInner<P::Data>>>>) -> Self {
@@ -220,7 +224,9 @@ where
     }
 
     unsafe fn get_mut_unchecked(this: &mut Self) -> &mut P::Data {
-        &mut *ptr::addr_of_mut!((*this.node_ptr.as_ptr().cast::<ArcInner<P::Data>>()).data)
+        &mut *ptr::addr_of_mut!(
+            (*ptr::addr_of_mut!((*this.node_ptr.as_ptr()).data).cast::<ArcInner<P::Data>>()).data
+        )
     }
 
     #[inline(never)]
@@ -277,7 +283,7 @@ where
     type Target = P::Data;
 
     fn deref(&self) -> &Self::Target {
-        unsafe { &*ptr::addr_of!((*self.node_ptr.as_ptr().cast::<ArcInner<P::Data>>()).data) }
+        &self.inner().data
     }
 }
 
diff --git a/src/pool/boxed.rs b/src/pool/boxed.rs
index bd215e1a..6743540a 100644
--- a/src/pool/boxed.rs
+++ b/src/pool/boxed.rs
@@ -244,7 +244,7 @@ where
     type Target = P::Data;
 
     fn deref(&self) -> &Self::Target {
-        unsafe { &*self.node_ptr.as_ptr().cast::<P::Data>() }
+        unsafe { &*addr_of!((*self.node_ptr.as_ptr()).data).cast::<P::Data>() }
     }
 }
 
@@ -253,7 +253,7 @@ where
     P: BoxPool,
 {
     fn deref_mut(&mut self) -> &mut Self::Target {
-        unsafe { &mut *self.node_ptr.as_ptr().cast::<P::Data>() }
+        unsafe { &mut *addr_of_mut!((*self.node_ptr.as_ptr()).data).cast::<P::Data>() }
     }
 }
 
@@ -276,7 +276,7 @@ where
     fn drop(&mut self) {
         let node = self.node_ptr;
 
-        unsafe { ptr::drop_in_place(node.as_ptr().cast::<P::Data>()) }
+        unsafe { ptr::drop_in_place(addr_of_mut!((*node.as_ptr()).data).cast::<P::Data>()) }
 
         unsafe { P::singleton().stack.push(node) }
     }
@@ -365,7 +365,7 @@ impl<T> BoxPoolImpl<T> {
 
     fn alloc(&self, value: T) -> Result<NonNullPtr<Node<MaybeUninit<T>>>, T> {
         if let Some(node_ptr) = self.stack.try_pop() {
-            unsafe { node_ptr.as_ptr().cast::<T>().write(value) }
+            unsafe { addr_of_mut!((*node_ptr.as_ptr()).data).cast::<T>().write(value) }
 
             Ok(node_ptr)
         } else {
@@ -633,15 +633,13 @@ mod tests {
             addr_of_mut!(BLOCK).as_mut().unwrap()
         });
 
-        let raw = {
-            let boxed = MyBoxPool
-                .alloc(MyStruct { value: [0xA5; 64] })
-                .ok()
-                .unwrap();
-            Box::into_raw(boxed)
-        };
+        let boxed = MyBoxPool
+            .alloc(MyStruct { value: [0xA5; 64] })
+            .ok()
+            .unwrap();
+        let addr_1 = boxed.node_ptr.as_ptr() as usize;
+        let raw = Box::into_raw(boxed);
         assert_eq!(0, NUM_DROP_CALLS.load(Ordering::Acquire));
-        let addr_1 = raw as usize;
 
         {
             let boxed_again: Box<MyBoxPool> = unsafe { Box::from_raw(raw) };

The existing into_raw_from_raw test needs to be updated too because it compares data pointers against node pointers, which were equal only with the prior layout.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I haven't touched pool prior to this either.

I also added a test for the address in Arc which fails without your patch. Thank you for finding this!

    #[test]
    fn addr_small() {
        arc_pool!(MyArcPool: u8);

        static mut BLOCK: ArcBlock<u8> = ArcBlock::new();
        let block_addr = addr_of_mut!(BLOCK).addr();
        let data_addr = unsafe { addr_of_mut!(BLOCK.node.data).addr() };
        let block = unsafe { addr_of_mut!(BLOCK).as_mut().unwrap() };
        MyArcPool.manage(block);

        let arc = MyArcPool.alloc(123).ok().unwrap();
        assert_eq!(*arc, 123);
        assert_eq!(arc.node_ptr.as_ptr().addr(), block_addr);
        assert_eq!((&*arc as *const u8).addr(), data_addr);
    }

@sgued

sgued commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

Given that this is a more complex change on a part of the crate we haven't touched in a while, a second reviewer's approval would be most welcome.

Since `UnionNode` was always unsound, this makes everying use a `Node`
that is quite similar to `StructNode`.
@sgued
sgued added this pull request to the merge queue Nov 17, 2026
Merged via the queue into rust-embedded:main with commit 570f47c Nov 17, 2026
23 checks passed
@sgued
sgued deleted the box-bug branch November 17, 2026 20:27
@sgued sgued mentioned this pull request Nov 18, 2026
4 tasks done
This was referenced Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Possible data race in the iteration of Stack's pop and UnionNode

2 participants