Skip to content

Commit af44cdf

Browse files
committed
Disallow statics initializing themselves
1 parent 2b25c0c commit af44cdf

File tree

3 files changed

+37
-3
lines changed

3 files changed

+37
-3
lines changed

src/librustc_mir/interpret/memory.rs

+10-1
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,16 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
400400

401401
// We can still be zero-sized in this branch, in which case we have to
402402
// return `None`.
403-
if size.bytes() == 0 { None } else { Some(ptr) }
403+
if size.bytes() == 0 {
404+
// We may be reading from a static.
405+
// In order to ensure that `static FOO: Type = FOO;` causes a cycle error
406+
// instead of magically pulling *any* ZST value from the ether, we need to
407+
// trigger a read here.
408+
self.get_raw(ptr.alloc_id)?;
409+
None
410+
} else {
411+
Some(ptr)
412+
}
404413
}
405414
})
406415
}

src/test/ui/consts/recursive-zst-static.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1-
// build-pass
1+
// This test ensures that we do not allow ZST statics to initialize themselves without ever
2+
// actually creating a value of that type. This is important, as the ZST may have private fields
3+
// that users can reasonably expect to only get initialized by their own code. Thus unsafe code
4+
// can depend on this fact and will thus do unsound things when it is violated.
5+
// See https://github.com/rust-lang/rust/issues/71078 for more details.
26

3-
static FOO: () = FOO;
7+
static FOO: () = FOO; //~ cycle detected when const-evaluating `FOO`
48

59
fn main() {
610
FOO
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
error[E0391]: cycle detected when const-evaluating `FOO`
2+
--> $DIR/recursive-zst-static.rs:7:18
3+
|
4+
LL | static FOO: () = FOO;
5+
| ^^^
6+
|
7+
note: ...which requires const-evaluating `FOO`...
8+
--> $DIR/recursive-zst-static.rs:7:1
9+
|
10+
LL | static FOO: () = FOO;
11+
| ^^^^^^^^^^^^^^^^^^^^^
12+
= note: ...which again requires const-evaluating `FOO`, completing the cycle
13+
note: cycle used when const-evaluating + checking `FOO`
14+
--> $DIR/recursive-zst-static.rs:7:1
15+
|
16+
LL | static FOO: () = FOO;
17+
| ^^^^^^^^^^^^^^^^^^^^^
18+
19+
error: aborting due to previous error
20+
21+
For more information about this error, try `rustc --explain E0391`.

0 commit comments

Comments
 (0)