Skip to content

Commit 7e4ed72

Browse files
authored
Rollup merge of #70558 - RalfJung:vec-extend-aliasing, r=Amanieu
Fix some aliasing issues in Vec `Vec::extend` and `Vec::truncate` invalidated references into the vector even without reallocation, because they (implicitly) created a mutable reference covering the *entire* initialized part of the vector. Fixes #70301 I verified the fix by adding some new tests here that I ran in Miri.
2 parents 7b657d3 + 7e81c11 commit 7e4ed72

File tree

2 files changed

+79
-14
lines changed

2 files changed

+79
-14
lines changed

src/liballoc/tests/vec.rs

+66-5
Original file line numberDiff line numberDiff line change
@@ -1351,24 +1351,85 @@ fn test_try_reserve_exact() {
13511351
}
13521352

13531353
#[test]
1354-
fn test_stable_push_pop() {
1354+
fn test_stable_pointers() {
1355+
/// Pull an element from the iterator, then drop it.
1356+
/// Useful to cover both the `next` and `drop` paths of an iterator.
1357+
fn next_then_drop<I: Iterator>(mut i: I) {
1358+
i.next().unwrap();
1359+
drop(i);
1360+
}
1361+
13551362
// Test that, if we reserved enough space, adding and removing elements does not
13561363
// invalidate references into the vector (such as `v0`). This test also
13571364
// runs in Miri, which would detect such problems.
1358-
let mut v = Vec::with_capacity(10);
1365+
let mut v = Vec::with_capacity(128);
13591366
v.push(13);
13601367

1361-
// laundering the lifetime -- we take care that `v` does not reallocate, so that's okay.
1362-
let v0 = unsafe { &*(&v[0] as *const _) };
1363-
1368+
// Laundering the lifetime -- we take care that `v` does not reallocate, so that's okay.
1369+
let v0 = &mut v[0];
1370+
let v0 = unsafe { &mut *(v0 as *mut _) };
13641371
// Now do a bunch of things and occasionally use `v0` again to assert it is still valid.
1372+
1373+
// Pushing/inserting and popping/removing
13651374
v.push(1);
13661375
v.push(2);
13671376
v.insert(1, 1);
13681377
assert_eq!(*v0, 13);
13691378
v.remove(1);
13701379
v.pop().unwrap();
13711380
assert_eq!(*v0, 13);
1381+
v.push(1);
1382+
v.swap_remove(1);
1383+
assert_eq!(v.len(), 2);
1384+
v.swap_remove(1); // swap_remove the last element
1385+
assert_eq!(*v0, 13);
1386+
1387+
// Appending
1388+
v.append(&mut vec![27, 19]);
1389+
assert_eq!(*v0, 13);
1390+
1391+
// Extending
1392+
v.extend_from_slice(&[1, 2]);
1393+
v.extend(&[1, 2]); // `slice::Iter` (with `T: Copy`) specialization
1394+
v.extend(vec![2, 3]); // `vec::IntoIter` specialization
1395+
v.extend(std::iter::once(3)); // `TrustedLen` specialization
1396+
v.extend(std::iter::empty::<i32>()); // `TrustedLen` specialization with empty iterator
1397+
v.extend(std::iter::once(3).filter(|_| true)); // base case
1398+
v.extend(std::iter::once(&3)); // `cloned` specialization
1399+
assert_eq!(*v0, 13);
1400+
1401+
// Truncation
1402+
v.truncate(2);
1403+
assert_eq!(*v0, 13);
1404+
1405+
// Resizing
1406+
v.resize_with(v.len() + 10, || 42);
1407+
assert_eq!(*v0, 13);
1408+
v.resize_with(2, || panic!());
1409+
assert_eq!(*v0, 13);
1410+
1411+
// No-op reservation
1412+
v.reserve(32);
1413+
v.reserve_exact(32);
1414+
assert_eq!(*v0, 13);
1415+
1416+
// Partial draining
1417+
v.resize_with(10, || 42);
1418+
next_then_drop(v.drain(5..));
1419+
assert_eq!(*v0, 13);
1420+
1421+
// Splicing
1422+
v.resize_with(10, || 42);
1423+
next_then_drop(v.splice(5.., vec![1, 2, 3, 4, 5])); // empty tail after range
1424+
assert_eq!(*v0, 13);
1425+
next_then_drop(v.splice(5..8, vec![1])); // replacement is smaller than original range
1426+
assert_eq!(*v0, 13);
1427+
next_then_drop(v.splice(5..6, vec![1; 10].into_iter().filter(|_| true))); // lower bound not exact
1428+
assert_eq!(*v0, 13);
1429+
1430+
// Smoke test that would fire even outside Miri if an actual relocation happened.
1431+
*v0 -= 13;
1432+
assert_eq!(v[0], 0);
13721433
}
13731434

13741435
// https://github.com/rust-lang/rust/pull/49496 introduced specialization based on:

src/liballoc/vec.rs

+13-9
Original file line numberDiff line numberDiff line change
@@ -740,7 +740,8 @@ impl<T> Vec<T> {
740740
if len > self.len {
741741
return;
742742
}
743-
let s = self.get_unchecked_mut(len..) as *mut _;
743+
let remaining_len = self.len - len;
744+
let s = slice::from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
744745
self.len = len;
745746
ptr::drop_in_place(s);
746747
}
@@ -963,13 +964,15 @@ impl<T> Vec<T> {
963964
#[inline]
964965
#[stable(feature = "rust1", since = "1.0.0")]
965966
pub fn swap_remove(&mut self, index: usize) -> T {
967+
let len = self.len();
968+
assert!(index < len);
966969
unsafe {
967970
// We replace self[index] with the last element. Note that if the
968-
// bounds check on hole succeeds there must be a last element (which
971+
// bounds check above succeeds there must be a last element (which
969972
// can be self[index] itself).
970-
let hole: *mut T = &mut self[index];
971-
let last = ptr::read(self.get_unchecked(self.len - 1));
972-
self.len -= 1;
973+
let last = ptr::read(self.as_ptr().add(len - 1));
974+
let hole: *mut T = self.as_mut_ptr().add(index);
975+
self.set_len(len - 1);
973976
ptr::replace(hole, last)
974977
}
975978
}
@@ -1200,7 +1203,7 @@ impl<T> Vec<T> {
12001203
} else {
12011204
unsafe {
12021205
self.len -= 1;
1203-
Some(ptr::read(self.get_unchecked(self.len())))
1206+
Some(ptr::read(self.as_ptr().add(self.len())))
12041207
}
12051208
}
12061209
}
@@ -2020,7 +2023,7 @@ where
20202023
let (lower, _) = iterator.size_hint();
20212024
let mut vector = Vec::with_capacity(lower.saturating_add(1));
20222025
unsafe {
2023-
ptr::write(vector.get_unchecked_mut(0), element);
2026+
ptr::write(vector.as_mut_ptr(), element);
20242027
vector.set_len(1);
20252028
}
20262029
vector
@@ -2122,8 +2125,9 @@ where
21222125
self.reserve(slice.len());
21232126
unsafe {
21242127
let len = self.len();
2128+
let dst_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(len), slice.len());
2129+
dst_slice.copy_from_slice(slice);
21252130
self.set_len(len + slice.len());
2126-
self.get_unchecked_mut(len..).copy_from_slice(slice);
21272131
}
21282132
}
21292133
}
@@ -2144,7 +2148,7 @@ impl<T> Vec<T> {
21442148
self.reserve(lower.saturating_add(1));
21452149
}
21462150
unsafe {
2147-
ptr::write(self.get_unchecked_mut(len), element);
2151+
ptr::write(self.as_mut_ptr().add(len), element);
21482152
// NB can't overflow since we would have had to alloc the address space
21492153
self.set_len(len + 1);
21502154
}

0 commit comments

Comments
 (0)