Skip to content
Open
Show file tree
Hide file tree
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
7 changes: 6 additions & 1 deletion library/alloc/src/vec/into_iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,12 @@ impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
// SAFETY: same as for advance_by()
self.end = unsafe { self.end.sub(step_size) };
}
let to_drop = ptr::slice_from_raw_parts_mut(self.end as *mut T, step_size);
let to_drop = if T::IS_ZST {
// ZST may cause unalignment
ptr::slice_from_raw_parts_mut(ptr::NonNull::<T>::dangling().as_ptr(), step_size)
} else {
ptr::slice_from_raw_parts_mut(self.end as *mut T, step_size)
};
// SAFETY: same as for advance_by()
unsafe {
ptr::drop_in_place(to_drop);
Expand Down
14 changes: 14 additions & 0 deletions library/alloctests/tests/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2717,3 +2717,17 @@ fn vec_null_ptr_roundtrip() {
let new = roundtripped.with_addr(ptr.addr());
unsafe { new.read() };
}

// Regression test for Undefined Behavior (UB) caused by IntoIter::nth_back (#148682)
// when dealing with high-aligned Zero-Sized Types (ZSTs).
#[test]
fn zst_vec_iter_nth_back_regression() {
Copy link
Member

Choose a reason for hiding this comment

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

Can you add tests for other collections that I suspect may well have the same bug? At the very least VecDeque, BTreeMap, HashMap, and BinaryHeap all seem likely to be potentially at risk.

#[repr(align(8))]
struct Thing;
let v = vec![Thing, Thing];
let mut iter = v.into_iter();
let _ = iter.nth_back(1);
let v2 = vec![Thing, Thing];
let mut iter2 = v2.into_iter();
let _ = iter2.nth_back(0);
}
Loading