Skip to content

Commit 15287f5

Browse files
committed
Auto merge of rust-lang#129313 - RalfJung:coroutine-niches, r=compiler-errors
Supress niches in coroutines to avoid aliasing violations As mentioned [here](rust-lang#63818 (comment)), using niches in fields of coroutines that are referenced by other fields is unsound: the discriminant accesses violate the aliasing requirements of the reference pointing to the relevant field. This issue causes [Miri errors in practice](rust-lang/miri#3780). The "obvious" fix for this is to suppress niches in coroutines. That's what this PR does. However, we have several tests explicitly ensuring that we *do* use niches in coroutines. So I see two options: - We guard this behavior behind a `-Z` flag (that Miri will set by default). There is no known case of these aliasing violations causing miscompilations. But absence of evidence is not evidence of absence... - (What this PR does right now.) We temporarily adjust the coroutine layout logic and the associated tests until the proper fix lands. The "proper fix" here is to wrap fields that other fields can point to in [`UnsafePinned`](rust-lang#125735) and make `UnsafePinned` suppress niches; that would then still permit using niches of *other* fields (those that never get borrowed). However, I know that coroutine sizes are already a problem, so I am not sure if this temporary size regression is acceptable. `@compiler-errors` any opinion? Also who else should be Cc'd here?
2 parents d6c8169 + 12cda6e commit 15287f5

File tree

6 files changed

+102
-27
lines changed

6 files changed

+102
-27
lines changed

Diff for: compiler/rustc_ty_utils/src/layout.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -1001,7 +1001,13 @@ fn coroutine_layout<'tcx>(
10011001
},
10021002
fields: outer_fields,
10031003
abi,
1004-
largest_niche: prefix.largest_niche,
1004+
// Suppress niches inside coroutines. If the niche is inside a field that is aliased (due to
1005+
// self-referentiality), getting the discriminant can cause aliasing violations.
1006+
// `UnsafeCell` blocks niches for the same reason, but we don't yet have `UnsafePinned` that
1007+
// would do the same for us here.
1008+
// See <https://github.com/rust-lang/rust/issues/63818>, <https://github.com/rust-lang/miri/issues/3780>.
1009+
// FIXME: Remove when <https://github.com/rust-lang/rust/issues/125735> is implemented and aliased coroutine fields are wrapped in `UnsafePinned`.
1010+
largest_niche: None,
10051011
size,
10061012
align,
10071013
max_repr_align: None,

Diff for: src/tools/miri/tests/pass/async-niche-aliasing.rs

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
//@revisions: stack tree
2+
//@[tree]compile-flags: -Zmiri-tree-borrows
3+
4+
use std::{
5+
future::Future,
6+
pin::Pin,
7+
sync::Arc,
8+
task::{Context, Poll, Wake},
9+
mem::MaybeUninit,
10+
};
11+
12+
struct ThingAdder<'a> {
13+
// Using `MaybeUninit` to ensure there are no niches here.
14+
thing: MaybeUninit<&'a mut String>,
15+
}
16+
17+
impl Future for ThingAdder<'_> {
18+
type Output = ();
19+
20+
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
21+
unsafe {
22+
**self.get_unchecked_mut().thing.assume_init_mut() += ", world";
23+
}
24+
Poll::Pending
25+
}
26+
}
27+
28+
fn main() {
29+
let mut thing = "hello".to_owned();
30+
// This future has (at least) two fields, a String (`thing`) and a ThingAdder pointing to that string.
31+
let fut = async move { ThingAdder { thing: MaybeUninit::new(&mut thing) }.await };
32+
33+
let mut fut = MaybeDone::Future(fut);
34+
let mut fut = unsafe { Pin::new_unchecked(&mut fut) };
35+
36+
let waker = Arc::new(DummyWaker).into();
37+
let mut ctx = Context::from_waker(&waker);
38+
// This ends up reading the discriminant of the `MaybeDone`. If that is stored inside the
39+
// `thing: String` as a niche optimization, that causes aliasing conflicts with the reference
40+
// stored in `ThingAdder`.
41+
assert_eq!(fut.as_mut().poll(&mut ctx), Poll::Pending);
42+
assert_eq!(fut.as_mut().poll(&mut ctx), Poll::Pending);
43+
}
44+
45+
struct DummyWaker;
46+
47+
impl Wake for DummyWaker {
48+
fn wake(self: Arc<Self>) {}
49+
}
50+
51+
pub enum MaybeDone<F: Future> {
52+
Future(F),
53+
Done,
54+
}
55+
impl<F: Future<Output = ()>> Future for MaybeDone<F> {
56+
type Output = ();
57+
58+
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
59+
unsafe {
60+
match *self.as_mut().get_unchecked_mut() {
61+
MaybeDone::Future(ref mut f) => Pin::new_unchecked(f).poll(cx),
62+
MaybeDone::Done => unreachable!(),
63+
}
64+
}
65+
}
66+
}

Diff for: tests/ui/async-await/async-drop.rs

+14-12
Original file line numberDiff line numberDiff line change
@@ -53,18 +53,20 @@ fn main() {
5353
let i = 13;
5454
let fut = pin!(async {
5555
test_async_drop(Int(0), 0).await;
56-
test_async_drop(AsyncInt(0), 104).await;
57-
test_async_drop([AsyncInt(1), AsyncInt(2)], 152).await;
58-
test_async_drop((AsyncInt(3), AsyncInt(4)), 488).await;
56+
// FIXME(#63818): niches in coroutines are disabled.
57+
// Some of these sizes should be smaller, as indicated in comments.
58+
test_async_drop(AsyncInt(0), /*104*/ 112).await;
59+
test_async_drop([AsyncInt(1), AsyncInt(2)], /*152*/ 168).await;
60+
test_async_drop((AsyncInt(3), AsyncInt(4)), /*488*/ 528).await;
5961
test_async_drop(5, 0).await;
6062
let j = 42;
6163
test_async_drop(&i, 0).await;
6264
test_async_drop(&j, 0).await;
63-
test_async_drop(AsyncStruct { b: AsyncInt(8), a: AsyncInt(7), i: 6 }, 1688).await;
65+
test_async_drop(AsyncStruct { b: AsyncInt(8), a: AsyncInt(7), i: 6 }, /*1688*/ 1792).await;
6466
test_async_drop(ManuallyDrop::new(AsyncInt(9)), 0).await;
6567

6668
let foo = AsyncInt(10);
67-
test_async_drop(AsyncReference { foo: &foo }, 104).await;
69+
test_async_drop(AsyncReference { foo: &foo }, /*104*/ 112).await;
6870

6971
let foo = AsyncInt(11);
7072
test_async_drop(
@@ -73,17 +75,17 @@ fn main() {
7375
let foo = AsyncInt(10);
7476
foo
7577
},
76-
120,
78+
/*120*/ 136,
7779
)
7880
.await;
7981

80-
test_async_drop(AsyncEnum::A(AsyncInt(12)), 680).await;
81-
test_async_drop(AsyncEnum::B(SyncInt(13)), 680).await;
82+
test_async_drop(AsyncEnum::A(AsyncInt(12)), /*680*/ 736).await;
83+
test_async_drop(AsyncEnum::B(SyncInt(13)), /*680*/ 736).await;
8284

83-
test_async_drop(SyncInt(14), 16).await;
85+
test_async_drop(SyncInt(14), /*16*/ 24).await;
8486
test_async_drop(
8587
SyncThenAsync { i: 15, a: AsyncInt(16), b: SyncInt(17), c: AsyncInt(18) },
86-
3064,
88+
/*3064*/ 3296,
8789
)
8890
.await;
8991

@@ -99,11 +101,11 @@ fn main() {
99101
black_box(core::future::ready(())).await;
100102
foo
101103
},
102-
120,
104+
/*120*/ 136,
103105
)
104106
.await;
105107

106-
test_async_drop(AsyncUnion { signed: 21 }, 32).await;
108+
test_async_drop(AsyncUnion { signed: 21 }, /*32*/ 40).await;
107109
});
108110
let res = fut.poll(&mut cx);
109111
assert_eq!(res, Poll::Ready(()));

Diff for: tests/ui/async-await/future-sizes/async-awaiting-fut.stdout

+9-11
Original file line numberDiff line numberDiff line change
@@ -14,28 +14,26 @@ print-type-size field `.value`: 3077 bytes
1414
print-type-size type: `{async fn body of calls_fut<{async fn body of big_fut()}>()}`: 3077 bytes, alignment: 1 bytes
1515
print-type-size discriminant: 1 bytes
1616
print-type-size variant `Unresumed`: 1025 bytes
17-
print-type-size upvar `.fut`: 1025 bytes, offset: 0 bytes, alignment: 1 bytes
17+
print-type-size upvar `.fut`: 1025 bytes
1818
print-type-size variant `Suspend0`: 2052 bytes
19-
print-type-size upvar `.fut`: 1025 bytes, offset: 0 bytes, alignment: 1 bytes
20-
print-type-size padding: 1 bytes
21-
print-type-size local `.fut`: 1025 bytes, alignment: 1 bytes
19+
print-type-size upvar `.fut`: 1025 bytes
20+
print-type-size local `.fut`: 1025 bytes
2221
print-type-size local `..coroutine_field4`: 1 bytes, type: bool
2322
print-type-size local `.__awaitee`: 1 bytes, type: {async fn body of wait()}
2423
print-type-size variant `Suspend1`: 3076 bytes
25-
print-type-size upvar `.fut`: 1025 bytes, offset: 0 bytes, alignment: 1 bytes
26-
print-type-size padding: 1026 bytes
24+
print-type-size upvar `.fut`: 1025 bytes
25+
print-type-size padding: 1025 bytes
2726
print-type-size local `..coroutine_field4`: 1 bytes, alignment: 1 bytes, type: bool
2827
print-type-size local `.__awaitee`: 1025 bytes, type: {async fn body of big_fut()}
2928
print-type-size variant `Suspend2`: 2052 bytes
30-
print-type-size upvar `.fut`: 1025 bytes, offset: 0 bytes, alignment: 1 bytes
31-
print-type-size padding: 1 bytes
32-
print-type-size local `.fut`: 1025 bytes, alignment: 1 bytes
29+
print-type-size upvar `.fut`: 1025 bytes
30+
print-type-size local `.fut`: 1025 bytes
3331
print-type-size local `..coroutine_field4`: 1 bytes, type: bool
3432
print-type-size local `.__awaitee`: 1 bytes, type: {async fn body of wait()}
3533
print-type-size variant `Returned`: 1025 bytes
36-
print-type-size upvar `.fut`: 1025 bytes, offset: 0 bytes, alignment: 1 bytes
34+
print-type-size upvar `.fut`: 1025 bytes
3735
print-type-size variant `Panicked`: 1025 bytes
38-
print-type-size upvar `.fut`: 1025 bytes, offset: 0 bytes, alignment: 1 bytes
36+
print-type-size upvar `.fut`: 1025 bytes
3937
print-type-size type: `std::mem::ManuallyDrop<{async fn body of big_fut()}>`: 1025 bytes, alignment: 1 bytes
4038
print-type-size field `.value`: 1025 bytes
4139
print-type-size type: `std::mem::MaybeUninit<{async fn body of big_fut()}>`: 1025 bytes, alignment: 1 bytes

Diff for: tests/ui/coroutine/discriminant.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -124,12 +124,14 @@ fn main() {
124124
};
125125

126126
assert_eq!(size_of_val(&gen_u8_tiny_niche()), 1);
127-
assert_eq!(size_of_val(&Some(gen_u8_tiny_niche())), 1); // uses niche
127+
// FIXME(#63818): niches in coroutines are disabled.
128+
// assert_eq!(size_of_val(&Some(gen_u8_tiny_niche())), 1); // uses niche
128129
assert_eq!(size_of_val(&Some(Some(gen_u8_tiny_niche()))), 2); // cannot use niche anymore
129130
assert_eq!(size_of_val(&gen_u8_full()), 1);
130131
assert_eq!(size_of_val(&Some(gen_u8_full())), 2); // cannot use niche
131132
assert_eq!(size_of_val(&gen_u16()), 2);
132-
assert_eq!(size_of_val(&Some(gen_u16())), 2); // uses niche
133+
// FIXME(#63818): niches in coroutines are disabled.
134+
// assert_eq!(size_of_val(&Some(gen_u16())), 2); // uses niche
133135

134136
cycle(gen_u8_tiny_niche(), 254);
135137
cycle(gen_u8_full(), 255);

Diff for: tests/ui/coroutine/niche-in-coroutine.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,6 @@ fn main() {
1515
take(x);
1616
};
1717

18-
assert_eq!(size_of_val(&gen1), size_of_val(&Some(gen1)));
18+
// FIXME(#63818): niches in coroutines are disabled. Should be `assert_eq`.
19+
assert_ne!(size_of_val(&gen1), size_of_val(&Some(gen1)));
1920
}

0 commit comments

Comments
 (0)