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

Cannot copy self-reference as of 0.18 #118

Open
vbkaisetsu opened this issue Jul 14, 2024 · 1 comment · May be fixed by #119
Open

Cannot copy self-reference as of 0.18 #118

vbkaisetsu opened this issue Jul 14, 2024 · 1 comment · May be fixed by #119

Comments

@vbkaisetsu
Copy link

The following code works in 0.17.2:

use ouroboros::self_referencing;

#[self_referencing]
struct Outer {
    data: String,

    #[borrows(data)]
    #[covariant]
    ref1: Option<&'this str>,

    #[borrows(data)]
    #[covariant]
    ref2: Option<&'this str>,
}

fn main() {
    let mut s = OuterBuilder {
        data: "test".to_string(),
        ref1_builder: |_| None,
        ref2_builder: |x| Some(x),
    }.build();

    s.with_mut(|f| {
        *f.ref1 = *f.ref2;
    });

    dbg!(s.borrow_ref1());
}

But in 0.18.4, it gives the following error:

error[E0597]: `s` does not live long enough
  --> src/main.rs:23:5
   |
17 |       let mut s = OuterBuilder {
   |           ----- binding `s` declared here
...
23 |       s.with_mut(|f| {
   |       ^ borrowed value does not live long enough
   |  _____|
   | |
24 | |         *f.ref1 = *f.ref2;
25 | |     });
   | |______- argument requires that `s` is borrowed for `'static`
...
28 |   }
   |   - `s` dropped here while still borrowed

error[E0502]: cannot borrow `s` as immutable because it is also borrowed as mutable
  --> src/main.rs:27:10
   |
23 |       s.with_mut(|f| {
   |       - mutable borrow occurs here
   |  _____|
   | |
24 | |         *f.ref1 = *f.ref2;
25 | |     });
   | |______- argument requires that `s` is borrowed for `'static`
26 |
27 |       dbg!(s.borrow_ref1());
   |            ^ immutable borrow occurs here
@someguynamedjosh
Copy link
Owner

This is unfortunately a limitation of a check that was introduced to prevent a situation like the following:

#[self_referencing]
struct Outer {
    data: String,

    #[borrows(data)]
    #[covariant]
    ref1: Option<&'this str>,

    other: String,
}


fn main() {
    let mut s = OuterBuilder {
        data: "test".to_string(),
        ref1_builder: |_| None,
        other: "other".to_string(),
    }.build();

    s.with_mut(|f| {
        *f.ref1 = Some(f.other);
    });

    drop(s);
}

Which causes a use-after-free, since other is dropped before ref1 in the generated struct.

@vbkaisetsu vbkaisetsu linked a pull request Jul 15, 2024 that will close this issue
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