Skip to content

Commit f4486ee

Browse files
committed
std: make thread::current available in all thread_local! destructors
1 parent 52f3c71 commit f4486ee

File tree

15 files changed

+385
-104
lines changed

15 files changed

+385
-104
lines changed

library/std/src/rt.rs

+25-8
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,11 @@
1919
pub use crate::panicking::{begin_panic, panic_count};
2020
pub use core::panicking::{panic_display, panic_fmt};
2121

22+
use crate::any::Any;
2223
use crate::sync::Once;
2324
use crate::sys;
2425
use crate::thread::{self, Thread};
26+
use crate::{mem, panic};
2527

2628
// Prints to the "panic output", depending on the platform this may be:
2729
// - the standard error output
@@ -64,6 +66,11 @@ macro_rules! rtunwrap {
6466
};
6567
}
6668

69+
fn handle_rt_panic(e: Box<dyn Any + Send>) {
70+
mem::forget(e);
71+
rtabort!("initialization or cleanup bug");
72+
}
73+
6774
// One-time runtime initialization.
6875
// Runs before `main`.
6976
// SAFETY: must be called only once during runtime initialization.
@@ -99,6 +106,20 @@ unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) {
99106
thread::set_current(thread);
100107
}
101108

109+
/// Clean up the thread-local runtime state. This *should* be run after all other
110+
/// code managed by the Rust runtime, but will not cause UB if that condition is
111+
/// not fulfilled. Also note that this function is not guaranteed to be run, but
112+
/// skipping it will cause leaks and therefore is to be avoided.
113+
pub(crate) fn thread_cleanup() {
114+
// This function is run in situations where unwinding leads to an abort
115+
// (think `extern "C"` functions). Abort here instead so that we can
116+
// print a nice message.
117+
panic::catch_unwind(|| {
118+
crate::thread::drop_current();
119+
})
120+
.unwrap_or_else(handle_rt_panic);
121+
}
122+
102123
// One-time runtime cleanup.
103124
// Runs after `main` or at program exit.
104125
// NOTE: this is not guaranteed to run, for example when the program aborts.
@@ -121,11 +142,6 @@ fn lang_start_internal(
121142
argv: *const *const u8,
122143
sigpipe: u8,
123144
) -> Result<isize, !> {
124-
use crate::{mem, panic};
125-
let rt_abort = move |e| {
126-
mem::forget(e);
127-
rtabort!("initialization or cleanup bug");
128-
};
129145
// Guard against the code called by this function from unwinding outside of the Rust-controlled
130146
// code, which is UB. This is a requirement imposed by a combination of how the
131147
// `#[lang="start"]` attribute is implemented as well as by the implementation of the panicking
@@ -137,16 +153,17 @@ fn lang_start_internal(
137153
// prevent std from accidentally introducing a panic to these functions. Another is from
138154
// user code from `main` or, more nefariously, as described in e.g. issue #86030.
139155
// SAFETY: Only called once during runtime initialization.
140-
panic::catch_unwind(move || unsafe { init(argc, argv, sigpipe) }).map_err(rt_abort)?;
156+
panic::catch_unwind(move || unsafe { init(argc, argv, sigpipe) })
157+
.unwrap_or_else(handle_rt_panic);
141158
let ret_code = panic::catch_unwind(move || panic::catch_unwind(main).unwrap_or(101) as isize)
142159
.map_err(move |e| {
143160
mem::forget(e);
144161
rtabort!("drop of the panic payload panicked");
145162
});
146-
panic::catch_unwind(cleanup).map_err(rt_abort)?;
163+
panic::catch_unwind(cleanup).unwrap_or_else(handle_rt_panic);
147164
// Guard against multple threads calling `libc::exit` concurrently.
148165
// See the documentation for `unique_thread_exit` for more information.
149-
panic::catch_unwind(|| crate::sys::exit_guard::unique_thread_exit()).map_err(rt_abort)?;
166+
panic::catch_unwind(crate::sys::exit_guard::unique_thread_exit).unwrap_or_else(handle_rt_panic);
150167
ret_code
151168
}
152169

library/std/src/sys/pal/hermit/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,8 @@ pub unsafe extern "C" fn runtime_entry(
104104
let result = main(argc as isize, argv);
105105

106106
crate::sys::thread_local::destructors::run();
107+
crate::rt::thread_cleanup();
108+
107109
hermit_abi::exit(result);
108110
}
109111

library/std/src/sys/pal/hermit/thread.rs

+1
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ impl Thread {
5050

5151
// run all destructors
5252
crate::sys::thread_local::destructors::run();
53+
crate::rt::thread_cleanup();
5354
}
5455
}
5556
}

library/std/src/sys/thread_local/guard/apple.rs

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ pub fn enable() {
2626
unsafe extern "C" fn run_dtors(_: *mut u8) {
2727
unsafe {
2828
destructors::run();
29+
crate::rt::thread_cleanup();
2930
}
3031
}
3132
}

library/std/src/sys/thread_local/guard/key.rs

+38-1
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
//! that will run all native TLS destructors in the destructor list.
44
55
use crate::ptr;
6-
use crate::sys::thread_local::destructors;
76
use crate::sys::thread_local::key::{set, LazyKey};
87

8+
#[cfg(target_thread_local)]
99
pub fn enable() {
10+
use crate::sys::thread_local::destructors;
11+
1012
static DTORS: LazyKey = LazyKey::new(Some(run));
1113

1214
// Setting the key value to something other than NULL will result in the
@@ -18,6 +20,41 @@ pub fn enable() {
1820
unsafe extern "C" fn run(_: *mut u8) {
1921
unsafe {
2022
destructors::run();
23+
// On platforms with `__cxa_thread_atexit_impl`, `destructors::run`
24+
// does nothing on newer systems as the TLS destructors are
25+
// registered with the system. But because all of those platforms
26+
// call the destructors of TLS keys after the registered ones, this
27+
// function will still be run last (at the time of writing).
28+
crate::rt::thread_cleanup();
29+
}
30+
}
31+
}
32+
33+
/// On platforms with key-based TLS, the system runs the destructors for us.
34+
/// We still have to make sure that [`crate::rt::thread_cleanup`] is called,
35+
/// however. This is done by defering the execution of a TLS destructor to
36+
/// the next round of destruction inside the TLS destructors.
37+
#[cfg(not(target_thread_local))]
38+
pub fn enable() {
39+
const DEFER: *mut u8 = ptr::without_provenance_mut(1);
40+
const RUN: *mut u8 = ptr::without_provenance_mut(2);
41+
42+
static CLEANUP: LazyKey = LazyKey::new(Some(run));
43+
44+
unsafe { set(CLEANUP.force(), DEFER) }
45+
46+
unsafe extern "C" fn run(state: *mut u8) {
47+
if state == DEFER {
48+
// Make sure that this function is run again in the next round of
49+
// TLS destruction. If there is no futher round, there will be leaks,
50+
// but that's okay, `thread_cleanup` is not guaranteed to be called.
51+
unsafe { set(CLEANUP.force(), RUN) }
52+
} else {
53+
debug_assert_eq!(state, RUN);
54+
// If the state is still RUN in the next round of TLS destruction,
55+
// it means that no other TLS destructors defined by this runtime
56+
// have been run, as they would have set the state to DEFER.
57+
crate::rt::thread_cleanup();
2158
}
2259
}
2360
}

library/std/src/sys/thread_local/guard/solid.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ pub fn enable() {
1818
}
1919

2020
unsafe extern "C" fn tls_dtor(_unused: *mut u8) {
21-
unsafe { destructors::run() };
21+
unsafe {
22+
destructors::run();
23+
crate::rt::thread_cleanup();
24+
}
2225
}
2326
}

library/std/src/sys/thread_local/guard/windows.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -92,13 +92,13 @@ unsafe extern "system" fn tls_callback(_h: *mut c_void, dw_reason: u32, _pv: *mu
9292
}
9393

9494
if dw_reason == c::DLL_THREAD_DETACH || dw_reason == c::DLL_PROCESS_DETACH {
95-
#[cfg(target_thread_local)]
9695
unsafe {
96+
#[cfg(target_thread_local)]
9797
super::super::destructors::run();
98-
}
99-
#[cfg(not(target_thread_local))]
100-
unsafe {
98+
#[cfg(not(target_thread_local))]
10199
super::super::key::run_dtors();
100+
101+
crate::rt::thread_cleanup();
102102
}
103103
}
104104
}

library/std/src/sys/thread_local/key/xous.rs

+2
Original file line numberDiff line numberDiff line change
@@ -213,4 +213,6 @@ unsafe fn run_dtors() {
213213
unsafe { cur = (*cur).next };
214214
}
215215
}
216+
217+
crate::rt::thread_cleanup();
216218
}

library/std/src/sys/thread_local/mod.rs

+30-16
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,15 @@ cfg_if::cfg_if! {
3131
))] {
3232
mod statik;
3333
pub use statik::{EagerStorage, LazyStorage, thread_local_inner};
34+
pub(crate) use statik::{LocalPointer, local_pointer};
3435
} else if #[cfg(target_thread_local)] {
3536
mod native;
3637
pub use native::{EagerStorage, LazyStorage, thread_local_inner};
38+
pub(crate) use native::{LocalPointer, local_pointer};
3739
} else {
3840
mod os;
3941
pub use os::{Storage, thread_local_inner};
42+
pub(crate) use os::{LocalPointer, local_pointer};
4043
}
4144
}
4245

@@ -72,36 +75,47 @@ pub(crate) mod destructors {
7275
}
7376

7477
/// This module provides a way to schedule the execution of the destructor list
75-
/// on systems without a per-variable destructor system.
76-
mod guard {
78+
/// and the [runtime cleanup](crate::rt::thread_cleanup) function. Calling [enable]
79+
/// should ensure that these functions are called at the right times.
80+
pub(crate) mod guard {
7781
cfg_if::cfg_if! {
7882
if #[cfg(all(target_thread_local, target_vendor = "apple"))] {
7983
mod apple;
80-
pub(super) use apple::enable;
84+
pub(crate) use apple::enable;
8185
} else if #[cfg(target_os = "windows")] {
8286
mod windows;
83-
pub(super) use windows::enable;
87+
pub(crate) use windows::enable;
8488
} else if #[cfg(any(
85-
all(target_family = "wasm", target_feature = "atomics"),
89+
target_family = "wasm",
90+
target_os = "uefi",
91+
target_os = "zkvm",
8692
))] {
87-
pub(super) fn enable() {
88-
// FIXME: Right now there is no concept of "thread exit", but
89-
// this is likely going to show up at some point in the form of
90-
// an exported symbol that the wasm runtime is going to be
91-
// expected to call. For now we just leak everything, but if
92-
// such a function starts to exist it will probably need to
93+
pub(crate) fn enable() {
94+
// FIXME: Right now there is no concept of "thread exit" on
95+
// wasm, but this is likely going to show up at some point in
96+
// the form of an exported symbol that the wasm runtime is going
97+
// to be expected to call. For now we just leak everything, but
98+
// if such a function starts to exist it will probably need to
9399
// iterate the destructor list with this function:
94100
#[allow(unused)]
101+
#[cfg(not(all(target_family = "wasm", not(target_feature = "atomics"))))]
95102
use super::destructors::run;
103+
#[allow(unused)]
104+
use crate::rt::thread_cleanup;
96105
}
97-
} else if #[cfg(target_os = "hermit")] {
98-
pub(super) fn enable() {}
106+
} else if #[cfg(any(
107+
target_os = "hermit",
108+
target_os = "xous",
109+
))] {
110+
// `std` is the only runtime, so it just calls the destructor functions
111+
// itself when the time comes.
112+
pub(crate) fn enable() {}
99113
} else if #[cfg(target_os = "solid_asp3")] {
100114
mod solid;
101-
pub(super) use solid::enable;
102-
} else if #[cfg(all(target_thread_local, not(target_family = "wasm")))] {
115+
pub(crate) use solid::enable;
116+
} else {
103117
mod key;
104-
pub(super) use key::enable;
118+
pub(crate) use key::enable;
105119
}
106120
}
107121
}

library/std/src/sys/thread_local/native/mod.rs

+31
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@
3232
mod eager;
3333
mod lazy;
3434

35+
use crate::cell::Cell;
36+
use crate::ptr;
37+
3538
pub use eager::Storage as EagerStorage;
3639
pub use lazy::Storage as LazyStorage;
3740

@@ -107,3 +110,31 @@ pub macro thread_local_inner {
107110
$crate::thread::local_impl::thread_local_inner!(@key $t, $($init)*);
108111
},
109112
}
113+
114+
#[rustc_macro_transparency = "semitransparent"]
115+
pub(crate) macro local_pointer {
116+
() => {},
117+
($vis:vis static $name:ident; $($rest:tt)*) => {
118+
#[thread_local]
119+
$vis static $name: $crate::sys::thread_local::LocalPointer = $crate::sys::thread_local::LocalPointer::__new();
120+
$crate::sys::thread_local::local_pointer! { $($rest)* }
121+
},
122+
}
123+
124+
pub(crate) struct LocalPointer {
125+
p: Cell<*mut ()>,
126+
}
127+
128+
impl LocalPointer {
129+
pub const fn __new() -> LocalPointer {
130+
LocalPointer { p: Cell::new(ptr::null_mut()) }
131+
}
132+
133+
pub fn get(&self) -> *mut () {
134+
self.p.get()
135+
}
136+
137+
pub fn set(&self, p: *mut ()) {
138+
self.p.set(p)
139+
}
140+
}

library/std/src/sys/thread_local/os.rs

+32-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
use super::abort_on_dtor_unwind;
2+
use super::guard;
3+
use super::key::{get, set, Key, LazyKey};
24
use crate::cell::Cell;
35
use crate::marker::PhantomData;
46
use crate::ptr;
5-
use crate::sys::thread_local::key::{get, set, Key, LazyKey};
67

78
#[doc(hidden)]
89
#[allow_internal_unstable(thread_local_internals)]
@@ -138,5 +139,35 @@ unsafe extern "C" fn destroy_value<T: 'static>(ptr: *mut u8) {
138139
drop(ptr);
139140
// SAFETY: `key` is the TLS key `ptr` was stored under.
140141
unsafe { set(key, ptr::null_mut()) };
142+
// Make sure that the runtime cleanup will be performed
143+
// after the next round of TLS destruction.
144+
guard::enable();
141145
});
142146
}
147+
148+
#[rustc_macro_transparency = "semitransparent"]
149+
pub(crate) macro local_pointer {
150+
() => {},
151+
($vis:vis static $name:ident; $($rest:tt)*) => {
152+
$vis static $name: $crate::sys::thread_local::LocalPointer = $crate::sys::thread_local::LocalPointer::__new();
153+
$crate::sys::thread_local::local_pointer! { $($rest)* }
154+
},
155+
}
156+
157+
pub(crate) struct LocalPointer {
158+
key: LazyKey,
159+
}
160+
161+
impl LocalPointer {
162+
pub const fn __new() -> LocalPointer {
163+
LocalPointer { key: LazyKey::new(None) }
164+
}
165+
166+
pub fn get(&'static self) -> *mut () {
167+
unsafe { get(self.key.force()) as *mut () }
168+
}
169+
170+
pub fn set(&'static self, p: *mut ()) {
171+
unsafe { set(self.key.force(), p as *mut u8) }
172+
}
173+
}

0 commit comments

Comments
 (0)