[PATCH] rust: rbtree: call rb_erase() before KBox::from_raw() in remove_current()

From: Bilal Hashim

Date: Fri Nov 27 2026 - 07:07:11 EST


In CursorMut::remove_current(), KBox::from_raw(this) is currently called
before bindings::rb_erase(&mut (*this).links, ...). Constructing and
moving a KBox asserts exclusive (noalias) ownership over the allocation,
which invalidates the raw pointer `this` and aliases with the subsequent
bindings::rb_erase() call that mutates the rb_node links in C.

Move bindings::rb_erase() before KBox::from_raw(this), matching the order
already used in CursorMut::remove_neighbor().

Tested with LLVM=-22 and Rust KUnit doctests in QEMU (372/372 passed,
including all 11 rbtree doctests).

Signed-off-by: Bilal Hashim <AeeSec@xxxxxxx>
---
--- a/rust/kernel/rbtree.rs
+++ b/rust/kernel/rbtree.rs
@@ -918,15 +918,15 @@
pub fn remove_current(self) -> (Option<Self>, RBTreeNode<K, V>) {
let prev = self.get_neighbor_raw(Direction::Prev);
let next = self.get_neighbor_raw(Direction::Next);
+ // SAFETY: The reference to the tree used to create the cursor outlives the cursor, so
+ // the tree cannot change. By the tree invariant, all nodes are valid.
+ unsafe { bindings::rb_erase(self.current.as_ptr(), addr_of_mut!(self.tree.root)) };
// SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
// point to the links field of `Node<K, V>` objects.
let this = unsafe { container_of!(self.current.as_ptr(), Node<K, V>, links) };
// SAFETY: `this` is valid by the type invariants as described above.
let node = unsafe { KBox::from_raw(this) };
let node = RBTreeNode { node };
- // SAFETY: The reference to the tree used to create the cursor outlives the cursor, so
- // the tree cannot change. By the tree invariant, all nodes are valid.
- unsafe { bindings::rb_erase(&mut (*this).links, addr_of_mut!(self.tree.root)) };

// INVARIANT:
// - `current` is a valid node in the [`RBTree`] pointed to by `self.tree`.