aidancully/containerof

Encounter dangling reference with `OwnBox::<T>::deref/deref_mut`

Closed this issue · 1 comments

The source of unsoundness

containerof/src/lib.rs

Lines 161 to 165 in 58f7c16

impl<T> ops::Deref for OwnBox<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
unsafe { mem::transmute(self.get_address()) }
}

Hi, we consider the implementation of deref and deref_mut are unsound because the memory at self.get_address() is unallocated. Therefore, if callers access the type after transmute will encounter a dangling reference.

To reproduce the bug

use containerof::OwnBox;
use std::boxed::Box;

fn main() {
    let bx = Box::new(1u8);
    let ob = OwnBox::from_box(bx);
    println!("{:?}", *ob);
}

to run with miri,

error: Undefined Behavior: constructing invalid value: encountered a dangling reference (address 0x89140 is unallocated)
   --> /${HOME}/.cargo/registry/src/github.com-1ecc6299db9ec823/containerof-0.2.2/src/lib.rs:164:18
    |
164 |         unsafe { mem::transmute(self.get_address()) }
    |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value: encountered a dangling reference (address 0x89140 is unallocated)
    |
    = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior

Thank you for your report, and I apologize for the delay addressing it. This should be fixed in v0.3.0 (just published).