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

UB for borrowed type containing interior mutability #5

Closed
dtolnay opened this issue Mar 14, 2021 · 2 comments
Closed

UB for borrowed type containing interior mutability #5

dtolnay opened this issue Mar 14, 2021 · 2 comments

Comments

@dtolnay
Copy link

dtolnay commented Mar 14, 2021

Filing to track @jDomantas's report in https://www.reddit.com/r/rust/comments/m42fjx/safetouse_procmacrofree_selfreferential_structs/gqt6jkm/.

The signature of get_or_init_dependent improperly permits the caller to pick an arbitrarily short lifetime 'a, and then put a reference that is only live for 'a into Dependent. Then it's possible for them to later pick a longer lifetime 'b and get a Dependent<'b> back out, leading to Use After Free or other undefined behavior in safe code.

use once_self_cell::sync_once_self_cell;
use std::cell::Cell;

struct Owner(Cell<&'static str>);

struct Borrowed<'a>(Cell<&'a str>);

impl<'a> From<&'a Owner> for Borrowed<'a> {
    fn from(owner: &'a Owner) -> Borrowed<'a> {
        let r = owner.0.get();
        Borrowed(Cell::new(r))
    }
}

sync_once_self_cell!(
    SelfRef,
    Owner,
    Borrowed<'_>,
);

fn do_evil(cell: &SelfRef) {
    let str = String::from("short lived");
    let dep = cell.get_or_init_dependent();
    dep.0.set(&str);
}

fn main() {
    let cell = SelfRef::new(Owner(Cell::new("static string")));
    do_evil(&cell);
    let dep = cell.get_or_init_dependent();
    println!("string: {:?}", dep.0.get());
}
@Voultapher
Copy link
Owner

See this comment chain for more background and discussion of different approaches https://www.reddit.com/r/rust/comments/m42fjx/safetouse_procmacrofree_selfreferential_structs/gqxvk7r/?context=10000

I'll fix it once I find the time.

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

No branches or pull requests

2 participants