Skip to main content

std/sys/thread_local/native/
mod.rs

1//! Thread local support for platforms with native TLS.
2//!
3//! To achieve the best performance, we choose from four different types for
4//! the TLS variable, depending on the method of initialization used (`const`
5//! or lazy) and the drop requirements of the stored type:
6//!
7//! |         | `Drop`               | `!Drop`             |
8//! |--------:|:--------------------:|:-------------------:|
9//! | `const` | `EagerStorage<T>`    | `T`                 |
10//! | lazy    | `LazyStorage<T, ()>` | `LazyStorage<T, !>` |
11//!
12//! For `const` initialization and `!Drop` types, we simply use `T` directly,
13//! but for other situations, we implement a state machine to handle
14//! initialization of the variable and its destructor and destruction.
15//! Upon accessing the TLS variable, the current state is compared:
16//!
17//! 1. If the state is `Initial`, initialize the storage, transition the state
18//!    to `Alive` and (if applicable) register the destructor, and return a
19//!    reference to the value.
20//! 2. If the state is `Alive`, initialization was previously completed, so
21//!    return a reference to the value.
22//! 3. If the state is `Destroyed`, the destructor has been run already, so
23//!    return [`None`].
24//!
25//! The TLS destructor sets the state to `Destroyed` and drops the current value.
26//!
27//! To simplify the code, we make `LazyStorage` generic over the destroyed state
28//! and use the `!` type (never type) as type parameter for `!Drop` types. This
29//! eliminates the `Destroyed` state for these values, which can allow more niche
30//! optimizations to occur for the `State` enum. For `Drop` types, `()` is used.
31
32use crate::cell::Cell;
33use crate::ptr;
34
35mod eager;
36mod lazy;
37
38pub use eager::Storage as EagerStorage;
39pub use lazy::Storage as LazyStorage;
40
41#[doc(hidden)]
42#[allow_internal_unstable(
43    thread_local_internals,
44    cfg_target_thread_local,
45    thread_local,
46    never_type
47)]
48#[allow_internal_unsafe]
49#[unstable(feature = "thread_local_internals", issue = "none")]
50#[rustc_macro_transparency = "semiopaque"]
51pub macro thread_local_inner {
52    // NOTE: we cannot import `LocalKey`, `LazyStorage` or `EagerStorage` with a `use` because that
53    // can shadow user provided type or type alias with a matching name. Please update the shadowing
54    // test in `tests/thread.rs` if these types are renamed.
55
56    // Used to generate the `LocalKey` value for const-initialized thread locals.
57    (@key $t:ty, $(#[$align_attr:meta])*, const $init:expr) => {{
58        const __RUST_STD_INTERNAL_INIT: $t = $init;
59
60        unsafe {
61            $crate::thread::LocalKey::new(const {
62                if $crate::mem::needs_drop::<$t>() {
63                    |_| {
64                        #[thread_local]
65                        $(#[$align_attr])*
66                        static __RUST_STD_INTERNAL_VAL: $crate::thread::local_impl::EagerStorage<$t>
67                            = $crate::thread::local_impl::EagerStorage::new(__RUST_STD_INTERNAL_INIT);
68                        __RUST_STD_INTERNAL_VAL.get()
69                    }
70                } else {
71                    |_| {
72                        #[thread_local]
73                        $(#[$align_attr])*
74                        static __RUST_STD_INTERNAL_VAL: $t = __RUST_STD_INTERNAL_INIT;
75                        &__RUST_STD_INTERNAL_VAL
76                    }
77                }
78            })
79        }
80    }},
81
82    // used to generate the `LocalKey` value for `thread_local!`
83    (@key $t:ty, $(#[$align_attr:meta])*, $init:expr) => {{
84        // We intentionally have an argument-position `'static` lifetime so that elided lifetimes in `$t`
85        // become `'static` like they do for `const`s and `static`s, including in the other two
86        // `thread_local!` implementations.
87        #[allow(mismatched_lifetime_syntaxes)]
88        #[inline]
89        fn __rust_std_internal_init_fn(_lifetime_elision: $crate::marker::PhantomData<&'static ()>) -> $t {
90            $init
91        }
92
93        unsafe {
94            $crate::thread::LocalKey::new(const {
95                if $crate::mem::needs_drop::<$t>() {
96                    |__rust_std_internal_init| {
97                        #[thread_local]
98                        $(#[$align_attr])*
99                        static __RUST_STD_INTERNAL_VAL: $crate::thread::local_impl::LazyStorage<$t, ()>
100                            = $crate::thread::local_impl::LazyStorage::new();
101                        __RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init, || __rust_std_internal_init_fn($crate::marker::PhantomData))
102                    }
103                } else {
104                    |__rust_std_internal_init| {
105                        #[thread_local]
106                        $(#[$align_attr])*
107                        static __RUST_STD_INTERNAL_VAL: $crate::thread::local_impl::LazyStorage<$t, !>
108                            = $crate::thread::local_impl::LazyStorage::new();
109                        __RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init, || __rust_std_internal_init_fn($crate::marker::PhantomData))
110                    }
111                }
112            })
113        }
114    }},
115}
116
117#[rustc_macro_transparency = "semiopaque"]
118pub(crate) macro local_pointer {
119    () => {},
120    ($vis:vis static $name:ident; $($rest:tt)*) => {
121        #[thread_local]
122        $vis static $name: $crate::sys::thread_local::LocalPointer = $crate::sys::thread_local::LocalPointer::__new();
123        $crate::sys::thread_local::local_pointer! { $($rest)* }
124    },
125}
126
127pub(crate) struct LocalPointer {
128    p: Cell<*mut ()>,
129}
130
131impl LocalPointer {
132    pub const fn __new() -> LocalPointer {
133        LocalPointer { p: Cell::new(ptr::null_mut()) }
134    }
135
136    pub fn get(&self) -> *mut () {
137        self.p.get()
138    }
139
140    pub fn set(&self, p: *mut ()) {
141        self.p.set(p)
142    }
143}