Skip to content

Commit 5d9eeff

Browse files
committed
Ensure TLS destructors run before thread joins in SGX
1 parent 6df26f8 commit 5d9eeff

File tree

3 files changed

+119
-11
lines changed

3 files changed

+119
-11
lines changed

library/std/src/sys/sgx/abi/mod.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,12 @@ unsafe extern "C" fn tcs_init(secondary: bool) {
6262
extern "C" fn entry(p1: u64, p2: u64, p3: u64, secondary: bool, p4: u64, p5: u64) -> EntryReturn {
6363
// FIXME: how to support TLS in library mode?
6464
let tls = Box::new(tls::Tls::new());
65-
let _tls_guard = unsafe { tls.activate() };
65+
let tls_guard = unsafe { tls.activate() };
6666

6767
if secondary {
68-
super::thread::Thread::entry();
68+
let join_notifier = super::thread::Thread::entry();
69+
drop(tls_guard);
70+
drop(join_notifier);
6971

7072
EntryReturn(0, 0)
7173
} else {

library/std/src/sys/sgx/thread.rs

+61-8
Original file line numberDiff line numberDiff line change
@@ -9,26 +9,37 @@ pub struct Thread(task_queue::JoinHandle);
99

1010
pub const DEFAULT_MIN_STACK_SIZE: usize = 4096;
1111

12+
pub use self::task_queue::JoinNotifier;
13+
1214
mod task_queue {
13-
use crate::sync::mpsc;
15+
use super::wait_notify;
1416
use crate::sync::{Mutex, MutexGuard, Once};
1517

16-
pub type JoinHandle = mpsc::Receiver<()>;
18+
pub type JoinHandle = wait_notify::Waiter;
19+
20+
pub struct JoinNotifier(Option<wait_notify::Notifier>);
21+
22+
impl Drop for JoinNotifier {
23+
fn drop(&mut self) {
24+
self.0.take().unwrap().notify();
25+
}
26+
}
1727

1828
pub(super) struct Task {
1929
p: Box<dyn FnOnce()>,
20-
done: mpsc::Sender<()>,
30+
done: JoinNotifier,
2131
}
2232

2333
impl Task {
2434
pub(super) fn new(p: Box<dyn FnOnce()>) -> (Task, JoinHandle) {
25-
let (done, recv) = mpsc::channel();
35+
let (done, recv) = wait_notify::new();
36+
let done = JoinNotifier(Some(done));
2637
(Task { p, done }, recv)
2738
}
2839

29-
pub(super) fn run(self) {
40+
pub(super) fn run(self) -> JoinNotifier {
3041
(self.p)();
31-
let _ = self.done.send(());
42+
self.done
3243
}
3344
}
3445

@@ -47,6 +58,48 @@ mod task_queue {
4758
}
4859
}
4960

61+
/// This module provides a synchronization primitive that does not use thread
62+
/// local variables. This is needed for signaling that a thread has finished
63+
/// execution. The signal is sent once all TLS destructors have finished at
64+
/// which point no new thread locals should be created.
65+
pub mod wait_notify {
66+
use super::super::waitqueue::{SpinMutex, WaitQueue, WaitVariable};
67+
use crate::sync::Arc;
68+
69+
pub struct Notifier(Arc<SpinMutex<WaitVariable<bool>>>);
70+
71+
impl Notifier {
72+
/// Notify the waiter. The waiter is either notified right away (if
73+
/// currently blocked in `Waiter::wait()`) or later when it calls the
74+
/// `Waiter::wait()` method.
75+
pub fn notify(self) {
76+
let mut guard = self.0.lock();
77+
*guard.lock_var_mut() = true;
78+
let _ = WaitQueue::notify_one(guard);
79+
}
80+
}
81+
82+
pub struct Waiter(Arc<SpinMutex<WaitVariable<bool>>>);
83+
84+
impl Waiter {
85+
/// Wait for a notification. If `Notifier::notify()` has already been
86+
/// called, this will return immediately, otherwise the current thread
87+
/// is blocked until notified.
88+
pub fn wait(self) {
89+
let guard = self.0.lock();
90+
if *guard.lock_var() {
91+
return;
92+
}
93+
WaitQueue::wait(guard, || {});
94+
}
95+
}
96+
97+
pub fn new() -> (Notifier, Waiter) {
98+
let inner = Arc::new(SpinMutex::new(WaitVariable::new(false)));
99+
(Notifier(inner.clone()), Waiter(inner))
100+
}
101+
}
102+
50103
impl Thread {
51104
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
52105
pub unsafe fn new(_stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
@@ -57,7 +110,7 @@ impl Thread {
57110
Ok(Thread(handle))
58111
}
59112

60-
pub(super) fn entry() {
113+
pub(super) fn entry() -> JoinNotifier {
61114
let mut pending_tasks = task_queue::lock();
62115
let task = rtunwrap!(Some, pending_tasks.pop());
63116
drop(pending_tasks); // make sure to not hold the task queue lock longer than necessary
@@ -78,7 +131,7 @@ impl Thread {
78131
}
79132

80133
pub fn join(self) {
81-
let _ = self.0.recv();
134+
self.0.wait();
82135
}
83136
}
84137

library/std/src/thread/local/tests.rs

+54-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use crate::cell::{Cell, UnsafeCell};
2-
use crate::sync::mpsc::{channel, Sender};
2+
use crate::sync::atomic::{AtomicBool, Ordering};
3+
use crate::sync::mpsc::{self, channel, Sender};
34
use crate::thread::{self, LocalKey};
45
use crate::thread_local;
56

@@ -207,3 +208,55 @@ fn dtors_in_dtors_in_dtors_const_init() {
207208
});
208209
rx.recv().unwrap();
209210
}
211+
212+
// This test tests that TLS destructors have run before the thread joins. The
213+
// test has no false positives (meaning: if the test fails, there's actually
214+
// an ordering problem). It may have false negatives, where the test passes but
215+
// join is not guaranteed to be after the TLS destructors. However, false
216+
// negatives should be exceedingly rare due to judicious use of
217+
// thread::yield_now and running the test several times.
218+
#[test]
219+
fn join_orders_after_tls_destructors() {
220+
static THREAD2_LAUNCHED: AtomicBool = AtomicBool::new(false);
221+
222+
for _ in 0..10 {
223+
let (tx, rx) = mpsc::sync_channel(0);
224+
THREAD2_LAUNCHED.store(false, Ordering::SeqCst);
225+
226+
let jh = thread::spawn(move || {
227+
struct RecvOnDrop(Cell<Option<mpsc::Receiver<()>>>);
228+
229+
impl Drop for RecvOnDrop {
230+
fn drop(&mut self) {
231+
let rx = self.0.take().unwrap();
232+
while !THREAD2_LAUNCHED.load(Ordering::SeqCst) {
233+
thread::yield_now();
234+
}
235+
rx.recv().unwrap();
236+
}
237+
}
238+
239+
thread_local! {
240+
static TL_RX: RecvOnDrop = RecvOnDrop(Cell::new(None));
241+
}
242+
243+
TL_RX.with(|v| v.0.set(Some(rx)))
244+
});
245+
246+
let tx_clone = tx.clone();
247+
let jh2 = thread::spawn(move || {
248+
THREAD2_LAUNCHED.store(true, Ordering::SeqCst);
249+
jh.join().unwrap();
250+
tx_clone.send(()).expect_err(
251+
"Expecting channel to be closed because thread 1 TLS destructors must've run",
252+
);
253+
});
254+
255+
while !THREAD2_LAUNCHED.load(Ordering::SeqCst) {
256+
thread::yield_now();
257+
}
258+
thread::yield_now();
259+
tx.send(()).expect("Expecting channel to be live because thread 2 must block on join");
260+
jh2.join().unwrap();
261+
}
262+
}

0 commit comments

Comments
 (0)