#3551·napi-rs

Aliasing violation (stacked borrow/tree borrow violation) in `new_inner`

Author: zhouxt1Created Sep 29, 2026Updated Sep 29, 2026

Hi, I found the following stacked/tree borrow violation in the new_inner.

Problem description:

In the code of new_inner, the problem is storage_ptr is put on top of the storage. But when we move storage, the stack is cleared. So storage_ptr is dead, but it is still inside the global struct. And when we want to use the pointer some time later, we get an undefined behavior.

rust
unsafe fn new_inner(root_values: bool) -> Self {
  let mut storage = Box::<NativeBorrowStorage>::default();
  ...
  let storage_ptr = (&mut *storage) as *mut NativeBorrowStorage; 
  NATIVE_BORROW_SCOPES.with(|scopes| scopes.borrow_mut().push(storage_ptr));
  Self { storage, collecting: true }                              // line 149: Box moved
}

To reproduce it

bash
cargo +nightly miri test --lib bindgen_runtime::native_borrow

Miri stacked borrow output:

test bindgen_runtime::native_borrow::tests::callback_barrier_hides_outer_conversion_scope ... error: Undefined Behavior: trying to retag from <155745> for Unique permission at alloc55483[0x0], but that tag does not exist in the borrow stack for this location
   --> crates/napi/src/bindgen_runtime/native_borrow.rs:258:5
    |
258 |     (&mut *scope).guards.push(guard);
    |     ^^^^^^^^^^^^^ this error occurs as part of retag at alloc55483[0x0..0x40]
    |
    = help: this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental
    = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information
help: <155745> was created by a SharedReadWrite retag at offsets [0x0..0x40]
   --> crates/napi/src/bindgen_runtime/native_borrow.rs:146:23
    |
146 |     let storage_ptr = (&mut *storage) as *mut NativeBorrowStorage;
    |                       ^^^^^^^^^^^^^^^
help: <155745> was later invalidated at offsets [0x0..0x40] by a Unique retag
   --> crates/napi/src/bindgen_runtime/native_borrow.rs:149:7
    |
149 |       storage,
    |       ^^^^^^^
    = note: this is on thread `bindgen_runtime`

Running tree borrow also shows error.

Potential Fix

Own it through a pointer instead of a box.

rust
 pub struct NativeBorrowScope {
-  storage: Box<NativeBorrowStorage>,
+  storage: ptr::NonNull<NativeBorrowStorage>,
   collecting: bool,
 }