Skip to content

Commit 04f835f

Browse files
committed
Ensure copy* intrinsics also perform the static self-init checks
1 parent 1d26f9a commit 04f835f

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

compiler/rustc_const_eval/src/interpret/memory.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1412,6 +1412,12 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
14121412
let src_alloc = self.get_alloc_raw(src_alloc_id)?;
14131413
let src_range = alloc_range(src_offset, size);
14141414
assert!(!self.memory.validation_in_progress.get(), "we can't be copying during validation");
1415+
1416+
// Do our own "do not read from static items while initializing them" checks
1417+
if let Ok((alloc_id, ..)) = self.ptr_try_get_alloc_id(src, size.bytes() as i64) {
1418+
M::before_alloc_read(self, alloc_id)?;
1419+
}
1420+
14151421
// For the overlapping case, it is crucial that we trigger the read hook
14161422
// before the write hook -- the aliasing model cares about the order.
14171423
M::before_memory_read(

tests/ui/statics/read_before_init.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
1-
//@ check-pass
1+
//! This test checks the one code path that does not go through
2+
//! the regular CTFE memory access (as an optimization). We forgot
3+
//! to duplicate the static item self-initialization check, allowing
4+
//! reading from the uninitialized static memory before it was
5+
//! initialized at the end of the static initializer.
6+
//!
7+
//! https://github.com/rust-lang/rust/issues/142532
28
39
use std::mem::MaybeUninit;
410

511
pub static X: (i32, MaybeUninit<i32>) = (1, foo(&X.0));
12+
//~^ ERROR: encountered static that tried to initialize itself with itself
613

714
const fn foo(x: &i32) -> MaybeUninit<i32> {
815
let mut temp = MaybeUninit::<i32>::uninit();
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
error[E0080]: encountered static that tried to initialize itself with itself
2+
--> $DIR/read_before_init.rs:11:45
3+
|
4+
LL | pub static X: (i32, MaybeUninit<i32>) = (1, foo(&X.0));
5+
| ^^^^^^^^^ evaluation of `X` failed inside this call
6+
|
7+
note: inside `foo`
8+
--> $DIR/read_before_init.rs:17:9
9+
|
10+
LL | std::ptr::copy(x, temp.as_mut_ptr(), 1);
11+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
12+
note: inside `std::ptr::copy::<i32>`
13+
--> $SRC_DIR/core/src/ptr/mod.rs:LL:COL
14+
15+
error: aborting due to 1 previous error
16+
17+
For more information about this error, try `rustc --explain E0080`.

0 commit comments

Comments
 (0)