Skip to content

Commit 50a37ca

Browse files
committed
miri native-call support: all previously exposed provenance is accessible to the callee
1 parent 2f58193 commit 50a37ca

File tree

6 files changed

+92
-33
lines changed

6 files changed

+92
-33
lines changed

Diff for: compiler/rustc_const_eval/src/interpret/memory.rs

+5-10
Original file line numberDiff line numberDiff line change
@@ -955,18 +955,13 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
955955

956956
/// Handle the effect an FFI call might have on the state of allocations.
957957
/// This overapproximates the modifications which external code might make to memory:
958-
/// We set all reachable allocations as initialized, mark all provenances as exposed
958+
/// We set all reachable allocations as initialized, mark all reachable provenances as exposed
959959
/// and overwrite them with `Provenance::WILDCARD`.
960-
pub fn prepare_for_native_call(
961-
&mut self,
962-
id: AllocId,
963-
initial_prov: M::Provenance,
964-
) -> InterpResult<'tcx> {
965-
// Expose provenance of the root allocation.
966-
M::expose_provenance(self, initial_prov)?;
967-
960+
///
961+
/// The allocations in `ids` are assumed to be already exposed.
962+
pub fn prepare_for_native_call(&mut self, ids: Vec<AllocId>) -> InterpResult<'tcx> {
968963
let mut done = FxHashSet::default();
969-
let mut todo = vec![id];
964+
let mut todo = ids;
970965
while let Some(id) = todo.pop() {
971966
if !done.insert(id) {
972967
// We already saw this allocation before, don't process it again.

Diff for: src/tools/miri/src/alloc_addresses/mod.rs

+24-1
Original file line numberDiff line numberDiff line change
@@ -285,9 +285,19 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
285285

286286
impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
287287
pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
288-
fn expose_ptr(&self, alloc_id: AllocId, tag: BorTag) -> InterpResult<'tcx> {
288+
fn expose_provenance(&self, provenance: Provenance) -> InterpResult<'tcx> {
289289
let this = self.eval_context_ref();
290290
let mut global_state = this.machine.alloc_addresses.borrow_mut();
291+
292+
let (alloc_id, tag) = match provenance {
293+
Provenance::Concrete { alloc_id, tag } => (alloc_id, tag),
294+
Provenance::Wildcard => {
295+
// No need to do anything for wildcard pointers as
296+
// their provenances have already been previously exposed.
297+
return interp_ok(());
298+
}
299+
};
300+
291301
// In strict mode, we don't need this, so we can save some cycles by not tracking it.
292302
if global_state.provenance_mode == ProvenanceMode::Strict {
293303
return interp_ok(());
@@ -422,6 +432,19 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
422432
let rel_offset = this.truncate_to_target_usize(addr.bytes().wrapping_sub(base_addr));
423433
Some((alloc_id, Size::from_bytes(rel_offset)))
424434
}
435+
436+
/// Prepare all exposed memory for a native call.
437+
/// This overapproximates the modifications which external code might make to memory:
438+
/// We set all reachable allocations as initialized, mark all reachable provenances as exposed
439+
/// and overwrite them with `Provenance::WILDCARD`.
440+
fn prepare_exposed_for_native_call(&mut self) -> InterpResult<'tcx> {
441+
let this = self.eval_context_mut();
442+
// We need to make a deep copy of this list, but it's fine; it also serves as scratch space
443+
// for the search within `prepare_for_native_call`.
444+
let exposed: Vec<AllocId> =
445+
this.machine.alloc_addresses.get_mut().exposed.iter().copied().collect();
446+
this.prepare_for_native_call(exposed)
447+
}
425448
}
426449

427450
impl<'tcx> MiriMachine<'tcx> {

Diff for: src/tools/miri/src/machine.rs

+2-8
Original file line numberDiff line numberDiff line change
@@ -1291,18 +1291,12 @@ impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> {
12911291
/// Called on `ptr as usize` casts.
12921292
/// (Actually computing the resulting `usize` doesn't need machine help,
12931293
/// that's just `Scalar::try_to_int`.)
1294+
#[inline(always)]
12941295
fn expose_provenance(
12951296
ecx: &InterpCx<'tcx, Self>,
12961297
provenance: Self::Provenance,
12971298
) -> InterpResult<'tcx> {
1298-
match provenance {
1299-
Provenance::Concrete { alloc_id, tag } => ecx.expose_ptr(alloc_id, tag),
1300-
Provenance::Wildcard => {
1301-
// No need to do anything for wildcard pointers as
1302-
// their provenances have already been previously exposed.
1303-
interp_ok(())
1304-
}
1305-
}
1299+
ecx.expose_provenance(provenance)
13061300
}
13071301

13081302
/// Convert a pointer with provenance into an allocation-offset pair and extra provenance info.

Diff for: src/tools/miri/src/shims/native_lib.rs

+6-10
Original file line numberDiff line numberDiff line change
@@ -160,16 +160,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
160160
}
161161
let imm = this.read_immediate(arg)?;
162162
libffi_args.push(imm_to_carg(&imm, this)?);
163-
// If we are passing a pointer, prepare the memory it points to.
163+
// If we are passing a pointer, expose its provenance. Below, all exposed memory
164+
// (previously exposed and new exposed) will then be properly prepared.
164165
if matches!(arg.layout.ty.kind(), ty::RawPtr(..)) {
165166
let ptr = imm.to_scalar().to_pointer(this)?;
166167
let Some(prov) = ptr.provenance else {
167-
// Pointer without provenance may not access any memory.
168-
continue;
169-
};
170-
// We use `get_alloc_id` for its best-effort behaviour with Wildcard provenance.
171-
let Some(alloc_id) = prov.get_alloc_id() else {
172-
// Wildcard pointer, whatever it points to must be already exposed.
168+
// Pointer without provenance may not access any memory anyway, skip.
173169
continue;
174170
};
175171
// The first time this happens, print a warning.
@@ -178,12 +174,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
178174
this.emit_diagnostic(NonHaltingDiagnostic::NativeCallSharedMem);
179175
}
180176

181-
this.prepare_for_native_call(alloc_id, prov)?;
177+
this.expose_provenance(prov)?;
182178
}
183179
}
184180

185-
// FIXME: In the future, we should also call `prepare_for_native_call` on all previously
186-
// exposed allocations, since C may access any of them.
181+
// Prepare all exposed memory.
182+
this.prepare_exposed_for_native_call()?;
187183

188184
// Convert them to `libffi::high::Arg` type.
189185
let libffi_args = libffi_args

Diff for: src/tools/miri/tests/native-lib/pass/ptr_write_access.rs

+36-4
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
#![feature(box_as_ptr)]
77

88
use std::mem::MaybeUninit;
9-
use std::ptr::null;
9+
use std::ptr;
1010

1111
fn main() {
1212
test_increment_int();
@@ -20,6 +20,8 @@ fn main() {
2020
test_pass_dangling();
2121
test_swap_ptr_triple_dangling();
2222
test_return_ptr();
23+
test_pass_ptr_as_int();
24+
test_pass_ptr_via_previously_shared_mem();
2325
}
2426

2527
/// Test function that modifies an int.
@@ -112,7 +114,7 @@ fn test_swap_ptr() {
112114
}
113115

114116
let x = 61;
115-
let (mut ptr0, mut ptr1) = (&raw const x, null());
117+
let (mut ptr0, mut ptr1) = (&raw const x, ptr::null());
116118

117119
unsafe { swap_ptr(&mut ptr0, &mut ptr1) };
118120
assert_eq!(unsafe { *ptr1 }, x);
@@ -131,7 +133,7 @@ fn test_swap_ptr_tuple() {
131133
}
132134

133135
let x = 71;
134-
let mut tuple = Tuple { ptr0: &raw const x, ptr1: null() };
136+
let mut tuple = Tuple { ptr0: &raw const x, ptr1: ptr::null() };
135137

136138
unsafe { swap_ptr_tuple(&mut tuple) }
137139
assert_eq!(unsafe { *tuple.ptr1 }, x);
@@ -148,7 +150,7 @@ fn test_overwrite_dangling() {
148150
drop(b);
149151

150152
unsafe { overwrite_ptr(&mut ptr) };
151-
assert_eq!(ptr, null());
153+
assert_eq!(ptr, ptr::null());
152154
}
153155

154156
/// Test function that passes a dangling pointer.
@@ -200,3 +202,33 @@ fn test_return_ptr() {
200202
let ptr = unsafe { return_ptr(ptr) };
201203
assert_eq!(unsafe { *ptr }, x);
202204
}
205+
206+
/// Test casting a pointer to an integer and passing that to C.
207+
fn test_pass_ptr_as_int() {
208+
extern "C" {
209+
fn pass_ptr_as_int(ptr: usize, set_to_val: i32);
210+
}
211+
212+
let mut m: MaybeUninit<i32> = MaybeUninit::uninit();
213+
unsafe { pass_ptr_as_int(m.as_mut_ptr() as usize, 42) };
214+
assert_eq!(unsafe { m.assume_init() }, 42);
215+
}
216+
217+
fn test_pass_ptr_via_previously_shared_mem() {
218+
extern "C" {
219+
fn set_shared_mem(ptr: *mut *mut i32);
220+
fn init_ptr_stored_in_shared_mem(val: i32);
221+
}
222+
223+
let mut m: *mut i32 = ptr::null_mut();
224+
let ptr_to_m = &raw mut m;
225+
unsafe { set_shared_mem(&raw mut m) };
226+
227+
let mut m2: MaybeUninit<i32> = MaybeUninit::uninit();
228+
// Store a pointer to m2 somewhere that C code can access it.
229+
unsafe { ptr_to_m.write(m2.as_mut_ptr()) };
230+
// Have C code write there.
231+
unsafe { init_ptr_stored_in_shared_mem(42) };
232+
// Ensure this memory is now considered initialized.
233+
assert_eq!(unsafe { m2.assume_init() }, 42);
234+
}

Diff for: src/tools/miri/tests/native-lib/ptr_write_access.c

+19
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include <stddef.h>
2+
#include <stdint.h>
23

34
// See comments in build_native_lib()
45
#define EXPORT __attribute__((visibility("default")))
@@ -88,3 +89,21 @@ EXPORT void swap_ptr_triple_dangling(Triple *t_ptr) {
8889
EXPORT const int *return_ptr(const int *ptr) {
8990
return ptr;
9091
}
92+
93+
/* Test: test_pass_ptr_as_int */
94+
95+
EXPORT void pass_ptr_as_int(uintptr_t ptr, int set_to_val) {
96+
*(int*)ptr = set_to_val;
97+
}
98+
99+
/* Test: test_pass_ptr_via_previously_shared_mem */
100+
101+
int** shared_place;
102+
103+
EXPORT void set_shared_mem(int** ptr) {
104+
shared_place = ptr;
105+
}
106+
107+
EXPORT void init_ptr_stored_in_shared_mem(int val) {
108+
**shared_place = val;
109+
}

0 commit comments

Comments
 (0)