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

Is it sound to field-project into a Cell or UnsafeCell? #451

Open
joshlf opened this issue Aug 14, 2023 · 5 comments
Open

Is it sound to field-project into a Cell or UnsafeCell? #451

joshlf opened this issue Aug 14, 2023 · 5 comments

Comments

@joshlf
Copy link

joshlf commented Aug 14, 2023

Given a &Cell<T> or &UnsafeCell<T>, is it sound to produce a &Cell<F> or &UnsafeCell<F> to a field within the original (assuming that lifetimes are respected etc etc)? E.g.:

pub fn project(cell: &Cell<(u8, u16)>) -> &Cell<u16> {
    let cell_raw: *const _ = cell;
    let inner_raw: *const (u8, u16) = cell_raw.cast();
    let field_raw = core::mem::addr_of!(inner_raw.1);
    unsafe { &*field_raw }
}
@RalfJung
Copy link
Member

This is intended to be sound for tuples and structs, yes. We have a function safely exposing this for slices, but Rust cannot express this for tuples or structs.

It is clearly not sound for enums.

@RalfJung
Copy link
Member

RalfJung commented Aug 14, 2023

That said, there is rust-lang/rust#80778, so currently this might actually not be sound.

EDIT: Ah no structs and tuples are still fine. It's arrays where there is a problem.

@joshlf
Copy link
Author

joshlf commented Aug 15, 2023

Thanks for the breadcrumbs!

@joshlf
Copy link
Author

joshlf commented Aug 29, 2023

Given a &Cell<T> or &UnsafeCell<T>, is it sound to produce a &Cell<F> or &UnsafeCell<F> to a field within the original (assuming that lifetimes are respected etc etc)? E.g.:

pub fn project(cell: &Cell<(u8, u16)>) -> &Cell<u16> {
    let cell_raw: *const _ = cell;
    let inner_raw: *const (u8, u16) = cell_raw.cast();
    let field_raw = core::mem::addr_of!(inner_raw.1);
    unsafe { &*field_raw }
}

Now that rust-lang/rust#114795 has landed, is this guaranteed to be sound?

@RalfJung
Copy link
Member

That is definitely my intention, yes. But ultimately this needs a T-libs-abi guarantee.

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