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

Double-free with into_owner #24

Closed
steffahn opened this issue Oct 5, 2021 · 2 comments · Fixed by #25
Closed

Double-free with into_owner #24

steffahn opened this issue Oct 5, 2021 · 2 comments · Fixed by #25

Comments

@steffahn
Copy link
Contributor

steffahn commented Oct 5, 2021

use std::cell::Cell;

use self_cell::self_cell;

type O = Cell<Option<Box<u8>>>;

self_cell! {
    struct S {
        owner: O,
        #[covariant]
        dependent: D,
    }
}

struct D<'a>(&'a O);

impl Drop for D<'_> {
    fn drop(&mut self) {
        self.0.take();
    }
}

fn main() {
    let s = S::new(Cell::new(Some(Box::new(42))), |o| D(o));
    s.into_owner();
}
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/small_pg`
thread 'main' panicked at 'explicit panic', src/main.rs:20:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
free(): double free detected in tcache 2
[1]    394203 IOT instruction (core dumped)  cargo r

The underlying problem is

let owner_ptr: *const Owner = &(*joined_ptr.as_ptr()).owner;
// Move owner out so it can be returned.
let owner = read(owner_ptr);
// Clean up rest of JoinedCell
drop_in_place(&mut (*joined_ptr.as_ptr()).dependent);

where the owner is read before dependent is dropped, so dropping dependent can access the original owner, but into_owner returns the copy created beforehand.


I have a branch that fixes this as well as some memory leaks: ebbf355...c482860

The branch is based on #21 (one of the memory leaks is in drop_joined), so I’ll only open a PR after #21 is merged. So consider not to release a new version yet after merging #21 😉

@steffahn
Copy link
Contributor Author

steffahn commented Oct 5, 2021

Actually… I just noticed that a panic isn’t necessary in the example (and I edited the example accordingly). So I can split up the double-free issue and the memory leaks and create two separate branches; the first one (the double-free) can already get a PR right now.

@Voultapher
Copy link
Owner

Dang, thanks for finding this! Goes to show how hard it is to write unsafe Rust even with the best intentions and code review.

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