Skip to content

get_mut is unsound #1

@qwaz-theori

Description

@qwaz-theori
use self_reference::{OptionRef, SelfReference};

fn main() {
    let mut self_ref: SelfReference<&(), OptionRef<Box<usize>>> =
        SelfReference::new(&(), || Box::leak(Box::new(None)).as_ref());
    {
        let x = Box::new(1234usize);
        // Should be disallowed
        *self_ref.get_mut() = Some(&x);
    }
    // Prints dangling pointer
    println!("{:p}", self_ref.get_ref().unwrap().as_ref());
}

get_mut() can shorten the lifetime 'x in R::Type<'x>. This is unsound because T is invariant in &mut T.

https://doc.rust-lang.org/nomicon/subtyping.html#variance

MIRI log
error: Undefined Behavior: trying to retag from <3097> for Unique permission at alloc1467[0x0], but that tag does not exist in the borrow stack for this location
  --> /home/qwaz/.cargo/registry/src/index.crates.io-6f17d22bba15001f/self-reference-0.2.2/src/utils.rs:44:12
   |
44 |     return value;
   |            ^^^^^
   |            |
   |            trying to retag from <3097> for Unique permission at alloc1467[0x0], but that tag does not exist in the borrow stack for this location
   |            this error occurs as part of retag at alloc1467[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: <3097> was created by a Unique retag at offsets [0x0..0x8]
  --> src/main.rs:9:10
   |
9  |         *self_ref.get_mut() = Some(&x);
   |          ^^^^^^^^^^^^^^^^^^
help: <3097> was later invalidated at offsets [0x0..0x8] by a Unique retag
  --> src/main.rs:9:10
   |
9  |         *self_ref.get_mut() = Some(&x);
   |          ^^^^^^^^^^^^^^^^^^
   = note: BACKTRACE (of the first span):
   = note: inside `self_reference::utils::detach_lifetime_get_mut::<self_reference::OptionRef<std::boxed::Box<usize>>>` at /home/qwaz/.cargo/registry/src/index.crates.io-6f17d22bba15001f/self-reference-0.2.2/src/utils.rs:44:12: 44:17
   = note: inside `self_reference::SelfReference::<'_, &(), self_reference::OptionRef<std::boxed::Box<usize>>>::get_mut` at /home/qwaz/.cargo/registry/src/index.crates.io-6f17d22bba15001f/self-reference-0.2.2/src/lib.rs:144:18: 144:69
note: inside `main`
  --> src/main.rs:9:10
   |
9  |         *self_ref.get_mut() = Some(&x);
   |          ^^^^^^^^^^^^^^^^^^

note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace

error: aborting due to previous error

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions