Skip to main content

std\sys\thread_local\key/
windows.rs

1//! Implementation of `LazyKey` for Windows.
2//!
3//! Windows has no native support for running destructors so we manage our own
4//! list of destructors to keep track of how to destroy keys. We then install a
5//! callback later to get invoked whenever a thread exits, running all
6//! appropriate destructors (see the [`guard`](guard) module documentation).
7//!
8//! This will likely need to be improved over time, but this module attempts a
9//! "poor man's" destructor callback system. Once we've got a list of what to
10//! run, we iterate over all keys, check their values, and then run destructors
11//! if the values turn out to be non null (setting them to null just beforehand).
12//! We do this a few times in a loop to basically match Unix semantics. If we
13//! don't reach a fixed point after a short while then we just inevitably leak
14//! something.
15//!
16//! The list is implemented as an atomic single-linked list of `LazyKey`s and
17//! does not support unregistration. Unfortunately, this means that we cannot
18//! use racy initialization for creating the keys in `LazyKey`, as that could
19//! result in destructors being missed. Hence, we synchronize the creation of
20//! keys with destructors through [`INIT_ONCE`](c::INIT_ONCE) (`std`'s
21//! [`Once`](crate::sync::Once) cannot be used since it might use TLS itself).
22//! For keys without destructors, racy initialization suffices.
23
24// FIXME: investigate using a fixed-size array instead, as the maximum number
25//        of keys is [limited to 1088](https://learn.microsoft.com/en-us/windows/win32/ProcThread/thread-local-storage).
26
27use crate::cell::UnsafeCell;
28use crate::ptr;
29use crate::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release};
30use crate::sync::atomic::{Atomic, AtomicPtr, AtomicU32};
31use crate::sys::c;
32use crate::sys::thread_local::guard;
33
34pub type Key = u32;
35type Dtor = unsafe extern "C" fn(*mut u8);
36
37pub struct LazyKey {
38    /// The key value shifted up by one. Since TLS_OUT_OF_INDEXES == u32::MAX
39    /// is not a valid key value, this allows us to use zero as sentinel value
40    /// without risking overflow.
41    key: Atomic<Key>,
42    dtor: Option<Dtor>,
43    next: Atomic<*mut LazyKey>,
44    /// Currently, destructors cannot be unregistered, so we cannot use racy
45    /// initialization for keys. Instead, we need synchronize initialization.
46    /// Use the Windows-provided `Once` since it does not require TLS.
47    once: UnsafeCell<c::INIT_ONCE>,
48}
49
50#[cold]
51fn fail() -> ! {
52    rtabort!("Unexpected TLS failure")
53}
54
55impl LazyKey {
56    #[inline]
57    pub const fn new(dtor: Option<Dtor>) -> LazyKey {
58        LazyKey {
59            key: AtomicU32::new(0),
60            dtor,
61            next: AtomicPtr::new(ptr::null_mut()),
62            once: UnsafeCell::new(c::INIT_ONCE_STATIC_INIT),
63        }
64    }
65
66    #[inline]
67    pub fn force(&'static self) -> Key {
68        if self.dtor.is_some() {
69            // Needs to be called on all threads where the key might have a non-null value!
70            // Otherwise, `run_dtors` might not be called on this thread.
71            guard::enable();
72        }
73
74        match self.key.load(Acquire).checked_sub(1) {
75            None => unsafe { self.init() },
76            Some(dec) => dec,
77        }
78    }
79
80    #[cold]
81    unsafe fn init(&'static self) -> Key {
82        if self.dtor.is_some() {
83            let mut pending = c::FALSE;
84            let r = unsafe {
85                c::InitOnceBeginInitialize(self.once.get(), 0, &mut pending, ptr::null_mut())
86            };
87            if r != c::TRUE {
88                fail()
89            }
90
91            if pending == c::FALSE {
92                // Some other thread initialized the key, load it.
93                self.key.load(Relaxed).wrapping_sub(1)
94            } else {
95                let key = unsafe { c::TlsAlloc() };
96                if key == c::TLS_OUT_OF_INDEXES {
97                    // Since we abort the process, there is no need to wake up
98                    // the waiting threads. If this were a panic, the wakeup
99                    // would need to occur first in order to avoid deadlock.
100                    rtabort!("out of TLS indexes");
101                }
102
103                unsafe {
104                    // Add ourselves to the `DTORS` list, so that when `run_dtors` gets called,
105                    // our dtor is invoked.
106                    register_dtor(self);
107                }
108
109                // Release-storing the key needs to be the last thing we do.
110                // This is because in `fn key()`, other threads will do an acquire load of the key,
111                // and if that sees this write then it will entirely bypass the `InitOnce`. We thus
112                // need to establish synchronization through `key`. In particular that acquire load
113                // must happen-after the register_dtor above, to ensure the dtor actually runs!
114                self.key.store(key.wrapping_add(1), Release);
115
116                let r = unsafe { c::InitOnceComplete(self.once.get(), 0, ptr::null_mut()) };
117                if r != c::TRUE {
118                    fail()
119                }
120
121                key
122            }
123        } else {
124            // If there is no destructor to clean up, we can use racy initialization.
125
126            let key = unsafe { c::TlsAlloc() };
127            if key == c::TLS_OUT_OF_INDEXES {
128                rtabort!("out of TLS indexes");
129            }
130
131            match self.key.compare_exchange(0, key.wrapping_add(1), AcqRel, Acquire) {
132                Ok(_) => key,
133                Err(new) => unsafe {
134                    // Some other thread completed initialization first, so destroy
135                    // our key and use theirs.
136                    let r = c::TlsFree(key);
137                    if r != c::TRUE {
138                        fail()
139                    }
140                    new.wrapping_sub(1)
141                },
142            }
143        }
144    }
145}
146
147unsafe impl Send for LazyKey {}
148unsafe impl Sync for LazyKey {}
149
150#[inline]
151pub unsafe fn set(key: Key, val: *mut u8) {
152    let r = unsafe { c::TlsSetValue(key, val.cast()) };
153    // According to MS documentation, `TlsSetValue` returns zero "if it fails"
154    if r != c::TRUE {
155        fail()
156    }
157}
158
159#[inline]
160pub unsafe fn get(key: Key) -> *mut u8 {
161    unsafe { c::TlsGetValue(key).cast() }
162}
163
164static DTORS: Atomic<*mut LazyKey> = AtomicPtr::new(ptr::null_mut());
165
166/// Should only be called once per key, otherwise loops or breaks may occur in
167/// the linked list.
168unsafe fn register_dtor(key: &'static LazyKey) {
169    let this = <*const LazyKey>::cast_mut(key);
170    // Use acquire ordering to pass along the changes done by the previously
171    // registered keys when we store the new head with release ordering.
172    let mut head = DTORS.load(Acquire);
173    loop {
174        key.next.store(head, Relaxed);
175        match DTORS.compare_exchange_weak(head, this, Release, Acquire) {
176            Ok(_) => break,
177            Err(new) => head = new,
178        }
179    }
180}
181
182/// This will and must only be run by the destructor callback in [`guard`].
183pub unsafe fn run_dtors() {
184    for _ in 0..5 {
185        let mut any_run = false;
186
187        // Use acquire ordering to observe key initialization.
188        let mut cur = DTORS.load(Acquire);
189        while !cur.is_null() {
190            let pre_key = unsafe { (*cur).key.load(Acquire) };
191            let dtor = unsafe { rtunwrap!(Some, (*cur).dtor) };
192            cur = unsafe { (*cur).next.load(Relaxed) };
193
194            // In LazyKey::init, we register the dtor before setting `key`.
195            // So if one thread's `run_dtors` races with another thread executing `init` on the same
196            // `LazyKey`, we can encounter a key of 0 here. That means this key was never
197            // initialized in this thread so we can safely skip it.
198            let Some(key) = pre_key.checked_sub(1) else {
199                continue;
200            };
201
202            // If this is non-zero, then via the `Acquire` load above we synchronized with
203            // everything relevant for this key. (It's not clear that this is needed, since the
204            // release-acquire pair on DTORS also establishes synchronization, but better safe than
205            // sorry.)
206            let ptr = unsafe { c::TlsGetValue(key) };
207            if !ptr.is_null() {
208                unsafe {
209                    c::TlsSetValue(key, ptr::null_mut());
210                    dtor(ptr as *mut _);
211                    any_run = true;
212                }
213            }
214        }
215
216        if !any_run {
217            break;
218        }
219    }
220}