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 = "redox",
14 target_os = "emscripten"))]
15 pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
17 use crate::sys_common::thread_local::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 fn(dtor: unsafe extern fn(*mut u8),
28 dso_handle: *mut u8) -> libc::c_int;
29 mem::transmute::<*const libc::c_void, F>(__cxa_thread_atexit_impl)
30 (dtor, t, &__dso_handle as *const _ as *mut _);
33 register_dtor_fallback(t, dtor);
36 // This implementation is very similar to register_dtor_fallback in
37 // sys_common/thread_local.rs. The main difference is that we want to hook into
38 // macOS's analog of the above linux function, _tlv_atexit. OSX will run the
39 // registered dtors before any TLS slots get freed, and when the main thread
42 // Unfortunately, calling _tlv_atexit while tls dtors are running is UB. The
43 // workaround below is to register, via _tlv_atexit, a custom DTOR list once per
44 // thread. thread_local dtors are pushed to the DTOR list without calling
46 #[cfg(target_os = "macos")]
47 pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
48 use crate::cell::Cell;
52 static REGISTERED: Cell<bool> = Cell::new(false);
53 if !REGISTERED.get() {
54 _tlv_atexit(run_dtors, ptr::null_mut());
58 type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>;
61 static DTORS: Cell<*mut List> = Cell::new(ptr::null_mut());
62 if DTORS.get().is_null() {
63 let v: Box<List> = box Vec::new();
64 DTORS.set(Box::into_raw(v));
68 fn _tlv_atexit(dtor: unsafe extern fn(*mut u8),
72 let list: &mut List = &mut *DTORS.get();
75 unsafe extern fn run_dtors(_: *mut u8) {
76 let mut ptr = DTORS.replace(ptr::null_mut());
77 while !ptr.is_null() {
78 let list = Box::from_raw(ptr);
79 for (ptr, dtor) in list.into_iter() {
82 ptr = DTORS.replace(ptr::null_mut());