1 #![cfg(target_thread_local)]
2 #![unstable(feature = "thread_local_internals", issue = "0")]
4 // Since what appears to be glibc 2.18 this symbol has been shipped which
5 // GCC and clang both use to invoke destructors in thread_local globals, so
8 // Note, however, that we run on lots older linuxes, as well as cross
9 // compiling from a newer linux to an older linux, so we also have a
10 // fallback implementation to use as well.
12 // Due to rust-lang/rust#18804, make sure this is not generic!
13 #[cfg(any(target_os = "linux", target_os = "fuchsia", target_os = "hermit", target_os = "redox"))]
14 pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
16 use crate::sys_common::thread_local::register_dtor_fallback;
19 #[linkage = "extern_weak"]
20 static __dso_handle: *mut u8;
21 #[linkage = "extern_weak"]
22 static __cxa_thread_atexit_impl: *const libc::c_void;
24 if !__cxa_thread_atexit_impl.is_null() {
25 type F = unsafe extern fn(dtor: unsafe extern fn(*mut u8),
27 dso_handle: *mut u8) -> libc::c_int;
28 mem::transmute::<*const libc::c_void, F>(__cxa_thread_atexit_impl)
29 (dtor, t, &__dso_handle as *const _ as *mut _);
32 register_dtor_fallback(t, dtor);
35 // This implementation is very similar to register_dtor_fallback in
36 // sys_common/thread_local.rs. The main difference is that we want to hook into
37 // macOS's analog of the above linux function, _tlv_atexit. OSX will run the
38 // registered dtors before any TLS slots get freed, and when the main thread
41 // Unfortunately, calling _tlv_atexit while tls dtors are running is UB. The
42 // workaround below is to register, via _tlv_atexit, a custom DTOR list once per
43 // thread. thread_local dtors are pushed to the DTOR list without calling
45 #[cfg(target_os = "macos")]
46 pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
47 use crate::cell::Cell;
51 static REGISTERED: Cell<bool> = Cell::new(false);
52 if !REGISTERED.get() {
53 _tlv_atexit(run_dtors, ptr::null_mut());
57 type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>;
60 static DTORS: Cell<*mut List> = Cell::new(ptr::null_mut());
61 if DTORS.get().is_null() {
62 let v: Box<List> = box Vec::new();
63 DTORS.set(Box::into_raw(v));
67 fn _tlv_atexit(dtor: unsafe extern fn(*mut u8),
71 let list: &mut List = &mut *DTORS.get();
74 unsafe extern fn run_dtors(_: *mut u8) {
75 let mut ptr = DTORS.replace(ptr::null_mut());
76 while !ptr.is_null() {
77 let list = Box::from_raw(ptr);
78 for (ptr, dtor) in list.into_iter() {
81 ptr = DTORS.replace(ptr::null_mut());