1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![cfg(target_thread_local)]
12 #![unstable(feature = "thread_local_internals", issue = "0")]
14 use cell::{Cell, UnsafeCell};
20 inner: UnsafeCell<Option<T>>,
22 // Metadata to keep track of the state of the destructor. Remember that
23 // these variables are thread-local, not global.
24 dtor_registered: Cell<bool>,
25 dtor_running: Cell<bool>,
28 impl<T> fmt::Debug for Key<T> {
29 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34 unsafe impl<T> ::marker::Sync for Key<T> { }
37 pub const fn new() -> Key<T> {
39 inner: UnsafeCell::new(None),
40 dtor_registered: Cell::new(false),
41 dtor_running: Cell::new(false)
45 pub fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> {
47 if intrinsics::needs_drop::<T>() && self.dtor_running.get() {
55 unsafe fn register_dtor(&self) {
56 if !intrinsics::needs_drop::<T>() || self.dtor_registered.get() {
60 register_dtor(self as *const _ as *mut u8,
62 self.dtor_registered.set(true);
66 #[cfg(any(target_os = "linux", target_os = "fuchsia"))]
67 unsafe fn register_dtor_fallback(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
68 // The fallback implementation uses a vanilla OS-based TLS key to track
69 // the list of destructors that need to be run for this thread. The key
70 // then has its own destructor which runs all the other destructors.
72 // The destructor for DTORS is a little special in that it has a `while`
73 // loop to continuously drain the list of registered destructors. It
74 // *should* be the case that this loop always terminates because we
75 // provide the guarantee that a TLS key cannot be set after it is
76 // flagged for destruction.
77 use sys_common::thread_local as os;
79 static DTORS: os::StaticKey = os::StaticKey::new(Some(run_dtors));
80 type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>;
81 if DTORS.get().is_null() {
82 let v: Box<List> = box Vec::new();
83 DTORS.set(Box::into_raw(v) as *mut u8);
85 let list: &mut List = &mut *(DTORS.get() as *mut List);
88 unsafe extern fn run_dtors(mut ptr: *mut u8) {
89 while !ptr.is_null() {
90 let list: Box<List> = Box::from_raw(ptr as *mut List);
91 for &(ptr, dtor) in list.iter() {
95 DTORS.set(ptr::null_mut());
100 // Since what appears to be glibc 2.18 this symbol has been shipped which
101 // GCC and clang both use to invoke destructors in thread_local globals, so
102 // let's do the same!
104 // Note, however, that we run on lots older linuxes, as well as cross
105 // compiling from a newer linux to an older linux, so we also have a
106 // fallback implementation to use as well.
108 // Due to rust-lang/rust#18804, make sure this is not generic!
109 #[cfg(target_os = "linux")]
110 unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
115 #[linkage = "extern_weak"]
116 static __dso_handle: *mut u8;
117 #[linkage = "extern_weak"]
118 static __cxa_thread_atexit_impl: *const libc::c_void;
120 if !__cxa_thread_atexit_impl.is_null() {
121 type F = unsafe extern fn(dtor: unsafe extern fn(*mut u8),
123 dso_handle: *mut u8) -> libc::c_int;
124 mem::transmute::<*const libc::c_void, F>(__cxa_thread_atexit_impl)
125 (dtor, t, &__dso_handle as *const _ as *mut _);
128 register_dtor_fallback(t, dtor);
131 // macOS's analog of the above linux function is this _tlv_atexit function.
132 // The disassembly of thread_local globals in C++ (at least produced by
133 // clang) will have this show up in the output.
134 #[cfg(target_os = "macos")]
135 unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
137 fn _tlv_atexit(dtor: unsafe extern fn(*mut u8),
140 _tlv_atexit(dtor, t);
143 // Just use the thread_local fallback implementation, at least until there's
144 // a more direct implementation.
145 #[cfg(target_os = "fuchsia")]
146 unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
147 register_dtor_fallback(t, dtor);
150 pub unsafe extern fn destroy_value<T>(ptr: *mut u8) {
151 let ptr = ptr as *mut Key<T>;
152 // Right before we run the user destructor be sure to flag the
153 // destructor as running for this thread so calls to `get` will return
155 (*ptr).dtor_running.set(true);
157 // The macOS implementation of TLS apparently had an odd aspect to it
158 // where the pointer we have may be overwritten while this destructor
159 // is running. Specifically if a TLS destructor re-accesses TLS it may
160 // trigger a re-initialization of all TLS variables, paving over at
161 // least some destroyed ones with initial values.
163 // This means that if we drop a TLS value in place on macOS that we could
164 // revert the value to its original state halfway through the
165 // destructor, which would be bad!
167 // Hence, we use `ptr::read` on macOS (to move to a "safe" location)
168 // instead of drop_in_place.
169 if cfg!(target_os = "macos") {
170 ptr::read((*ptr).inner.get());
172 ptr::drop_in_place((*ptr).inner.get());