1 #![cfg(target_thread_local)]
2 #![unstable(feature = "thread_local_internals", issue = "none")]
4 //! Provides thread-local destructors without an associated "key", which
5 //! can be more efficient.
7 // Since what appears to be glibc 2.18 this symbol has been shipped which
8 // GCC and clang both use to invoke destructors in thread_local globals, so
11 // Note, however, that we run on lots older linuxes, as well as cross
12 // compiling from a newer linux to an older linux, so we also have a
13 // fallback implementation to use as well.
14 #[cfg(any(target_os = "linux", target_os = "fuchsia", target_os = "redox"))]
15 pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) {
17 use crate::sys_common::thread_local_dtor::register_dtor_fallback;
20 #[linkage = "extern_weak"]
21 static __dso_handle: *mut u8;
22 #[linkage = "extern_weak"]
23 static __cxa_thread_atexit_impl: *const libc::c_void;
25 if !__cxa_thread_atexit_impl.is_null() {
26 type F = unsafe extern "C" fn(
27 dtor: unsafe extern "C" fn(*mut u8),
31 mem::transmute::<*const libc::c_void, F>(__cxa_thread_atexit_impl)(
34 &__dso_handle as *const _ as *mut _,
38 register_dtor_fallback(t, dtor);
41 // This implementation is very similar to register_dtor_fallback in
42 // sys_common/thread_local.rs. The main difference is that we want to hook into
43 // macOS's analog of the above linux function, _tlv_atexit. OSX will run the
44 // registered dtors before any TLS slots get freed, and when the main thread
47 // Unfortunately, calling _tlv_atexit while tls dtors are running is UB. The
48 // workaround below is to register, via _tlv_atexit, a custom DTOR list once per
49 // thread. thread_local dtors are pushed to the DTOR list without calling
51 #[cfg(target_os = "macos")]
52 pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) {
53 use crate::cell::Cell;
58 static REGISTERED: Cell<bool> = Cell::new(false);
61 static mut DTORS: Vec<(*mut u8, unsafe extern "C" fn(*mut u8))> = Vec::new();
63 if !REGISTERED.get() {
64 _tlv_atexit(run_dtors, ptr::null_mut());
69 fn _tlv_atexit(dtor: unsafe extern "C" fn(*mut u8), arg: *mut u8);
72 let list = &mut DTORS;
75 unsafe extern "C" fn run_dtors(_: *mut u8) {
76 let mut list = mem::take(&mut DTORS);
77 while !list.is_empty() {
78 for (ptr, dtor) in list {
81 list = mem::take(&mut DTORS);
86 #[cfg(any(target_os = "vxworks", target_os = "horizon", target_os = "emscripten"))]
87 #[cfg_attr(target_family = "wasm", allow(unused))] // might remain unused depending on target details (e.g. wasm32-unknown-emscripten)
88 pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) {
89 use crate::sys_common::thread_local_dtor::register_dtor_fallback;
90 register_dtor_fallback(t, dtor);