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

MappedRwLockWriteGuard::downgrade is unsound #198

Closed
pitdicker opened this issue Jan 2, 2020 · 2 comments · Fixed by #244
Closed

MappedRwLockWriteGuard::downgrade is unsound #198

pitdicker opened this issue Jan 2, 2020 · 2 comments · Fixed by #244

Comments

@pitdicker
Copy link

pitdicker commented Jan 2, 2020

I was trying to put my finger on what exactly it was that made RefMut::downgrade unsound in rust-lang/rust#57401, and wrote it down as part of a blog post.

To quote from there (sorry to quote myself):

RwLockWriteGuard in parking_lot has a downgrade method which turns it into a RwLockReadGuard. It is instructive to explore why RefCells RefMut can't provide a similar method to turn it into a Ref.

The signature of the closure used in RefMut::map is FnOnce(&mut T) -> &mut U. This gives it an interesting property: it allows you to bypass conventions of wrapped interior mutability types because you have exclusive access (with as_mut).

Because RefMut::map made the promise to wrapped types that its reference is unique, the returned RefMut has to remain unique. It can't be turned into a Ref, of which multiple can exist. Example of how it can go wrong:

let refcell = RefCell::new(Cell::new(10u32));
let ref_mut = refcell.borrow_mut();
RefMut::map(ref_mut, |x| x.get_mut());
let ref1 = RefMut::downgrade(ref_mut);
let cell_ref = &*ref1;
let ref2 = refcell.borrow();
// We can now mutate the `Cell` through `ref2` while there also exists a
// reference to its interior.

For RwLockWriteGuard however downgrade is sound, because it's map method returns another type. But that returned type, MappedRwLockWriteGuard, now has to remain unique, so MappedRwLockWriteGuard::downgrade is unsound.

@pitdicker pitdicker changed the title MappedRwLockReadGuard::downgrade is unsound MappedRwLockWriteGuard::downgrade is unsound Jan 2, 2020
@Amanieu
Copy link
Owner

Amanieu commented Jan 3, 2020

Nice catch! Now I just need to figure out what to do about the breaking change this will cause...

@Amanieu
Copy link
Owner

Amanieu commented Jan 4, 2020

I marked the function as deprecated for now, and will remove it in a future release.

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