Skip to content

Commit 7dfbc0a

Browse files
committed
miri: detect passing the same local twice as an in-place argument
1 parent ece1397 commit 7dfbc0a

File tree

4 files changed

+133
-20
lines changed

4 files changed

+133
-20
lines changed

compiler/rustc_const_eval/src/interpret/step.rs

Lines changed: 41 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
55
use either::Either;
66
use rustc_abi::{FIRST_VARIANT, FieldIdx};
7+
use rustc_data_structures::fx::FxHashSet;
78
use rustc_index::IndexSlice;
89
use rustc_middle::ty::{self, Instance, Ty};
910
use rustc_middle::{bug, mir, span_bug};
@@ -389,8 +390,9 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
389390

390391
/// Evaluate the arguments of a function call
391392
fn eval_fn_call_argument(
392-
&self,
393+
&mut self,
393394
op: &mir::Operand<'tcx>,
395+
move_definitely_disjoint: bool,
394396
) -> InterpResult<'tcx, FnArg<'tcx, M::Provenance>> {
395397
interp_ok(match op {
396398
mir::Operand::Copy(_) | mir::Operand::Constant(_) => {
@@ -399,25 +401,19 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
399401
FnArg::Copy(op)
400402
}
401403
mir::Operand::Move(place) => {
402-
// If this place lives in memory, preserve its location.
403-
// We call `place_to_op` which will be an `MPlaceTy` whenever there exists
404-
// an mplace for this place. (This is in contrast to `PlaceTy::as_mplace_or_local`
405-
// which can return a local even if that has an mplace.)
406404
let place = self.eval_place(*place)?;
407-
let op = self.place_to_op(&place)?;
408-
409-
match op.as_mplace_or_imm() {
410-
Either::Left(mplace) => FnArg::InPlace(mplace),
411-
Either::Right(_imm) => {
412-
// This argument doesn't live in memory, so there's no place
413-
// to make inaccessible during the call.
414-
// We rely on there not being any stray `PlaceTy` that would let the
415-
// caller directly access this local!
416-
// This is also crucial for tail calls, where we want the `FnArg` to
417-
// stay valid when the old stack frame gets popped.
418-
// FIXME: How can this be right for aliasing arguments?
419-
FnArg::Copy(op)
405+
if move_definitely_disjoint {
406+
// We still have to ensure that no *other* pointers are used to access this place,
407+
// so *if* it is in memory then we have to treat it as `InPlace`.
408+
// Use `place_to_op` to guarantee that we notice it being in memory.
409+
let op = self.place_to_op(&place)?;
410+
match op.as_mplace_or_imm() {
411+
Either::Left(mplace) => FnArg::InPlace(mplace),
412+
Either::Right(_imm) => FnArg::Copy(op),
420413
}
414+
} else {
415+
// We have to force this into memory to detect aliasing among `Move` arguments.
416+
FnArg::InPlace(self.force_allocation(&place)?)
421417
}
422418
}
423419
})
@@ -426,15 +422,40 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
426422
/// Shared part of `Call` and `TailCall` implementation — finding and evaluating all the
427423
/// necessary information about callee and arguments to make a call.
428424
fn eval_callee_and_args(
429-
&self,
425+
&mut self,
430426
terminator: &mir::Terminator<'tcx>,
431427
func: &mir::Operand<'tcx>,
432428
args: &[Spanned<mir::Operand<'tcx>>],
433429
) -> InterpResult<'tcx, EvaluatedCalleeAndArgs<'tcx, M>> {
434430
let func = self.eval_operand(func, None)?;
431+
432+
// Evaluating function call arguments. The tricky part here is dealing with `Move`
433+
// arguments: we have to ensure no two such arguments alias. This would be most easily done
434+
// by just forcing them all into memory and then doing the usual in-place argument
435+
// protection, but then we'd force *a lot* of arguments into memory. So we do some syntactic
436+
// pre-processing here where if all `move` arguments are syntactically distinct local
437+
// variables (and none is indirect), we can skip the in-memory forcing.
438+
let move_definitely_disjoint = 'move_definitely_disjoint: {
439+
let mut previous_locals = FxHashSet::<mir::Local>::default();
440+
for arg in args {
441+
let mir::Operand::Move(place) = arg.node else {
442+
continue; // we can skip non-`Move` arguments.
443+
};
444+
if place.is_indirect_first_projection() {
445+
// An indirect `Move` argument could alias with anything else...
446+
break 'move_definitely_disjoint false;
447+
}
448+
if !previous_locals.insert(place.local) {
449+
// This local is the base for two arguments! They might overlap.
450+
break 'move_definitely_disjoint false;
451+
}
452+
}
453+
// We found no violation so they are all definitely disjoint.
454+
true
455+
};
435456
let args = args
436457
.iter()
437-
.map(|arg| self.eval_fn_call_argument(&arg.node))
458+
.map(|arg| self.eval_fn_call_argument(&arg.node, move_definitely_disjoint))
438459
.collect::<InterpResult<'tcx, Vec<_>>>()?;
439460

440461
let fn_sig_binder = func.layout.ty.fn_sig(*self.tcx);
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
//@revisions: stack tree
2+
//@[tree]compile-flags: -Zmiri-tree-borrows
3+
// Validation forces more things into memory, which we can't have here.
4+
//@compile-flags: -Zmiri-disable-validation
5+
#![feature(custom_mir, core_intrinsics)]
6+
use std::intrinsics::mir::*;
7+
8+
pub struct S(i32);
9+
10+
#[custom_mir(dialect = "runtime", phase = "optimized")]
11+
fn main() {
12+
mir! {
13+
let _unit: ();
14+
{
15+
let staging = S(42); // This forces `staging` into memory...
16+
let non_copy = staging; // ... so we move it to a non-inmemory local here.
17+
// This specifically uses a type with scalar representation to tempt Miri to use the
18+
// efficient way of storing local variables (outside adressable memory).
19+
Call(_unit = callee(Move(non_copy), Move(non_copy)), ReturnTo(after_call), UnwindContinue())
20+
//~[stack]^ ERROR: not granting access
21+
//~[tree]| ERROR: /read access .* forbidden/
22+
}
23+
after_call = {
24+
Return()
25+
}
26+
}
27+
}
28+
29+
pub fn callee(x: S, mut y: S) {
30+
// With the setup above, if `x` and `y` are both moved,
31+
// then writing to `y` will change the value stored in `x`!
32+
y.0 = 0;
33+
assert_eq!(x.0, 42);
34+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
error: Undefined Behavior: not granting access to tag <TAG> because that would remove [Unique for <TAG>] which is strongly protected
2+
--> tests/fail/function_calls/arg_inplace_locals_alias.rs:LL:CC
3+
|
4+
LL | Call(_unit = callee(Move(non_copy), Move(non_copy)), ReturnTo(after_call), UnwindContinue())
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Undefined Behavior occurred here
6+
|
7+
= help: this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental
8+
= help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information
9+
help: <TAG> was created here, as the root tag for ALLOC
10+
--> tests/fail/function_calls/arg_inplace_locals_alias.rs:LL:CC
11+
|
12+
LL | Call(_unit = callee(Move(non_copy), Move(non_copy)), ReturnTo(after_call), UnwindContinue())
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
14+
help: <TAG> is this argument
15+
--> tests/fail/function_calls/arg_inplace_locals_alias.rs:LL:CC
16+
|
17+
LL | y.0 = 0;
18+
| ^^^^^^^
19+
= note: BACKTRACE (of the first span):
20+
= note: inside `main` at tests/fail/function_calls/arg_inplace_locals_alias.rs:LL:CC
21+
22+
note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace
23+
24+
error: aborting due to 1 previous error
25+
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
error: Undefined Behavior: read access through <TAG> (root of the allocation) at ALLOC[0x0] is forbidden
2+
--> tests/fail/function_calls/arg_inplace_locals_alias.rs:LL:CC
3+
|
4+
LL | Call(_unit = callee(Move(non_copy), Move(non_copy)), ReturnTo(after_call), UnwindContinue())
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Undefined Behavior occurred here
6+
|
7+
= help: this indicates a potential bug in the program: it performed an invalid operation, but the Tree Borrows rules it violated are still experimental
8+
= help: the accessed tag <TAG> (root of the allocation) is foreign to the protected tag <TAG> (i.e., it is not a child)
9+
= help: this foreign read access would cause the protected tag <TAG> (currently Active) to become Disabled
10+
= help: protected tags must never be Disabled
11+
help: the accessed tag <TAG> was created here
12+
--> tests/fail/function_calls/arg_inplace_locals_alias.rs:LL:CC
13+
|
14+
LL | Call(_unit = callee(Move(non_copy), Move(non_copy)), ReturnTo(after_call), UnwindContinue())
15+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
16+
help: the protected tag <TAG> was created here, in the initial state Reserved
17+
--> tests/fail/function_calls/arg_inplace_locals_alias.rs:LL:CC
18+
|
19+
LL | y.0 = 0;
20+
| ^^^^^^^
21+
help: the protected tag <TAG> later transitioned to Active due to a child write access at offsets [0x0..0x4]
22+
--> tests/fail/function_calls/arg_inplace_locals_alias.rs:LL:CC
23+
|
24+
LL | y.0 = 0;
25+
| ^^^^^^^
26+
= help: this transition corresponds to the first write to a 2-phase borrowed mutable reference
27+
= note: BACKTRACE (of the first span):
28+
= note: inside `main` at tests/fail/function_calls/arg_inplace_locals_alias.rs:LL:CC
29+
30+
note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace
31+
32+
error: aborting due to 1 previous error
33+

0 commit comments

Comments
 (0)