Skip to content

Commit e6cef04

Browse files
committed
Auto merge of #70807 - Dylan-DPC:rollup-qd1kgl2, r=Dylan-DPC
Rollup of 5 pull requests Successful merges: - #70558 (Fix some aliasing issues in Vec) - #70760 (docs: make the description of Result::map_or more clear) - #70769 (Miri: remove an outdated FIXME) - #70776 (clarify comment in RawVec::into_box) - #70806 (fix Miri assignment sanity check) Failed merges: r? @ghost
2 parents 607b858 + 31b8d65 commit e6cef04

File tree

9 files changed

+138
-39
lines changed

9 files changed

+138
-39
lines changed

src/liballoc/raw_vec.rs

+6-3
Original file line numberDiff line numberDiff line change
@@ -570,16 +570,19 @@ impl<T> RawVec<T, Global> {
570570
///
571571
/// # Safety
572572
///
573-
/// `shrink_to_fit(len)` must be called immediately prior to calling this function. This
574-
/// implies, that `len` must be smaller than or equal to `self.capacity()`.
573+
/// * `len` must be greater than or equal to the most recently requested capacity, and
574+
/// * `len` must be less than or equal to `self.capacity()`.
575+
///
576+
/// Note, that the requested capacity and `self.capacity()` could differ, as
577+
/// an allocator could overallocate and return a greater memory block than requested.
575578
pub unsafe fn into_box(self, len: usize) -> Box<[MaybeUninit<T>]> {
579+
// Sanity-check one half of the safety requirement (we cannot check the other half).
576580
debug_assert!(
577581
len <= self.capacity(),
578582
"`len` must be smaller than or equal to `self.capacity()`"
579583
);
580584

581585
let me = ManuallyDrop::new(self);
582-
// NOTE: not calling `capacity()` here; actually using the real `cap` field!
583586
let slice = slice::from_raw_parts_mut(me.ptr() as *mut MaybeUninit<T>, len);
584587
Box::from_raw(slice)
585588
}

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
}

src/libcore/result.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -521,14 +521,16 @@ impl<T, E> Result<T, E> {
521521
}
522522
}
523523

524-
/// Applies a function to the contained value (if any),
525-
/// or returns the provided default (if not).
524+
/// Applies a function to the contained value (if [`Ok`]),
525+
/// or returns the provided default (if [`Err`]).
526526
///
527527
/// Arguments passed to `map_or` are eagerly evaluated; if you are passing
528528
/// the result of a function call, it is recommended to use [`map_or_else`],
529529
/// which is lazily evaluated.
530530
///
531531
/// [`map_or_else`]: #method.map_or_else
532+
/// [`Ok`]: enum.Result.html#variant.Ok
533+
/// [`Err`]: enum.Result.html#variant.Err
532534
///
533535
/// # Examples
534536
///

src/librustc_mir/interpret/eval_context.rs

+36-16
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,11 @@ use rustc_middle::mir::interpret::{
1414
sign_extend, truncate, AllocId, FrameInfo, GlobalId, InterpResult, Pointer, Scalar,
1515
};
1616
use rustc_middle::ty::layout::{self, TyAndLayout};
17-
use rustc_middle::ty::query::TyCtxtAt;
18-
use rustc_middle::ty::subst::SubstsRef;
19-
use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable};
17+
use rustc_middle::ty::{
18+
self, fold::BottomUpFolder, query::TyCtxtAt, subst::SubstsRef, Ty, TyCtxt, TypeFoldable,
19+
};
2020
use rustc_span::source_map::DUMMY_SP;
21-
use rustc_target::abi::{Abi, Align, HasDataLayout, LayoutOf, Size, TargetDataLayout};
21+
use rustc_target::abi::{Align, HasDataLayout, LayoutOf, Size, TargetDataLayout};
2222

2323
use super::{
2424
Immediate, MPlaceTy, Machine, MemPlace, MemPlaceMeta, Memory, OpTy, Operand, Place, PlaceTy,
@@ -213,30 +213,50 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> LayoutOf for InterpCx<'mir, 'tcx, M> {
213213
/// Test if it is valid for a MIR assignment to assign `src`-typed place to `dest`-typed value.
214214
/// This test should be symmetric, as it is primarily about layout compatibility.
215215
pub(super) fn mir_assign_valid_types<'tcx>(
216+
tcx: TyCtxt<'tcx>,
216217
src: TyAndLayout<'tcx>,
217218
dest: TyAndLayout<'tcx>,
218219
) -> bool {
219220
if src.ty == dest.ty {
220221
// Equal types, all is good.
221222
return true;
222223
}
223-
// Type-changing assignments can happen for (at least) two reasons:
224-
// - `&mut T` -> `&T` gets optimized from a reborrow to a mere assignment.
225-
// - Subtyping is used. While all normal lifetimes are erased, higher-ranked lifetime
226-
// bounds are still around and can lead to type differences.
227-
// There is no good way to check the latter, so we compare layouts instead -- but only
228-
// for values with `Scalar`/`ScalarPair` abi.
229-
// FIXME: Do something more accurate, type-based.
230-
match &src.abi {
231-
Abi::Scalar(..) | Abi::ScalarPair(..) => src.layout == dest.layout,
232-
_ => false,
224+
if src.layout != dest.layout {
225+
// Layout differs, definitely not equal.
226+
// We do this here because Miri would *do the wrong thing* if we allowed layout-changing
227+
// assignments.
228+
return false;
233229
}
230+
231+
// Type-changing assignments can happen for (at least) two reasons:
232+
// 1. `&mut T` -> `&T` gets optimized from a reborrow to a mere assignment.
233+
// 2. Subtyping is used. While all normal lifetimes are erased, higher-ranked types
234+
// with their late-bound lifetimes are still around and can lead to type differences.
235+
// Normalize both of them away.
236+
let normalize = |ty: Ty<'tcx>| {
237+
ty.fold_with(&mut BottomUpFolder {
238+
tcx,
239+
// Normalize all references to immutable.
240+
ty_op: |ty| match ty.kind {
241+
ty::Ref(_, pointee, _) => tcx.mk_imm_ref(tcx.lifetimes.re_erased, pointee),
242+
_ => ty,
243+
},
244+
// We just erase all late-bound lifetimes, but this is not fully correct (FIXME):
245+
// lifetimes in invariant positions could matter (e.g. through associated types).
246+
// We rely on the fact that layout was confirmed to be equal above.
247+
lt_op: |_| tcx.lifetimes.re_erased,
248+
// Leave consts unchanged.
249+
ct_op: |ct| ct,
250+
})
251+
};
252+
normalize(src.ty) == normalize(dest.ty)
234253
}
235254

236255
/// Use the already known layout if given (but sanity check in debug mode),
237256
/// or compute the layout.
238257
#[cfg_attr(not(debug_assertions), inline(always))]
239258
pub(super) fn from_known_layout<'tcx>(
259+
tcx: TyCtxt<'tcx>,
240260
known_layout: Option<TyAndLayout<'tcx>>,
241261
compute: impl FnOnce() -> InterpResult<'tcx, TyAndLayout<'tcx>>,
242262
) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
@@ -246,7 +266,7 @@ pub(super) fn from_known_layout<'tcx>(
246266
if cfg!(debug_assertions) {
247267
let check_layout = compute()?;
248268
assert!(
249-
mir_assign_valid_types(check_layout, known_layout),
269+
mir_assign_valid_types(tcx, check_layout, known_layout),
250270
"expected type differs from actual type.\nexpected: {:?}\nactual: {:?}",
251271
known_layout.ty,
252272
check_layout.ty,
@@ -424,7 +444,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
424444
// have to support that case (mostly by skipping all caching).
425445
match frame.locals.get(local).and_then(|state| state.layout.get()) {
426446
None => {
427-
let layout = from_known_layout(layout, || {
447+
let layout = from_known_layout(self.tcx.tcx, layout, || {
428448
let local_ty = frame.body.local_decls[local].ty;
429449
let local_ty =
430450
self.subst_from_frame_and_normalize_erasing_regions(frame, local_ty);

src/librustc_mir/interpret/operand.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -529,7 +529,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
529529
ty::ConstKind::Value(val_val) => val_val,
530530
};
531531
// Other cases need layout.
532-
let layout = from_known_layout(layout, || self.layout_of(val.ty))?;
532+
let layout = from_known_layout(self.tcx.tcx, layout, || self.layout_of(val.ty))?;
533533
let op = match val_val {
534534
ConstValue::ByRef { alloc, offset } => {
535535
let id = self.tcx.alloc_map.lock().create_memory_alloc(alloc);

src/librustc_mir/interpret/place.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -868,7 +868,7 @@ where
868868
// We do NOT compare the types for equality, because well-typed code can
869869
// actually "transmute" `&mut T` to `&T` in an assignment without a cast.
870870
assert!(
871-
mir_assign_valid_types(src.layout, dest.layout),
871+
mir_assign_valid_types(self.tcx.tcx, src.layout, dest.layout),
872872
"type mismatch when copying!\nsrc: {:?},\ndest: {:?}",
873873
src.layout.ty,
874874
dest.layout.ty,
@@ -922,7 +922,7 @@ where
922922
src: OpTy<'tcx, M::PointerTag>,
923923
dest: PlaceTy<'tcx, M::PointerTag>,
924924
) -> InterpResult<'tcx> {
925-
if mir_assign_valid_types(src.layout, dest.layout) {
925+
if mir_assign_valid_types(self.tcx.tcx, src.layout, dest.layout) {
926926
// Fast path: Just use normal `copy_op`
927927
return self.copy_op(src, dest);
928928
}

src/librustc_mir/interpret/terminator.rs

-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,6 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
7575
}
7676

7777
Drop { location, target, unwind } => {
78-
// FIXME(CTFE): forbid drop in const eval
7978
let place = self.eval_place(location)?;
8079
let ty = place.layout.ty;
8180
trace!("TerminatorKind::drop: {:?}, type {}", location, ty);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// check-pass
2+
#![feature(const_fn)]
3+
4+
const fn nested(x: (for<'a> fn(&'a ()), String)) -> (fn(&'static ()), String) {
5+
x
6+
}
7+
8+
pub const TEST: (fn(&'static ()), String) = nested((|_x| (), String::new()));
9+
10+
fn main() {}

0 commit comments

Comments
 (0)