Kimundi / owning-ref-rs

A library for creating references that carry their owner with them.
MIT License
359 stars 50 forks source link

OwningRefMut::as_owner and as_owner_mut are unsound #61

Open comex opened 4 years ago

comex commented 4 years ago

No fancy Stacked Borrows stuff in this one, just normal memory unsafety. These methods of OwningRefMut:

    /// A reference to the underlying owner.
    pub fn as_owner(&self) -> &O {
        &self.owner
    }

    /// A mutable reference to the underlying owner.
    pub fn as_owner_mut(&mut self) -> &mut O {
        &mut self.owner
    }

...are both unsound, because they can be used to access the owner object while the associated reference thinks it has unique access to it. In particular, it can be used to modify that data and invalidate the reference. (Doing so is straightforward with as_owner_mut, and is still possible with as_owner with some interior mutability shenanigans.)

Here is a simple test case for both methods. Clone the repo and run either

and you should get a heap-use-after-free error.

This doesn't affect the non-Mut OwningRef; OwningRef::as_owner is sound.