]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fast_thread_local.rs
Rollup merge of #40521 - TimNN:panic-free-shift, r=alexcrichton
[rust.git] / src / libstd / sys / unix / fast_thread_local.rs
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.
4 //
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.
10
11 #![cfg(target_thread_local)]
12 #![unstable(feature = "thread_local_internals", issue = "0")]
13
14 use cell::{Cell, UnsafeCell};
15 use fmt;
16 use intrinsics;
17 use ptr;
18
19 pub struct Key<T> {
20     inner: UnsafeCell<Option<T>>,
21
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>,
26 }
27
28 impl<T> fmt::Debug for Key<T> {
29     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
30         f.pad("Key { .. }")
31     }
32 }
33
34 unsafe impl<T> ::marker::Sync for Key<T> { }
35
36 impl<T> Key<T> {
37     pub const fn new() -> Key<T> {
38         Key {
39             inner: UnsafeCell::new(None),
40             dtor_registered: Cell::new(false),
41             dtor_running: Cell::new(false)
42         }
43     }
44
45     pub fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> {
46         unsafe {
47             if intrinsics::needs_drop::<T>() && self.dtor_running.get() {
48                 return None
49             }
50             self.register_dtor();
51         }
52         Some(&self.inner)
53     }
54
55     unsafe fn register_dtor(&self) {
56         if !intrinsics::needs_drop::<T>() || self.dtor_registered.get() {
57             return
58         }
59
60         register_dtor(self as *const _ as *mut u8,
61                       destroy_value::<T>);
62         self.dtor_registered.set(true);
63     }
64 }
65
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.
71     //
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;
78
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);
84     }
85     let list: &mut List = &mut *(DTORS.get() as *mut List);
86     list.push((t, dtor));
87
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() {
92                 dtor(ptr);
93             }
94             ptr = DTORS.get();
95             DTORS.set(ptr::null_mut());
96         }
97     }
98 }
99
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!
103 //
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.
107 //
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)) {
111     use mem;
112     use libc;
113
114     extern {
115         #[linkage = "extern_weak"]
116         static __dso_handle: *mut u8;
117         #[linkage = "extern_weak"]
118         static __cxa_thread_atexit_impl: *const libc::c_void;
119     }
120     if !__cxa_thread_atexit_impl.is_null() {
121         type F = unsafe extern fn(dtor: unsafe extern fn(*mut u8),
122                                   arg: *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 _);
126         return
127     }
128     register_dtor_fallback(t, dtor);
129 }
130
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)) {
136     extern {
137         fn _tlv_atexit(dtor: unsafe extern fn(*mut u8),
138                        arg: *mut u8);
139     }
140     _tlv_atexit(dtor, t);
141 }
142
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);
148 }
149
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
154     // `None`.
155     (*ptr).dtor_running.set(true);
156
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.
162     //
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!
166     //
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());
171     } else {
172         ptr::drop_in_place((*ptr).inner.get());
173     }
174 }