Skip to content
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

The unsafe_self_cell field is accessible, allowing UB from safe code #17

Closed
steffahn opened this issue Sep 20, 2021 · 2 comments · Fixed by #19
Closed

The unsafe_self_cell field is accessible, allowing UB from safe code #17

steffahn opened this issue Sep 20, 2021 · 2 comments · Fixed by #19

Comments

@steffahn
Copy link
Contributor

use self_cell::self_cell;

type Dep1<'a> = (&'a str, &'static str);

self_cell! {
    pub struct Struct1 {
        owner: String,
        #[covariant]
        dependent: Dep1,
    }
}

type Dep2<'a> = (&'static str, &'a str);

self_cell! {
    pub struct Struct2 {
        owner: String,
        #[covariant]
        dependent: Dep2,
    }
}

fn main() {
    let hello: &'static str;
    {
        let mut x1 = Struct1::new(String::from("Hello World"), |s| (s, ""));
        let mut x2 = Struct2::new(String::new(), |_| ("", ""));
        std::mem::swap(&mut x1.unsafe_self_cell, &mut x2.unsafe_self_cell);
        hello = x2.borrow_dependent().0;

        dbg!(hello); // "Hello World"
        // hello is now a static reference in to the "Hello World" string
    }
    // the String is dropped at the end of the block above

    dbg!(hello); // prints garbage, use-after-free
}
@steffahn steffahn changed the title The unsafe_self_cell field is accessible, leading to unsound safe code The unsafe_self_cell field is accessible, allowing UB from safe code Sep 20, 2021
@Voultapher
Copy link
Owner

Arghh, I had hoped that by marking all member function of UnsafeSelfCell as unsafe users couldn't run into safe UB. Any idea how to address this?

@steffahn
Copy link
Contributor Author

Yes, an additional argument to UnsafeSelfCell should help… I’ll open a PR

Voultapher added a commit that referenced this issue Oct 2, 2021
This release addresses two somewhat exotic ways self_cell could be used in an
unsound fashion to cause UB. See issues #17 and #18. Thanks @steffahn for
reporting and helping to fix these issues.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants