1use crate::cell::{Cell, UnsafeCell};
2use crate::mem::MaybeUninit;
3use crate::ptr;
4use crate::sys::thread_local::{abort_on_dtor_unwind, destructors};
56pub unsafe trait DestroyedState: Sized + Copy {
7fn register_dtor<T>(s: &Storage<T, Self>);
8}
910unsafe impl DestroyedStatefor ! {
11fn register_dtor<T>(_: &Storage<T, !>) {}
12}
1314unsafe impl DestroyedStatefor () {
15fn register_dtor<T>(s: &Storage<T, ()>) {
16unsafe {
17 destructors::register(ptr::from_ref(s).cast_mut().cast(), destroy::<T>);
18 }
19 }
20}
2122#[derive(#[automatically_derived]
impl<D: ::core::marker::Copy> ::core::marker::Copy for State<D> { }Copy, #[automatically_derived]
impl<D: ::core::clone::Clone> ::core::clone::Clone for State<D> {
#[inline]
fn clone(&self) -> State<D> {
match self {
State::Uninitialized => State::Uninitialized,
State::Alive => State::Alive,
State::Destroyed(__self_0) =>
State::Destroyed(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
23enum State<D> {
24 Uninitialized,
25 Alive,
26 Destroyed(D),
27}
2829#[allow(missing_debug_implementations)]
30#[repr(C)]
31pub struct Storage<T, D> {
32// This field must be first, for correctness of `#[rustc_align_static]`
33value: UnsafeCell<MaybeUninit<T>>,
34 state: Cell<State<D>>,
35}
3637impl<T, D> Storage<T, D>
38where
39D: DestroyedState,
40{
41pub const fn new() -> Storage<T, D> {
42Storage {
43 state: Cell::new(State::Uninitialized),
44 value: UnsafeCell::new(MaybeUninit::uninit()),
45 }
46 }
4748/// Gets a pointer to the TLS value, potentially initializing it with the
49 /// provided parameters. If the TLS variable has been destroyed, a null
50 /// pointer is returned.
51 ///
52 /// The resulting pointer may not be used after reentrant inialialization
53 /// or thread destruction has occurred.
54 ///
55 /// # Safety
56 /// The `self` reference must remain valid until the TLS destructor is run.
57#[inline]
58pub unsafe fn get_or_init(&self, i: Option<&mut Option<T>>, f: impl FnOnce() -> T) -> *const T {
59if let State::Alive = self.state.get() {
60self.value.get().cast()
61 } else {
62unsafe { self.get_or_init_slow(i, f) }
63 }
64 }
6566/// # Safety
67 /// The `self` reference must remain valid until the TLS destructor is run.
68#[cold]
69unsafe fn get_or_init_slow(
70&self,
71 i: Option<&mut Option<T>>,
72 f: impl FnOnce() -> T,
73 ) -> *const T {
74match self.state.get() {
75 State::Uninitialized => {}
76 State::Alive => return self.value.get().cast(),
77 State::Destroyed(_) => return ptr::null(),
78 }
7980let v = i.and_then(Option::take).unwrap_or_else(f);
8182// SAFETY: we cannot be inside a `LocalKey::with` scope, as the initializer
83 // has already returned and the next scope only starts after we return
84 // the pointer. Therefore, there can be no references to the old value,
85 // even if it was initialized. Thus because we are !Sync we have exclusive
86 // access to self.value and may replace it.
87let mut old_value = unsafe { self.value.get().replace(MaybeUninit::new(v)) };
88match self.state.replace(State::Alive) {
89// If the variable is not being recursively initialized, register
90 // the destructor. This might be a noop if the value does not need
91 // destruction.
92State::Uninitialized => D::register_dtor(self),
9394// Recursive initialization, we only need to drop the old value
95 // as we've already registered the destructor.
96State::Alive => unsafe { old_value.assume_init_drop() },
9798 State::Destroyed(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
99 }
100101self.value.get().cast()
102 }
103}
104105/// Transition an `Alive` TLS variable into the `Destroyed` state, dropping its
106/// value.
107///
108/// # Safety
109/// * Must only be called at thread destruction.
110/// * `ptr` must point to an instance of `Storage<T, ()>` and be valid for
111/// accessing that instance.
112unsafe extern "C" fn destroy<T>(ptr: *mut u8) {
113// Print a nice abort message if a panic occurs.
114abort_on_dtor_unwind(|| {
115let storage = unsafe { &*(ptras *const Storage<T, ()>) };
116if let State::Alive = storage.state.replace(State::Destroyed(())) {
117// SAFETY: we ensured the state was Alive so the value was initialized.
118 // We also updated the state to Destroyed to prevent the destructor
119 // from accessing the thread-local variable, as this would violate
120 // the exclusive access provided by &mut T in Drop::drop.
121unsafe { (*storage.value.get()).assume_init_drop() }
122 }
123 })
124}