Skip to content

Commit 335f7f5

Browse files
committed
swap_typed_nonoverlapping: properly detect overlap even when swapping scalar values
1 parent 7291b1e commit 335f7f5

File tree

7 files changed

+53
-48
lines changed

7 files changed

+53
-48
lines changed

compiler/rustc_const_eval/src/interpret/call.rs

+1-13
Original file line numberDiff line numberDiff line change
@@ -883,19 +883,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
883883
.local_to_op(mir::RETURN_PLACE, None)
884884
.expect("return place should always be live");
885885
let dest = self.frame().return_place.clone();
886-
let res = if self.stack().len() == 1 {
887-
// The initializer of constants and statics will get validated separately
888-
// after the constant has been fully evaluated. While we could fall back to the default
889-
// code path, that will cause -Zenforce-validity to cycle on static initializers.
890-
// Reading from a static's memory is not allowed during its evaluation, and will always
891-
// trigger a cycle error. Validation must read from the memory of the current item.
892-
// For Miri this means we do not validate the root frame return value,
893-
// but Miri anyway calls `read_target_isize` on that so separate validation
894-
// is not needed.
895-
self.copy_op_no_dest_validation(&op, &dest)
896-
} else {
897-
self.copy_op_allow_transmute(&op, &dest)
898-
};
886+
let res = self.copy_op_allow_transmute(&op, &dest);
899887
trace!("return value: {:?}", self.dump_place(&dest.into()));
900888
// We delay actually short-circuiting on this error until *after* the stack frame is
901889
// popped, since we want this error to be attributed to the caller, whose type defines

compiler/rustc_const_eval/src/interpret/intrinsics.rs

+22-6
Original file line numberDiff line numberDiff line change
@@ -425,7 +425,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
425425
self.write_scalar(result, dest)?;
426426
}
427427
sym::typed_swap_nonoverlapping => {
428-
self.typed_swap_intrinsic(&args[0], &args[1])?;
428+
self.typed_swap_nonoverlapping_intrinsic(&args[0], &args[1])?;
429429
}
430430

431431
sym::vtable_size => {
@@ -638,19 +638,35 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
638638
}
639639

640640
/// Does a *typed* swap of `*left` and `*right`.
641-
fn typed_swap_intrinsic(
641+
fn typed_swap_nonoverlapping_intrinsic(
642642
&mut self,
643643
left: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
644644
right: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
645645
) -> InterpResult<'tcx> {
646646
let left = self.deref_pointer(left)?;
647647
let right = self.deref_pointer(right)?;
648-
debug_assert_eq!(left.layout, right.layout);
648+
assert_eq!(left.layout, right.layout);
649+
assert!(left.layout.is_sized());
649650
let kind = MemoryKind::Stack;
650651
let temp = self.allocate(left.layout, kind)?;
651-
self.copy_op(&left, &temp)?;
652-
self.copy_op(&right, &left)?; // this checks that they are non-overlapping
653-
self.copy_op(&temp, &right)?;
652+
self.copy_op(&left, &temp)?; // checks alignment of `left`
653+
654+
// We want to always enforce non-overlapping, even if this is a scalar type.
655+
// Therefore we directly use the underlying `mem_copy` here.
656+
self.mem_copy(right.ptr(), left.ptr(), left.layout.size, /*nonoverlapping*/ true)?;
657+
// This means we also need to do the validation of the value that used to be in `right`
658+
// ourselves. This value is now in `left.` The one that started out in `left` already got
659+
// validated by the copy above.
660+
if M::enforce_validity(self, left.layout) {
661+
self.validate_operand(
662+
&left.clone().into(),
663+
M::enforce_validity_recursively(self, left.layout),
664+
/*reset_provenance_and_padding*/ true,
665+
)?;
666+
}
667+
668+
self.copy_op(&temp, &right)?; // checks alignment of `right`
669+
654670
self.deallocate_ptr(temp.ptr(), None, kind)?;
655671
interp_ok(())
656672
}

compiler/rustc_const_eval/src/interpret/place.rs

+5-26
Original file line numberDiff line numberDiff line change
@@ -773,22 +773,6 @@ where
773773
interp_ok(())
774774
}
775775

776-
/// Copies the data from an operand to a place.
777-
/// The layouts of the `src` and `dest` may disagree.
778-
/// Does not perform validation of the destination.
779-
/// The only known use case for this function is checking the return
780-
/// value of a static during stack frame popping.
781-
#[inline(always)]
782-
pub(super) fn copy_op_no_dest_validation(
783-
&mut self,
784-
src: &impl Projectable<'tcx, M::Provenance>,
785-
dest: &impl Writeable<'tcx, M::Provenance>,
786-
) -> InterpResult<'tcx> {
787-
self.copy_op_inner(
788-
src, dest, /* allow_transmute */ true, /* validate_dest */ false,
789-
)
790-
}
791-
792776
/// Copies the data from an operand to a place.
793777
/// The layouts of the `src` and `dest` may disagree.
794778
#[inline(always)]
@@ -797,9 +781,7 @@ where
797781
src: &impl Projectable<'tcx, M::Provenance>,
798782
dest: &impl Writeable<'tcx, M::Provenance>,
799783
) -> InterpResult<'tcx> {
800-
self.copy_op_inner(
801-
src, dest, /* allow_transmute */ true, /* validate_dest */ true,
802-
)
784+
self.copy_op_inner(src, dest, /* allow_transmute */ true)
803785
}
804786

805787
/// Copies the data from an operand to a place.
@@ -810,9 +792,7 @@ where
810792
src: &impl Projectable<'tcx, M::Provenance>,
811793
dest: &impl Writeable<'tcx, M::Provenance>,
812794
) -> InterpResult<'tcx> {
813-
self.copy_op_inner(
814-
src, dest, /* allow_transmute */ false, /* validate_dest */ true,
815-
)
795+
self.copy_op_inner(src, dest, /* allow_transmute */ false)
816796
}
817797

818798
/// Copies the data from an operand to a place.
@@ -824,22 +804,21 @@ where
824804
src: &impl Projectable<'tcx, M::Provenance>,
825805
dest: &impl Writeable<'tcx, M::Provenance>,
826806
allow_transmute: bool,
827-
validate_dest: bool,
828807
) -> InterpResult<'tcx> {
829808
// These are technically *two* typed copies: `src` is a not-yet-loaded value,
830-
// so we're going a typed copy at `src` type from there to some intermediate storage.
809+
// so we're doing a typed copy at `src` type from there to some intermediate storage.
831810
// And then we're doing a second typed copy from that intermediate storage to `dest`.
832811
// But as an optimization, we only make a single direct copy here.
833812

834813
// Do the actual copy.
835814
self.copy_op_no_validate(src, dest, allow_transmute)?;
836815

837-
if validate_dest && M::enforce_validity(self, dest.layout()) {
816+
if M::enforce_validity(self, dest.layout()) {
838817
let dest = dest.to_place();
839818
// Given that there were two typed copies, we have to ensure this is valid at both types,
840819
// and we have to ensure this loses provenance and padding according to both types.
841820
// But if the types are identical, we only do one pass.
842-
if allow_transmute && src.layout().ty != dest.layout().ty {
821+
if src.layout().ty != dest.layout().ty {
843822
self.validate_operand(
844823
&dest.transmute(src.layout(), self)?,
845824
M::enforce_validity_recursively(self, src.layout()),
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
error: Undefined Behavior: constructing invalid value: encountered 0x03, but expected a boolean
2+
--> tests/fail/intrinsics/typed-swap-invalid-scalar.rs:LL:CC
3+
|
4+
LL | typed_swap_nonoverlapping(a, b);
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value: encountered 0x03, but expected a boolean
6+
|
7+
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
8+
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
9+
= note: BACKTRACE:
10+
= note: inside `invalid_scalar` at tests/fail/intrinsics/typed-swap-invalid-scalar.rs:LL:CC
11+
note: inside `main`
12+
--> tests/fail/intrinsics/typed-swap-invalid-scalar.rs:LL:CC
13+
|
14+
LL | invalid_scalar();
15+
| ^^^^^^^^^^^^^^^^
16+
17+
note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace
18+
19+
error: aborting due to 1 previous error
20+

src/tools/miri/tests/fail/intrinsics/typed-swap-invalid-scalar.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
1+
//@revisions: left right
12
#![feature(core_intrinsics)]
23
#![feature(rustc_attrs)]
34

45
use std::intrinsics::typed_swap_nonoverlapping;
56
use std::ptr::addr_of_mut;
67

78
fn invalid_scalar() {
8-
let mut a = 1_u8;
9-
let mut b = 2_u8;
9+
// We run the test twice, with either the left or the right side being invalid.
10+
let mut a = if cfg!(left) { 2_u8} else { 1_u8 };
11+
let mut b = if cfg!(right) { 3_u8} else { 1_u8 };
1012
unsafe {
1113
let a = addr_of_mut!(a).cast::<bool>();
1214
let b = addr_of_mut!(b).cast::<bool>();

src/tools/miri/tests/fail/intrinsics/typed-swap-overlap.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::intrinsics::typed_swap_nonoverlapping;
55
use std::ptr::addr_of_mut;
66

77
fn main() {
8-
let mut a = [0_u8; 100];
8+
let mut a = 0_u8;
99
unsafe {
1010
let a = addr_of_mut!(a);
1111
typed_swap_nonoverlapping(a, a); //~ERROR: called on overlapping ranges

0 commit comments

Comments
 (0)