Closed
Description
My understanding of this crate was that it ought to make this sort of thing legal:
use std::ptr::addr_of_mut;
use aliasable::boxed::AliasableBox;
fn main() {
let mut b = AliasableBox::from_unique(Box::new(1usize));
let p = addr_of_mut!(*b);
*b = 2;
assert_eq!(unsafe { p.read() }, 2);
}
It does seem to run fine, even if I hide various pieces of it inside #[inline(never)]
functions. However, miri complains about it:
error: Undefined Behavior: attempting a read access using <2514> at alloc1093[0x0], but that tag does not exist in the borrow stack for this location
--> src/main.rs:8:25
|
8 | assert_eq!(unsafe { p.read() }, 2);
| ^^^^^^^^
| |
| attempting a read access using <2514> at alloc1093[0x0], but that tag does not exist in the borrow stack for this location
| this error occurs as part of an access at alloc1093[0x0..0x8]
|
= 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: <2514> was created by a SharedReadWrite retag at offsets [0x0..0x8]
--> src/main.rs:6:13
|
6 | let p = addr_of_mut!(*b);
| ^^^^^^^^^^^^^^^^
help: <2514> was later invalidated at offsets [0x0..0x8] by a Unique retag
--> src/main.rs:7:5
|
7 | *b = 2;
| ^^
= note: BACKTRACE (of the first span):
= note: inside `main` at src/main.rs:8:25: 8:33
= note: this error originates in the macro `addr_of_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace
error: aborting due to 1 previous error
Is this a bug in miri, a bug in aliasable
, or a bug in my understanding?
Activity
dfoxfranke commentedon Aug 7, 2024
After more investigation, I think everything is working as designed, and that this is just a horrible landmine arising from the design of stacked borrow semantics. Just to convince myself that this has nothing particularly to do with
std::boxed::Box
or withAliasableBox
, I wrote my own trivial box implementation which doesn't usecore::ptr::Unique
or evenNonNull
:Now, the following triggers UB in MIRI:
But if I subtly change how I construct
p
, there's no UB any more:Just by momentarily going through
<MyBox as DerefMut>::deref_mut
which returns a&mut T
and casting to a*mut T
, instead of directly obtaining a*mut T
, my pointer becomes infected with stacked-borrow cooties and writing to*b
invalidates it.dfoxfranke commentedon Aug 8, 2024
I filed a rust issue about this: rust-lang/rust#128803. Closing this to push discussion over to that.