-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Why is this code illegal? #8
Comments
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 use std::{
alloc::{Layout,alloc,dealloc},
ops::{Deref,DerefMut}
};
struct MyBox<T>(*mut T);
impl <T> MyBox<T> {
fn new(val: T) -> MyBox<T> {
unsafe {
let p : *mut T = alloc(Layout::new::<T>()).cast();
assert!(!p.is_null());
p.write(val);
MyBox(p)
}
}
}
impl <T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.0.as_ref().unwrap() }
}
}
impl <T> DerefMut for MyBox<T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { self.0.as_mut().unwrap() }
}
}
impl <T> Drop for MyBox<T> {
fn drop(&mut self) {
unsafe { dealloc(self.0.cast(), Layout::new::<T>()); }
}
} Now, the following triggers UB in MIRI: fn main() {
let mut b = MyBox::new(1);
let p = std::ptr::addr_of_mut!(*b);
*b = 2;
assert_eq!( unsafe { p.read() }, 2);
} But if I subtly change how I construct fn main() {
let mut b = MyBox::new(1);
let p = b.0;
*b = 2;
assert_eq!( unsafe { p.read() }, 2);
} Just by momentarily going through |
I filed a rust issue about this: rust-lang/rust#128803. Closing this to push discussion over to that. |
My understanding of this crate was that it ought to make this sort of thing legal:
It does seem to run fine, even if I hide various pieces of it inside
#[inline(never)]
functions. However, miri complains about it:Is this a bug in miri, a bug in
aliasable
, or a bug in my understanding?The text was updated successfully, but these errors were encountered: