]> git.lizzy.rs Git - rust.git/blob - src/libstd/thread/local.rs
SGX target: fix std unit tests
[rust.git] / src / libstd / thread / local.rs
1 //! Thread local storage
2
3 #![unstable(feature = "thread_local_internals", issue = "0")]
4
5 use crate::cell::UnsafeCell;
6 use crate::fmt;
7 use crate::hint;
8 use crate::mem;
9
10 /// A thread local storage key which owns its contents.
11 ///
12 /// This key uses the fastest possible implementation available to it for the
13 /// target platform. It is instantiated with the [`thread_local!`] macro and the
14 /// primary method is the [`with`] method.
15 ///
16 /// The [`with`] method yields a reference to the contained value which cannot be
17 /// sent across threads or escape the given closure.
18 ///
19 /// # Initialization and Destruction
20 ///
21 /// Initialization is dynamically performed on the first call to [`with`]
22 /// within a thread, and values that implement [`Drop`] get destructed when a
23 /// thread exits. Some caveats apply, which are explained below.
24 ///
25 /// A `LocalKey`'s initializer cannot recursively depend on itself, and using
26 /// a `LocalKey` in this way will cause the initializer to infinitely recurse
27 /// on the first call to `with`.
28 ///
29 /// # Examples
30 ///
31 /// ```
32 /// use std::cell::RefCell;
33 /// use std::thread;
34 ///
35 /// thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
36 ///
37 /// FOO.with(|f| {
38 ///     assert_eq!(*f.borrow(), 1);
39 ///     *f.borrow_mut() = 2;
40 /// });
41 ///
42 /// // each thread starts out with the initial value of 1
43 /// let t = thread::spawn(move|| {
44 ///     FOO.with(|f| {
45 ///         assert_eq!(*f.borrow(), 1);
46 ///         *f.borrow_mut() = 3;
47 ///     });
48 /// });
49 ///
50 /// // wait for the thread to complete and bail out on panic
51 /// t.join().unwrap();
52 ///
53 /// // we retain our original value of 2 despite the child thread
54 /// FOO.with(|f| {
55 ///     assert_eq!(*f.borrow(), 2);
56 /// });
57 /// ```
58 ///
59 /// # Platform-specific behavior
60 ///
61 /// Note that a "best effort" is made to ensure that destructors for types
62 /// stored in thread local storage are run, but not all platforms can guarantee
63 /// that destructors will be run for all types in thread local storage. For
64 /// example, there are a number of known caveats where destructors are not run:
65 ///
66 /// 1. On Unix systems when pthread-based TLS is being used, destructors will
67 ///    not be run for TLS values on the main thread when it exits. Note that the
68 ///    application will exit immediately after the main thread exits as well.
69 /// 2. On all platforms it's possible for TLS to re-initialize other TLS slots
70 ///    during destruction. Some platforms ensure that this cannot happen
71 ///    infinitely by preventing re-initialization of any slot that has been
72 ///    destroyed, but not all platforms have this guard. Those platforms that do
73 ///    not guard typically have a synthetic limit after which point no more
74 ///    destructors are run.
75 ///
76 /// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
77 /// [`thread_local!`]: ../../std/macro.thread_local.html
78 /// [`Drop`]: ../../std/ops/trait.Drop.html
79 #[stable(feature = "rust1", since = "1.0.0")]
80 pub struct LocalKey<T: 'static> {
81     // This outer `LocalKey<T>` type is what's going to be stored in statics,
82     // but actual data inside will sometimes be tagged with #[thread_local].
83     // It's not valid for a true static to reference a #[thread_local] static,
84     // so we get around that by exposing an accessor through a layer of function
85     // indirection (this thunk).
86     //
87     // Note that the thunk is itself unsafe because the returned lifetime of the
88     // slot where data lives, `'static`, is not actually valid. The lifetime
89     // here is actually slightly shorter than the currently running thread!
90     //
91     // Although this is an extra layer of indirection, it should in theory be
92     // trivially devirtualizable by LLVM because the value of `inner` never
93     // changes and the constant should be readonly within a crate. This mainly
94     // only runs into problems when TLS statics are exported across crates.
95     inner: unsafe fn() -> Option<&'static UnsafeCell<Option<T>>>,
96
97     // initialization routine to invoke to create a value
98     init: fn() -> T,
99 }
100
101 #[stable(feature = "std_debug", since = "1.16.0")]
102 impl<T: 'static> fmt::Debug for LocalKey<T> {
103     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104         f.pad("LocalKey { .. }")
105     }
106 }
107
108 /// Declare a new thread local storage key of type [`std::thread::LocalKey`].
109 ///
110 /// # Syntax
111 ///
112 /// The macro wraps any number of static declarations and makes them thread local.
113 /// Publicity and attributes for each static are allowed. Example:
114 ///
115 /// ```
116 /// use std::cell::RefCell;
117 /// thread_local! {
118 ///     pub static FOO: RefCell<u32> = RefCell::new(1);
119 ///
120 ///     #[allow(unused)]
121 ///     static BAR: RefCell<f32> = RefCell::new(1.0);
122 /// }
123 /// # fn main() {}
124 /// ```
125 ///
126 /// See [LocalKey documentation][`std::thread::LocalKey`] for more
127 /// information.
128 ///
129 /// [`std::thread::LocalKey`]: ../std/thread/struct.LocalKey.html
130 #[macro_export]
131 #[stable(feature = "rust1", since = "1.0.0")]
132 #[allow_internal_unstable(thread_local_internals)]
133 macro_rules! thread_local {
134     // empty (base case for the recursion)
135     () => {};
136
137     // process multiple declarations
138     ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
139         $crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
140         $crate::thread_local!($($rest)*);
141     );
142
143     // handle a single declaration
144     ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => (
145         $crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
146     );
147 }
148
149 #[doc(hidden)]
150 #[unstable(feature = "thread_local_internals",
151            reason = "should not be necessary",
152            issue = "0")]
153 #[macro_export]
154 #[allow_internal_unstable(thread_local_internals, cfg_target_thread_local, thread_local)]
155 #[allow_internal_unsafe]
156 macro_rules! __thread_local_inner {
157     (@key $(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $init:expr) => {
158         {
159             #[inline]
160             fn __init() -> $t { $init }
161
162             unsafe fn __getit() -> $crate::option::Option<
163                 &'static $crate::cell::UnsafeCell<
164                     $crate::option::Option<$t>>>
165             {
166                 #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))]
167                 static __KEY: $crate::thread::__StaticLocalKeyInner<$t> =
168                     $crate::thread::__StaticLocalKeyInner::new();
169
170                 #[thread_local]
171                 #[cfg(all(
172                     target_thread_local,
173                     not(all(target_arch = "wasm32", not(target_feature = "atomics"))),
174                 ))]
175                 static __KEY: $crate::thread::__FastLocalKeyInner<$t> =
176                     $crate::thread::__FastLocalKeyInner::new();
177
178                 #[cfg(all(
179                     not(target_thread_local),
180                     not(all(target_arch = "wasm32", not(target_feature = "atomics"))),
181                 ))]
182                 static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
183                     $crate::thread::__OsLocalKeyInner::new();
184
185                 __KEY.get()
186             }
187
188             unsafe {
189                 $crate::thread::LocalKey::new(__getit, __init)
190             }
191         }
192     };
193     ($(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $init:expr) => {
194         $(#[$attr])* $vis const $name: $crate::thread::LocalKey<$t> =
195             $crate::__thread_local_inner!(@key $(#[$attr])* $vis $name, $t, $init);
196     }
197 }
198
199 /// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with).
200 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
201 pub struct AccessError {
202     _private: (),
203 }
204
205 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
206 impl fmt::Debug for AccessError {
207     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
208         f.debug_struct("AccessError").finish()
209     }
210 }
211
212 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
213 impl fmt::Display for AccessError {
214     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
215         fmt::Display::fmt("already destroyed", f)
216     }
217 }
218
219 impl<T: 'static> LocalKey<T> {
220     #[doc(hidden)]
221     #[unstable(feature = "thread_local_internals",
222                reason = "recently added to create a key",
223                issue = "0")]
224     pub const unsafe fn new(inner: unsafe fn() -> Option<&'static UnsafeCell<Option<T>>>,
225                             init: fn() -> T) -> LocalKey<T> {
226         LocalKey {
227             inner,
228             init,
229         }
230     }
231
232     /// Acquires a reference to the value in this TLS key.
233     ///
234     /// This will lazily initialize the value if this thread has not referenced
235     /// this key yet.
236     ///
237     /// # Panics
238     ///
239     /// This function will `panic!()` if the key currently has its
240     /// destructor running, and it **may** panic if the destructor has
241     /// previously been run for this thread.
242     #[stable(feature = "rust1", since = "1.0.0")]
243     pub fn with<F, R>(&'static self, f: F) -> R
244                       where F: FnOnce(&T) -> R {
245         self.try_with(f).expect("cannot access a TLS value during or \
246                                  after it is destroyed")
247     }
248
249     unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T {
250         // Execute the initialization up front, *then* move it into our slot,
251         // just in case initialization fails.
252         let value = (self.init)();
253         let ptr = slot.get();
254
255         // note that this can in theory just be `*ptr = Some(value)`, but due to
256         // the compiler will currently codegen that pattern with something like:
257         //
258         //      ptr::drop_in_place(ptr)
259         //      ptr::write(ptr, Some(value))
260         //
261         // Due to this pattern it's possible for the destructor of the value in
262         // `ptr` (e.g., if this is being recursively initialized) to re-access
263         // TLS, in which case there will be a `&` and `&mut` pointer to the same
264         // value (an aliasing violation). To avoid setting the "I'm running a
265         // destructor" flag we just use `mem::replace` which should sequence the
266         // operations a little differently and make this safe to call.
267         mem::replace(&mut *ptr, Some(value));
268
269         // After storing `Some` we want to get a reference to the contents of
270         // what we just stored. While we could use `unwrap` here and it should
271         // always work it empirically doesn't seem to always get optimized away,
272         // which means that using something like `try_with` can pull in
273         // panicking code and cause a large size bloat.
274         match *ptr {
275             Some(ref x) => x,
276             None => hint::unreachable_unchecked(),
277         }
278     }
279
280     /// Acquires a reference to the value in this TLS key.
281     ///
282     /// This will lazily initialize the value if this thread has not referenced
283     /// this key yet. If the key has been destroyed (which may happen if this is called
284     /// in a destructor), this function will return an [`AccessError`](struct.AccessError.html).
285     ///
286     /// # Panics
287     ///
288     /// This function will still `panic!()` if the key is uninitialized and the
289     /// key's initializer panics.
290     #[stable(feature = "thread_local_try_with", since = "1.26.0")]
291     pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
292     where
293         F: FnOnce(&T) -> R,
294     {
295         unsafe {
296             let slot = (self.inner)().ok_or(AccessError {
297                 _private: (),
298             })?;
299             Ok(f(match *slot.get() {
300                 Some(ref inner) => inner,
301                 None => self.init(slot),
302             }))
303         }
304     }
305 }
306
307 /// On some platforms like wasm32 there's no threads, so no need to generate
308 /// thread locals and we can instead just use plain statics!
309 #[doc(hidden)]
310 #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))]
311 pub mod statik {
312     use crate::cell::UnsafeCell;
313     use crate::fmt;
314
315     pub struct Key<T> {
316         inner: UnsafeCell<Option<T>>,
317     }
318
319     unsafe impl<T> Sync for Key<T> { }
320
321     impl<T> fmt::Debug for Key<T> {
322         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
323             f.pad("Key { .. }")
324         }
325     }
326
327     impl<T> Key<T> {
328         pub const fn new() -> Key<T> {
329             Key {
330                 inner: UnsafeCell::new(None),
331             }
332         }
333
334         pub unsafe fn get(&self) -> Option<&'static UnsafeCell<Option<T>>> {
335             Some(&*(&self.inner as *const _))
336         }
337     }
338 }
339
340 #[doc(hidden)]
341 #[cfg(target_thread_local)]
342 pub mod fast {
343     use crate::cell::{Cell, UnsafeCell};
344     use crate::fmt;
345     use crate::mem;
346     use crate::ptr;
347     use crate::sys::fast_thread_local::{register_dtor, requires_move_before_drop};
348
349     pub struct Key<T> {
350         inner: UnsafeCell<Option<T>>,
351
352         // Metadata to keep track of the state of the destructor. Remember that
353         // these variables are thread-local, not global.
354         dtor_registered: Cell<bool>,
355         dtor_running: Cell<bool>,
356     }
357
358     impl<T> fmt::Debug for Key<T> {
359         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
360             f.pad("Key { .. }")
361         }
362     }
363
364     impl<T> Key<T> {
365         pub const fn new() -> Key<T> {
366             Key {
367                 inner: UnsafeCell::new(None),
368                 dtor_registered: Cell::new(false),
369                 dtor_running: Cell::new(false)
370             }
371         }
372
373         pub unsafe fn get(&self) -> Option<&'static UnsafeCell<Option<T>>> {
374             if mem::needs_drop::<T>() && self.dtor_running.get() {
375                 return None
376             }
377             self.register_dtor();
378             Some(&*(&self.inner as *const _))
379         }
380
381         unsafe fn register_dtor(&self) {
382             if !mem::needs_drop::<T>() || self.dtor_registered.get() {
383                 return
384             }
385
386             register_dtor(self as *const _ as *mut u8,
387                           destroy_value::<T>);
388             self.dtor_registered.set(true);
389         }
390     }
391
392     unsafe extern fn destroy_value<T>(ptr: *mut u8) {
393         let ptr = ptr as *mut Key<T>;
394         // Right before we run the user destructor be sure to flag the
395         // destructor as running for this thread so calls to `get` will return
396         // `None`.
397         (*ptr).dtor_running.set(true);
398
399         // Some implementations may require us to move the value before we drop
400         // it as it could get re-initialized in-place during destruction.
401         //
402         // Hence, we use `ptr::read` on those platforms (to move to a "safe"
403         // location) instead of drop_in_place.
404         if requires_move_before_drop() {
405             ptr::read((*ptr).inner.get());
406         } else {
407             ptr::drop_in_place((*ptr).inner.get());
408         }
409     }
410 }
411
412 #[doc(hidden)]
413 pub mod os {
414     use crate::cell::{Cell, UnsafeCell};
415     use crate::fmt;
416     use crate::marker;
417     use crate::ptr;
418     use crate::sys_common::thread_local::StaticKey as OsStaticKey;
419
420     pub struct Key<T> {
421         // OS-TLS key that we'll use to key off.
422         os: OsStaticKey,
423         marker: marker::PhantomData<Cell<T>>,
424     }
425
426     impl<T> fmt::Debug for Key<T> {
427         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
428             f.pad("Key { .. }")
429         }
430     }
431
432     unsafe impl<T> Sync for Key<T> { }
433
434     struct Value<T: 'static> {
435         key: &'static Key<T>,
436         value: UnsafeCell<Option<T>>,
437     }
438
439     impl<T: 'static> Key<T> {
440         pub const fn new() -> Key<T> {
441             Key {
442                 os: OsStaticKey::new(Some(destroy_value::<T>)),
443                 marker: marker::PhantomData
444             }
445         }
446
447         pub unsafe fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> {
448             let ptr = self.os.get() as *mut Value<T>;
449             if !ptr.is_null() {
450                 if ptr as usize == 1 {
451                     return None
452                 }
453                 return Some(&(*ptr).value);
454             }
455
456             // If the lookup returned null, we haven't initialized our own
457             // local copy, so do that now.
458             let ptr: Box<Value<T>> = box Value {
459                 key: self,
460                 value: UnsafeCell::new(None),
461             };
462             let ptr = Box::into_raw(ptr);
463             self.os.set(ptr as *mut u8);
464             Some(&(*ptr).value)
465         }
466     }
467
468     unsafe extern fn destroy_value<T: 'static>(ptr: *mut u8) {
469         // The OS TLS ensures that this key contains a NULL value when this
470         // destructor starts to run. We set it back to a sentinel value of 1 to
471         // ensure that any future calls to `get` for this thread will return
472         // `None`.
473         //
474         // Note that to prevent an infinite loop we reset it back to null right
475         // before we return from the destructor ourselves.
476         let ptr = Box::from_raw(ptr as *mut Value<T>);
477         let key = ptr.key;
478         key.os.set(1 as *mut u8);
479         drop(ptr);
480         key.os.set(ptr::null_mut());
481     }
482 }
483
484 #[cfg(all(test, not(target_os = "emscripten")))]
485 mod tests {
486     use crate::sync::mpsc::{channel, Sender};
487     use crate::cell::{Cell, UnsafeCell};
488     use crate::thread;
489
490     struct Foo(Sender<()>);
491
492     impl Drop for Foo {
493         fn drop(&mut self) {
494             let Foo(ref s) = *self;
495             s.send(()).unwrap();
496         }
497     }
498
499     #[test]
500     fn smoke_no_dtor() {
501         thread_local!(static FOO: Cell<i32> = Cell::new(1));
502
503         FOO.with(|f| {
504             assert_eq!(f.get(), 1);
505             f.set(2);
506         });
507         let (tx, rx) = channel();
508         let _t = thread::spawn(move|| {
509             FOO.with(|f| {
510                 assert_eq!(f.get(), 1);
511             });
512             tx.send(()).unwrap();
513         });
514         rx.recv().unwrap();
515
516         FOO.with(|f| {
517             assert_eq!(f.get(), 2);
518         });
519     }
520
521     #[test]
522     fn states() {
523         struct Foo;
524         impl Drop for Foo {
525             fn drop(&mut self) {
526                 assert!(FOO.try_with(|_| ()).is_err());
527             }
528         }
529         thread_local!(static FOO: Foo = Foo);
530
531         thread::spawn(|| {
532             assert!(FOO.try_with(|_| ()).is_ok());
533         }).join().ok().expect("thread panicked");
534     }
535
536     #[test]
537     fn smoke_dtor() {
538         thread_local!(static FOO: UnsafeCell<Option<Foo>> = UnsafeCell::new(None));
539
540         let (tx, rx) = channel();
541         let _t = thread::spawn(move|| unsafe {
542             let mut tx = Some(tx);
543             FOO.with(|f| {
544                 *f.get() = Some(Foo(tx.take().unwrap()));
545             });
546         });
547         rx.recv().unwrap();
548     }
549
550     #[test]
551     fn circular() {
552         struct S1;
553         struct S2;
554         thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
555         thread_local!(static K2: UnsafeCell<Option<S2>> = UnsafeCell::new(None));
556         static mut HITS: u32 = 0;
557
558         impl Drop for S1 {
559             fn drop(&mut self) {
560                 unsafe {
561                     HITS += 1;
562                     if K2.try_with(|_| ()).is_err() {
563                         assert_eq!(HITS, 3);
564                     } else {
565                         if HITS == 1 {
566                             K2.with(|s| *s.get() = Some(S2));
567                         } else {
568                             assert_eq!(HITS, 3);
569                         }
570                     }
571                 }
572             }
573         }
574         impl Drop for S2 {
575             fn drop(&mut self) {
576                 unsafe {
577                     HITS += 1;
578                     assert!(K1.try_with(|_| ()).is_ok());
579                     assert_eq!(HITS, 2);
580                     K1.with(|s| *s.get() = Some(S1));
581                 }
582             }
583         }
584
585         thread::spawn(move|| {
586             drop(S1);
587         }).join().ok().expect("thread panicked");
588     }
589
590     #[test]
591     fn self_referential() {
592         struct S1;
593         thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
594
595         impl Drop for S1 {
596             fn drop(&mut self) {
597                 assert!(K1.try_with(|_| ()).is_err());
598             }
599         }
600
601         thread::spawn(move|| unsafe {
602             K1.with(|s| *s.get() = Some(S1));
603         }).join().ok().expect("thread panicked");
604     }
605
606     // Note that this test will deadlock if TLS destructors aren't run (this
607     // requires the destructor to be run to pass the test).
608     #[test]
609     fn dtors_in_dtors_in_dtors() {
610         struct S1(Sender<()>);
611         thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
612         thread_local!(static K2: UnsafeCell<Option<Foo>> = UnsafeCell::new(None));
613
614         impl Drop for S1 {
615             fn drop(&mut self) {
616                 let S1(ref tx) = *self;
617                 unsafe {
618                     let _ = K2.try_with(|s| *s.get() = Some(Foo(tx.clone())));
619                 }
620             }
621         }
622
623         let (tx, rx) = channel();
624         let _t = thread::spawn(move|| unsafe {
625             let mut tx = Some(tx);
626             K1.with(|s| *s.get() = Some(S1(tx.take().unwrap())));
627         });
628         rx.recv().unwrap();
629     }
630 }
631
632 #[cfg(test)]
633 mod dynamic_tests {
634     use crate::cell::RefCell;
635     use crate::collections::HashMap;
636
637     #[test]
638     fn smoke() {
639         fn square(i: i32) -> i32 { i * i }
640         thread_local!(static FOO: i32 = square(3));
641
642         FOO.with(|f| {
643             assert_eq!(*f, 9);
644         });
645     }
646
647     #[test]
648     fn hashmap() {
649         fn map() -> RefCell<HashMap<i32, i32>> {
650             let mut m = HashMap::new();
651             m.insert(1, 2);
652             RefCell::new(m)
653         }
654         thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map());
655
656         FOO.with(|map| {
657             assert_eq!(map.borrow()[&1], 2);
658         });
659     }
660
661     #[test]
662     fn refcell_vec() {
663         thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3]));
664
665         FOO.with(|vec| {
666             assert_eq!(vec.borrow().len(), 3);
667             vec.borrow_mut().push(4);
668             assert_eq!(vec.borrow()[3], 4);
669         });
670     }
671 }