Skip to content

Fix zero-sized reference to deallocated memory #91797

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

Merged
merged 1 commit into from
Dec 12, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions library/alloc/src/vec/drain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,6 @@ impl<T, A: Allocator> Drop for Drain<'_, T, A> {

let iter = mem::replace(&mut self.iter, (&mut []).iter());
let drop_len = iter.len();
let drop_ptr = iter.as_slice().as_ptr();

// forget iter so there's no aliasing reference
drop(iter);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does iter have an actual impl Drop that used to be run here?

Copy link
Member Author

@the8472 the8472 Dec 12, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it wasn't actually necessary. I thought slice::Iter internally holds a slice reference that would be invalidated by mutating the vec through other pointers. But it actually contains pointers.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, at least under Stacked Borrows, droping a reference doesn't help with anything -- it only marks the reference as active the moment it gets dropped.


let mut vec = self.vec;

Expand All @@ -155,6 +151,12 @@ impl<T, A: Allocator> Drop for Drain<'_, T, A> {
return;
}

// as_slice() must only be called when iter.len() is > 0 because
// vec::Splice modifies vec::Drain fields and may grow the vec which would invalidate
// the iterator's internal pointers. Creating a reference to deallocated memory
// is invalid even when it is zero-length
let drop_ptr = iter.as_slice().as_ptr();

unsafe {
// drop_ptr comes from a slice::Iter which only gives us a &[T] but for drop_in_place
// a pointer with mutable provenance is necessary. Therefore we must reconstruct
Expand Down