Skip to main content

std\sys\thread_local/
os.rs

1use super::key::{Key, LazyKey, get, set};
2use super::{abort_on_dtor_unwind, guard};
3use crate::alloc::{GlobalAlloc, Layout, System};
4use crate::cell::Cell;
5use crate::marker::PhantomData;
6use crate::mem::ManuallyDrop;
7use crate::ops::Deref;
8use crate::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
9use crate::ptr::{self, NonNull};
10
11#[doc(hidden)]
12#[allow_internal_unstable(thread_local_internals)]
13#[allow_internal_unsafe]
14#[unstable(feature = "thread_local_internals", issue = "none")]
15#[rustc_macro_transparency = "semiopaque"]
16pub macro thread_local_inner {
17    // NOTE: we cannot import `Storage` or `LocalKey` with a `use` because that can shadow user
18    // provided type or type alias with a matching name. Please update the shadowing test in
19    // `tests/thread.rs` if these types are renamed.
20
21    // used to generate the `LocalKey` value for `thread_local!`.
22    (@key $t:ty, $($(#[$($align_attr:tt)*])+)?, $init:expr) => {{
23        #[inline]
24        fn __rust_std_internal_init_fn() -> $t { $init }
25
26        // NOTE: this cannot import `LocalKey` or `Storage` with a `use` because that can shadow
27        // user provided type or type alias with a matching name. Please update the shadowing test
28        // in `tests/thread.rs` if these types are renamed.
29        unsafe {
30            $crate::thread::LocalKey::new(|__rust_std_internal_init| {
31                static __RUST_STD_INTERNAL_VAL: $crate::thread::local_impl::Storage<$t, {
32                    $({
33                        // Ensure that attributes have valid syntax
34                        // and that the proper feature gate is enabled
35                        $(#[$($align_attr)*])+
36                        #[allow(unused)]
37                        static DUMMY: () = ();
38                    })?
39
40                    #[allow(unused_mut)]
41                    let mut final_align = $crate::thread::local_impl::value_align::<$t>();
42                    $($($crate::thread::local_impl::thread_local_inner!(@align final_align, $($align_attr)*);)+)?
43                    final_align
44                }>
45                    = $crate::thread::local_impl::Storage::new();
46                __RUST_STD_INTERNAL_VAL.get(__rust_std_internal_init, __rust_std_internal_init_fn)
47            })
48        }
49    }},
50
51    // process a single `rustc_align_static` attribute
52    (@align $final_align:ident, rustc_align_static($($align:tt)*) $(, $($attr_rest:tt)+)?) => {
53        let new_align: $crate::primitive::usize = $($align)*;
54        if new_align > $final_align {
55            $final_align = new_align;
56        }
57
58        $($crate::thread::local_impl::thread_local_inner!(@align $final_align, $($attr_rest)+);)?
59    },
60
61    // process a single `cfg_attr` attribute
62    // by translating it into a `cfg`ed block and recursing.
63    // https://doc.rust-lang.org/reference/conditional-compilation.html#railroad-ConfigurationPredicate
64
65    (@align $final_align:ident, cfg_attr($cfg_pred:expr, $($cfg_rhs:tt)*) $(, $($attr_rest:tt)+)?) => {
66        #[cfg($cfg_pred)]
67        {
68            $crate::thread::local_impl::thread_local_inner!(@align $final_align, $($cfg_rhs)*);
69        }
70
71        $($crate::thread::local_impl::thread_local_inner!(@align $final_align, $($attr_rest)+);)?
72    },
73}
74
75/// Use a regular global static to store this key; the state provided will then be
76/// thread-local.
77/// INVARIANT: ALIGN must be a valid alignment, and no less than `value_align::<T>`.
78#[allow(missing_debug_implementations)]
79pub struct Storage<T, const ALIGN: usize> {
80    key: LazyKey,
81    marker: PhantomData<Cell<T>>,
82}
83
84unsafe impl<T, const ALIGN: usize> Sync for Storage<T, ALIGN> {}
85
86#[repr(C)]
87struct Value<T: 'static> {
88    // This field must be first, for correctness of `#[rustc_align_static]`
89    value: T,
90    // INVARIANT: if this value is stored under a TLS key, `key` must be that `key`.
91    key: Key,
92}
93
94pub const fn value_align<T: 'static>() -> usize {
95    crate::mem::align_of::<Value<T>>()
96}
97
98/// Equivalent to `Box<Value<T>, System>`, but potentially over-aligned.
99struct AlignedSystemBox<T: 'static, const ALIGN: usize> {
100    ptr: NonNull<Value<T>>,
101}
102
103impl<T: 'static, const ALIGN: usize> AlignedSystemBox<T, ALIGN> {
104    #[inline]
105    fn new(v: Value<T>) -> Self {
106        let layout = rtunwrap!(Ok, Layout::new::<Value<T>>().align_to(ALIGN));
107
108        // We use the System allocator here to avoid interfering with a potential
109        // Global allocator using thread-local storage.
110        let ptr: *mut Value<T> = (unsafe { System.alloc(layout) }).cast();
111        let Some(ptr) = NonNull::new(ptr) else {
112            // Do not call the alloc error hook here. It may allocate!
113            rtabort!("Allocation failure");
114        };
115        unsafe { ptr.write(v) };
116        Self { ptr }
117    }
118
119    #[inline]
120    fn into_raw(b: Self) -> *mut Value<T> {
121        let md = ManuallyDrop::new(b);
122        md.ptr.as_ptr()
123    }
124
125    #[inline]
126    unsafe fn from_raw(ptr: *mut Value<T>) -> Self {
127        Self { ptr: unsafe { NonNull::new_unchecked(ptr) } }
128    }
129}
130
131impl<T: 'static, const ALIGN: usize> Deref for AlignedSystemBox<T, ALIGN> {
132    type Target = Value<T>;
133
134    #[inline]
135    fn deref(&self) -> &Self::Target {
136        unsafe { &*(self.ptr.as_ptr()) }
137    }
138}
139
140impl<T: 'static, const ALIGN: usize> Drop for AlignedSystemBox<T, ALIGN> {
141    #[inline]
142    fn drop(&mut self) {
143        let layout = rtunwrap!(Ok, Layout::new::<Value<T>>().align_to(ALIGN));
144
145        unsafe {
146            let unwind_result = catch_unwind(AssertUnwindSafe(|| self.ptr.drop_in_place()));
147            System.dealloc(self.ptr.as_ptr().cast(), layout);
148            if let Err(payload) = unwind_result {
149                resume_unwind(payload);
150            }
151        }
152    }
153}
154
155impl<T: 'static, const ALIGN: usize> Storage<T, ALIGN> {
156    pub const fn new() -> Storage<T, ALIGN> {
157        Storage { key: LazyKey::new(Some(destroy_value::<T, ALIGN>)), marker: PhantomData }
158    }
159
160    /// Gets a pointer to the TLS value, potentially initializing it with the
161    /// provided parameters. If the TLS variable has been destroyed, a null
162    /// pointer is returned.
163    ///
164    /// The resulting pointer may not be used after reentrant inialialization
165    /// or thread destruction has occurred.
166    #[inline]
167    pub fn get(&'static self, i: Option<&mut Option<T>>, f: impl FnOnce() -> T) -> *const T {
168        let key = self.key.force();
169        let ptr = unsafe { get(key) as *mut Value<T> };
170        if ptr.addr() > 1 {
171            // SAFETY: the check ensured the pointer is safe (its destructor
172            // is not running) + it is coming from a trusted source (self).
173            unsafe { &(*ptr).value }
174        } else {
175            // SAFETY: trivially correct.
176            unsafe { Self::try_initialize(key, ptr, i, f) }
177        }
178    }
179
180    /// # Safety
181    /// * `key` must be the result of calling `self.key.force()`
182    /// * `ptr` must be the current value associated with `key`.
183    #[cold]
184    unsafe fn try_initialize(
185        key: Key,
186        ptr: *mut Value<T>,
187        i: Option<&mut Option<T>>,
188        f: impl FnOnce() -> T,
189    ) -> *const T {
190        if ptr.addr() == 1 {
191            // destructor is running
192            return ptr::null();
193        }
194
195        let value = AlignedSystemBox::<T, ALIGN>::new(Value {
196            value: i.and_then(Option::take).unwrap_or_else(f),
197            key,
198        });
199        let ptr = AlignedSystemBox::into_raw(value);
200
201        // SAFETY:
202        // * key came from a `LazyKey` and is thus correct.
203        // * `ptr` is a correct pointer that can be destroyed by the key destructor.
204        // * the value is stored under the key that it contains.
205        let old = unsafe {
206            let old = get(key) as *mut Value<T>;
207            set(key, ptr as *mut u8);
208            old
209        };
210
211        if !old.is_null() {
212            // If the variable was recursively initialized, drop the old value.
213            // SAFETY: We cannot be inside a `LocalKey::with` scope, as the
214            // initializer has already returned and the next scope only starts
215            // after we return the pointer. Therefore, there can be no references
216            // to the old value.
217            drop(unsafe { AlignedSystemBox::<T, ALIGN>::from_raw(old) });
218        }
219
220        // SAFETY: We just created this value above.
221        unsafe { &(*ptr).value }
222    }
223}
224
225unsafe extern "C" fn destroy_value<T: 'static, const ALIGN: usize>(ptr: *mut u8) {
226    // SAFETY:
227    //
228    // The OS TLS ensures that this key contains a null value when this
229    // destructor starts to run. We set it back to a sentinel value of 1 to
230    // ensure that any future calls to `get` for this thread will return
231    // `None`.
232    //
233    // Note that to prevent an infinite loop we reset it back to null right
234    // before we return from the destructor ourselves.
235    abort_on_dtor_unwind(|| {
236        let ptr = unsafe { AlignedSystemBox::<T, ALIGN>::from_raw(ptr as *mut Value<T>) };
237        let key = ptr.key;
238        // SAFETY: `key` is the TLS key `ptr` was stored under.
239        unsafe { set(key, ptr::without_provenance_mut(1)) };
240        drop(ptr);
241        // SAFETY: `key` is the TLS key `ptr` was stored under.
242        unsafe { set(key, ptr::null_mut()) };
243        // Make sure that the runtime cleanup will be performed
244        // after the next round of TLS destruction.
245        guard::enable();
246    });
247}
248
249#[rustc_macro_transparency = "semiopaque"]
250pub(crate) macro local_pointer {
251    () => {},
252    ($vis:vis static $name:ident; $($rest:tt)*) => {
253        $vis static $name: $crate::sys::thread_local::LocalPointer = $crate::sys::thread_local::LocalPointer::__new();
254        $crate::sys::thread_local::local_pointer! { $($rest)* }
255    },
256}
257
258pub(crate) struct LocalPointer {
259    key: LazyKey,
260}
261
262impl LocalPointer {
263    pub const fn __new() -> LocalPointer {
264        LocalPointer { key: LazyKey::new(None) }
265    }
266
267    pub fn get(&'static self) -> *mut () {
268        unsafe { get(self.key.force()) as *mut () }
269    }
270
271    pub fn set(&'static self, p: *mut ()) {
272        unsafe { set(self.key.force(), p as *mut u8) }
273    }
274}