std\sys\thread_local/
os.rs1use super::key::{Key, LazyKey, get, set};
2use super::{abort_on_dtor_unwind, guard};
3use crate::alloc::{self, 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 (@key $t:ty, $($(#[$($align_attr:tt)*])+)?, $init:expr) => {{
23 #[inline]
24 fn __rust_std_internal_init_fn() -> $t { $init }
25
26 unsafe {
30 $crate::thread::LocalKey::new(|__rust_std_internal_init| {
31 static __RUST_STD_INTERNAL_VAL: $crate::thread::local_impl::Storage<$t, {
32 $({
33 $(#[$($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 (@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 (@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#[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 value: T,
90 key: Key,
92}
93
94pub const fn value_align<T: 'static>() -> usize {
95 crate::mem::align_of::<Value<T>>()
96}
97
98struct 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 = Layout::new::<Value<T>>().align_to(ALIGN).unwrap();
107
108 let ptr: *mut Value<T> = (unsafe { System.alloc(layout) }).cast();
111 let Some(ptr) = NonNull::new(ptr) else {
112 alloc::handle_alloc_error(layout);
113 };
114 unsafe { ptr.write(v) };
115 Self { ptr }
116 }
117
118 #[inline]
119 fn into_raw(b: Self) -> *mut Value<T> {
120 let md = ManuallyDrop::new(b);
121 md.ptr.as_ptr()
122 }
123
124 #[inline]
125 unsafe fn from_raw(ptr: *mut Value<T>) -> Self {
126 Self { ptr: unsafe { NonNull::new_unchecked(ptr) } }
127 }
128}
129
130impl<T: 'static, const ALIGN: usize> Deref for AlignedSystemBox<T, ALIGN> {
131 type Target = Value<T>;
132
133 #[inline]
134 fn deref(&self) -> &Self::Target {
135 unsafe { &*(self.ptr.as_ptr()) }
136 }
137}
138
139impl<T: 'static, const ALIGN: usize> Drop for AlignedSystemBox<T, ALIGN> {
140 #[inline]
141 fn drop(&mut self) {
142 let layout = Layout::new::<Value<T>>().align_to(ALIGN).unwrap();
143
144 unsafe {
145 let unwind_result = catch_unwind(AssertUnwindSafe(|| self.ptr.drop_in_place()));
146 System.dealloc(self.ptr.as_ptr().cast(), layout);
147 if let Err(payload) = unwind_result {
148 resume_unwind(payload);
149 }
150 }
151 }
152}
153
154impl<T: 'static, const ALIGN: usize> Storage<T, ALIGN> {
155 pub const fn new() -> Storage<T, ALIGN> {
156 Storage { key: LazyKey::new(Some(destroy_value::<T, ALIGN>)), marker: PhantomData }
157 }
158
159 pub fn get(&'static self, i: Option<&mut Option<T>>, f: impl FnOnce() -> T) -> *const T {
166 let key = self.key.force();
167 let ptr = unsafe { get(key) as *mut Value<T> };
168 if ptr.addr() > 1 {
169 unsafe { &(*ptr).value }
172 } else {
173 unsafe { Self::try_initialize(key, ptr, i, f) }
175 }
176 }
177
178 unsafe fn try_initialize(
182 key: Key,
183 ptr: *mut Value<T>,
184 i: Option<&mut Option<T>>,
185 f: impl FnOnce() -> T,
186 ) -> *const T {
187 if ptr.addr() == 1 {
188 return ptr::null();
190 }
191
192 let value = AlignedSystemBox::<T, ALIGN>::new(Value {
193 value: i.and_then(Option::take).unwrap_or_else(f),
194 key,
195 });
196 let ptr = AlignedSystemBox::into_raw(value);
197
198 let old = unsafe {
203 let old = get(key) as *mut Value<T>;
204 set(key, ptr as *mut u8);
205 old
206 };
207
208 if !old.is_null() {
209 drop(unsafe { AlignedSystemBox::<T, ALIGN>::from_raw(old) });
215 }
216
217 unsafe { &(*ptr).value }
219 }
220}
221
222unsafe extern "C" fn destroy_value<T: 'static, const ALIGN: usize>(ptr: *mut u8) {
223 abort_on_dtor_unwind(|| {
233 let ptr = unsafe { AlignedSystemBox::<T, ALIGN>::from_raw(ptr as *mut Value<T>) };
234 let key = ptr.key;
235 unsafe { set(key, ptr::without_provenance_mut(1)) };
237 drop(ptr);
238 unsafe { set(key, ptr::null_mut()) };
240 guard::enable();
243 });
244}
245
246#[rustc_macro_transparency = "semiopaque"]
247pub(crate) macro local_pointer {
248 () => {},
249 ($vis:vis static $name:ident; $($rest:tt)*) => {
250 $vis static $name: $crate::sys::thread_local::LocalPointer = $crate::sys::thread_local::LocalPointer::__new();
251 $crate::sys::thread_local::local_pointer! { $($rest)* }
252 },
253}
254
255pub(crate) struct LocalPointer {
256 key: LazyKey,
257}
258
259impl LocalPointer {
260 pub const fn __new() -> LocalPointer {
261 LocalPointer { key: LazyKey::new(None) }
262 }
263
264 pub fn get(&'static self) -> *mut () {
265 unsafe { get(self.key.force()) as *mut () }
266 }
267
268 pub fn set(&'static self, p: *mut ()) {
269 unsafe { set(self.key.force(), p as *mut u8) }
270 }
271}