1use crate::cell::{Cell, UnsafeCell};
2use crate::ptr::{self, drop_in_place};
3use crate::sys::thread_local::{abort_on_dtor_unwind, destructors};
45#[derive(#[automatically_derived]
impl ::core::clone::Clone for State {
#[inline]
fn clone(&self) -> State { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for State { }Copy)]
6enum State {
7 Alive = 0,
8 Unregistered,
9 Destroyed,
10}
1112#[allow(missing_debug_implementations)]
13#[repr(C)]
14pub struct Storage<T> {
15// This field must be first, for correctness of `#[rustc_align_static]`
16val: UnsafeCell<T>,
17 state: Cell<State>,
18}
1920impl<T> Storage<T> {
21pub const fn new(val: T) -> Storage<T> {
22Storage { state: Cell::new(State::Unregistered), val: UnsafeCell::new(val) }
23 }
2425/// Gets a pointer to the TLS value. If the TLS variable has been destroyed,
26 /// a null pointer is returned.
27 ///
28 /// The resulting pointer may not be used after thread destruction has
29 /// occurred.
30 ///
31 /// # Safety
32 /// The `self` reference must remain valid until the TLS destructor is run.
33#[inline]
34pub unsafe fn get(&self) -> *const T {
35if let State::Alive = self.state.get() {
36self.val.get()
37 } else {
38unsafe { self.get_or_init_slow() }
39 }
40 }
4142#[cold]
43unsafe fn get_or_init_slow(&self) -> *const T {
44match self.state.get() {
45 State::Unregistered => {}
46 State::Alive => return self.val.get(),
47 State::Destroyed => return ptr::null(),
48 }
4950// Register the destructor.
5152 // SAFETY:
53 // The caller guarantees that `self` will be valid until thread destruction.
54unsafe {
55 destructors::register(ptr::from_ref(self).cast_mut().cast(), destroy::<T>);
56 }
5758self.state.set(State::Alive);
59self.val.get()
60 }
61}
6263/// Transition an `Alive` TLS variable into the `Destroyed` state, dropping its
64/// value.
65///
66/// # Safety
67/// * Must only be called at thread destruction.
68/// * `ptr` must point to an instance of `Storage` with `Alive` state and be
69/// valid for accessing that instance.
70unsafe extern "C" fn destroy<T>(ptr: *mut u8) {
71// Print a nice abort message if a panic occurs.
72abort_on_dtor_unwind(|| {
73let storage = unsafe { &*(ptras *const Storage<T>) };
74// Update the state before running the destructor as it may attempt to
75 // access the variable.
76storage.state.set(State::Destroyed);
77unsafe {
78drop_in_place(storage.val.get());
79 }
80 })
81}