]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/common/thread_local.rs
std: Leak all statically allocated TLS keys
[rust.git] / src / libstd / sys / common / thread_local.rs
1 // Copyright 2014 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 //! OS-based thread local storage
12 //!
13 //! This module provides an implementation of OS-based thread local storage,
14 //! using the native OS-provided facilities (think `TlsAlloc` or
15 //! `pthread_setspecific`). The interface of this differs from the other types
16 //! of thread-local-storage provided in this crate in that OS-based TLS can only
17 //! get/set pointers,
18 //!
19 //! This module also provides two flavors of TLS. One is intended for static
20 //! initialization, and does not contain a `Drop` implementation to deallocate
21 //! the OS-TLS key. The other is a type which does implement `Drop` and hence
22 //! has a safe interface.
23 //!
24 //! # Usage
25 //!
26 //! This module should likely not be used directly unless other primitives are
27 //! being built on. types such as `thread_local::scoped::Key` are likely much
28 //! more useful in practice than this OS-based version which likely requires
29 //! unsafe code to interoperate with.
30 //!
31 //! # Example
32 //!
33 //! Using a dynamically allocated TLS key. Note that this key can be shared
34 //! among many threads via an `Arc`.
35 //!
36 //! ```rust,ignore
37 //! let key = Key::new(None);
38 //! assert!(key.get().is_null());
39 //! key.set(1 as *mut u8);
40 //! assert!(!key.get().is_null());
41 //!
42 //! drop(key); // deallocate this TLS slot.
43 //! ```
44 //!
45 //! Sometimes a statically allocated key is either required or easier to work
46 //! with, however.
47 //!
48 //! ```rust,ignore
49 //! static KEY: StaticKey = INIT;
50 //!
51 //! unsafe {
52 //!     assert!(KEY.get().is_null());
53 //!     KEY.set(1 as *mut u8);
54 //! }
55 //! ```
56
57 #![allow(non_camel_case_types)]
58
59 use prelude::*;
60
61 use kinds::marker;
62 use rustrt::exclusive::Exclusive;
63 use sync::atomic::{mod, AtomicUint};
64 use sync::{Once, ONCE_INIT};
65
66 use sys::thread_local as imp;
67
68 /// A type for TLS keys that are statically allocated.
69 ///
70 /// This type is entirely `unsafe` to use as it does not protect against
71 /// use-after-deallocation or use-during-deallocation.
72 ///
73 /// The actual OS-TLS key is lazily allocated when this is used for the first
74 /// time. The key is also deallocated when the Rust runtime exits or `destroy`
75 /// is called, whichever comes first.
76 ///
77 /// # Example
78 ///
79 /// ```ignore
80 /// use tls::os::{StaticKey, INIT};
81 ///
82 /// static KEY: StaticKey = INIT;
83 ///
84 /// unsafe {
85 ///     assert!(KEY.get().is_null());
86 ///     KEY.set(1 as *mut u8);
87 /// }
88 /// ```
89 pub struct StaticKey {
90     /// Inner static TLS key (internals), created with by `INIT_INNER` in this
91     /// module.
92     pub inner: StaticKeyInner,
93     /// Destructor for the TLS value.
94     ///
95     /// See `Key::new` for information about when the destructor runs and how
96     /// it runs.
97     pub dtor: Option<unsafe extern fn(*mut u8)>,
98 }
99
100 /// Inner contents of `StaticKey`, created by the `INIT_INNER` constant.
101 pub struct StaticKeyInner {
102     key: AtomicUint,
103     nc: marker::NoCopy,
104 }
105
106 /// A type for a safely managed OS-based TLS slot.
107 ///
108 /// This type allocates an OS TLS key when it is initialized and will deallocate
109 /// the key when it falls out of scope. When compared with `StaticKey`, this
110 /// type is entirely safe to use.
111 ///
112 /// Implementations will likely, however, contain unsafe code as this type only
113 /// operates on `*mut u8`, an unsafe pointer.
114 ///
115 /// # Example
116 ///
117 /// ```rust,ignore
118 /// use tls::os::Key;
119 ///
120 /// let key = Key::new(None);
121 /// assert!(key.get().is_null());
122 /// key.set(1 as *mut u8);
123 /// assert!(!key.get().is_null());
124 ///
125 /// drop(key); // deallocate this TLS slot.
126 /// ```
127 pub struct Key {
128     key: imp::Key,
129 }
130
131 /// Constant initialization value for static TLS keys.
132 ///
133 /// This value specifies no destructor by default.
134 pub const INIT: StaticKey = StaticKey {
135     inner: INIT_INNER,
136     dtor: None,
137 };
138
139 /// Constant initialization value for the inner part of static TLS keys.
140 ///
141 /// This value allows specific configuration of the destructor for a TLS key.
142 pub const INIT_INNER: StaticKeyInner = StaticKeyInner {
143     key: atomic::INIT_ATOMIC_UINT,
144     nc: marker::NoCopy,
145 };
146
147 static INIT_KEYS: Once = ONCE_INIT;
148 static mut KEYS: *mut Exclusive<Vec<imp::Key>> = 0 as *mut _;
149
150 impl StaticKey {
151     /// Gets the value associated with this TLS key
152     ///
153     /// This will lazily allocate a TLS key from the OS if one has not already
154     /// been allocated.
155     #[inline]
156     pub unsafe fn get(&self) -> *mut u8 { imp::get(self.key()) }
157
158     /// Sets this TLS key to a new value.
159     ///
160     /// This will lazily allocate a TLS key from the OS if one has not already
161     /// been allocated.
162     #[inline]
163     pub unsafe fn set(&self, val: *mut u8) { imp::set(self.key(), val) }
164
165     /// Deallocates this OS TLS key.
166     ///
167     /// This function is unsafe as there is no guarantee that the key is not
168     /// currently in use by other threads or will not ever be used again.
169     ///
170     /// Note that this does *not* run the user-provided destructor if one was
171     /// specified at definition time. Doing so must be done manually.
172     pub unsafe fn destroy(&self) {
173         match self.inner.key.swap(0, atomic::SeqCst) {
174             0 => {}
175             n => { imp::destroy(n as imp::Key) }
176         }
177     }
178
179     #[inline]
180     unsafe fn key(&self) -> imp::Key {
181         match self.inner.key.load(atomic::Relaxed) {
182             0 => self.lazy_init() as imp::Key,
183             n => n as imp::Key
184         }
185     }
186
187     unsafe fn lazy_init(&self) -> uint {
188         let key = imp::create(self.dtor);
189         assert!(key != 0);
190         match self.inner.key.compare_and_swap(0, key as uint, atomic::SeqCst) {
191             // The CAS succeeded, so we've created the actual key
192             0 => key as uint,
193             // If someone beat us to the punch, use their key instead
194             n => { imp::destroy(key); n }
195         }
196     }
197 }
198
199 impl Key {
200     /// Create a new managed OS TLS key.
201     ///
202     /// This key will be deallocated when the key falls out of scope.
203     ///
204     /// The argument provided is an optionally-specified destructor for the
205     /// value of this TLS key. When a thread exits and the value for this key
206     /// is non-null the destructor will be invoked. The TLS value will be reset
207     /// to null before the destructor is invoked.
208     ///
209     /// Note that the destructor will not be run when the `Key` goes out of
210     /// scope.
211     #[inline]
212     pub fn new(dtor: Option<unsafe extern fn(*mut u8)>) -> Key {
213         Key { key: unsafe { imp::create(dtor) } }
214     }
215
216     /// See StaticKey::get
217     #[inline]
218     pub fn get(&self) -> *mut u8 {
219         unsafe { imp::get(self.key) }
220     }
221
222     /// See StaticKey::set
223     #[inline]
224     pub fn set(&self, val: *mut u8) {
225         unsafe { imp::set(self.key, val) }
226     }
227 }
228
229 impl Drop for Key {
230     fn drop(&mut self) {
231         unsafe { imp::destroy(self.key) }
232     }
233 }
234
235 #[cfg(test)]
236 mod tests {
237     use prelude::*;
238     use super::{Key, StaticKey, INIT_INNER};
239
240     fn assert_sync<T: Sync>() {}
241     fn assert_send<T: Send>() {}
242
243     #[test]
244     fn smoke() {
245         assert_sync::<Key>();
246         assert_send::<Key>();
247
248         let k1 = Key::new(None);
249         let k2 = Key::new(None);
250         assert!(k1.get().is_null());
251         assert!(k2.get().is_null());
252         k1.set(1 as *mut _);
253         k2.set(2 as *mut _);
254         assert_eq!(k1.get() as uint, 1);
255         assert_eq!(k2.get() as uint, 2);
256     }
257
258     #[test]
259     fn statik() {
260         static K1: StaticKey = StaticKey { inner: INIT_INNER, dtor: None };
261         static K2: StaticKey = StaticKey { inner: INIT_INNER, dtor: None };
262
263         unsafe {
264             assert!(K1.get().is_null());
265             assert!(K2.get().is_null());
266             K1.set(1 as *mut _);
267             K2.set(2 as *mut _);
268             assert_eq!(K1.get() as uint, 1);
269             assert_eq!(K2.get() as uint, 2);
270         }
271     }
272 }
273