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

Fix in-place collection leak when remaining element destructor panic #101642

Merged
merged 5 commits into from
Oct 4, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
8 changes: 6 additions & 2 deletions library/alloc/src/vec/in_place_collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ use core::iter::{InPlaceIterable, SourceIter, TrustedRandomAccessNoCoerce};
use core::mem::{self, ManuallyDrop};
use core::ptr::{self};

use super::{InPlaceDrop, SpecFromIter, SpecFromIterNested, Vec};
use super::{InPlaceDrop, InPlaceDstBufDrop, SpecFromIter, SpecFromIterNested, Vec};

/// Specialization marker for collecting an iterator pipeline into a Vec while reusing the
/// source allocation, i.e. executing the pipeline in place.
Expand Down Expand Up @@ -193,12 +193,16 @@ where

// Drop any remaining values at the tail of the source but prevent drop of the allocation
// itself once IntoIter goes out of scope.
// If the drop panics then we also leak any elements collected into dst_buf.
// If the drop panics then we also try to drop the destination buffer and its elements.
// This is safe because `forget_allocation_drop_remaining` forgets the allocation *before*
// trying to drop the remaining elements.
SkiFire13 marked this conversation as resolved.
Show resolved Hide resolved
//
// Note: This access to the source wouldn't be allowed by the TrustedRandomIteratorNoCoerce
// contract (used by SpecInPlaceCollect below). But see the "O(1) collect" section in the
// module documenttation why this is ok anyway.
let dst_guard = InPlaceDstBufDrop { ptr: dst_buf, len, cap };
SkiFire13 marked this conversation as resolved.
Show resolved Hide resolved
src.forget_allocation_drop_remaining();
mem::forget(dst_guard);

let vec = unsafe { Vec::from_raw_parts(dst_buf, len, cap) };

Expand Down
15 changes: 15 additions & 0 deletions library/alloc/src/vec/in_place_drop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,18 @@ impl<T> Drop for InPlaceDrop<T> {
}
}
}

// A helper struct for in-place collection that drops the destination allocation and elements,
// to avoid leaking them if some other destructor panics.
pub(super) struct InPlaceDstBufDrop<T> {
pub(super) ptr: *mut T,
pub(super) len: usize,
pub(super) cap: usize,
}

impl<T> Drop for InPlaceDstBufDrop<T> {
#[inline]
fn drop(&mut self) {
unsafe { super::Vec::from_raw_parts(self.ptr, self.len, self.cap) };
}
}
2 changes: 1 addition & 1 deletion library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ use self::set_len_on_drop::SetLenOnDrop;
mod set_len_on_drop;

#[cfg(not(no_global_oom_handling))]
use self::in_place_drop::InPlaceDrop;
use self::in_place_drop::{InPlaceDrop, InPlaceDstBufDrop};

#[cfg(not(no_global_oom_handling))]
mod in_place_drop;
Expand Down
36 changes: 20 additions & 16 deletions library/alloc/tests/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1110,23 +1110,31 @@ fn test_from_iter_specialization_panic_during_iteration_drops() {
}

#[test]
fn test_from_iter_specialization_panic_during_drop_leaks() {
static mut DROP_COUNTER: usize = 0;
fn test_from_iter_specialization_panic_during_drop_doesnt_leak() {
SkiFire13 marked this conversation as resolved.
Show resolved Hide resolved
static mut DROP_COUNTER_SHOULD_BE_DROPPED: usize = 0;
static mut DROP_COUNTER_DROPPED_TWICE: usize = 0;
SkiFire13 marked this conversation as resolved.
Show resolved Hide resolved

#[derive(Debug)]
enum Droppable {
ShouldBeDropped,
DroppedTwice(Box<i32>),
PanicOnDrop,
}

impl Drop for Droppable {
fn drop(&mut self) {
match self {
Droppable::ShouldBeDropped => {
unsafe {
DROP_COUNTER_SHOULD_BE_DROPPED += 1;
}
println!("Dropping ShouldBeDropped!")
}
Droppable::DroppedTwice(_) => {
unsafe {
DROP_COUNTER += 1;
DROP_COUNTER_DROPPED_TWICE += 1;
}
println!("Dropping!")
println!("Dropping DroppedTwice!")
}
Droppable::PanicOnDrop => {
if !std::thread::panicking() {
Expand All @@ -1137,21 +1145,17 @@ fn test_from_iter_specialization_panic_during_drop_leaks() {
}
}

let mut to_free: *mut Droppable = core::ptr::null_mut();
let mut cap = 0;

let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
let mut v = vec![Droppable::DroppedTwice(Box::new(123)), Droppable::PanicOnDrop];
to_free = v.as_mut_ptr();
cap = v.capacity();
let _ = v.into_iter().take(0).collect::<Vec<_>>();
let v = vec![
Droppable::ShouldBeDropped,
Droppable::DroppedTwice(Box::new(123)),
Droppable::PanicOnDrop,
];
let _ = v.into_iter().take(1).collect::<Vec<_>>();
SkiFire13 marked this conversation as resolved.
Show resolved Hide resolved
}));

assert_eq!(unsafe { DROP_COUNTER }, 1);
// clean up the leak to keep miri happy
unsafe {
drop(Vec::from_raw_parts(to_free, 0, cap));
}
assert_eq!(unsafe { DROP_COUNTER_SHOULD_BE_DROPPED }, 1);
assert_eq!(unsafe { DROP_COUNTER_DROPPED_TWICE }, 1);
}

// regression test for issue #85322. Peekable previously implemented InPlaceIterable,
Expand Down