miri/shims/tls.rs
1//! Implement thread-local storage.
2
3use std::collections::btree_map::Entry as BTreeEntry;
4use std::collections::{BTreeMap, VecDeque};
5use std::task::Poll;
6
7use rustc_abi::{ExternAbi, Size};
8use rustc_middle::ty;
9use rustc_span::Span;
10use rustc_target::spec::Os;
11
12use crate::*;
13
14pub type TlsKey = u64;
15
16#[derive(Clone, Debug)]
17pub struct TlsEntry<'tcx> {
18 /// The data for this key. Absence of data for a thread ID is used to represent NULL.
19 /// (We normalize this early to avoid having to do a NULL-ptr-test each time we access the data.)
20 pub data: BTreeMap<ThreadId, Pointer>,
21 pub dtor: Option<(ty::Instance<'tcx>, Span)>,
22}
23
24#[derive(Default, Debug)]
25struct RunningPthreadDtorState {
26 /// The last TlsKey used to retrieve a TLS destructor. `None` means that we
27 /// have not tried to retrieve a TLS destructor yet or that we already tried
28 /// all keys.
29 last_key: Option<TlsKey>,
30}
31
32#[derive(Default, Debug)]
33struct RunningWindowsDtorState {
34 /// The last TlsKey for which a TLS (really, FLS) destructor ran. `None` means that we
35 /// have not run a TLS destructor yet. This is used to clear the TLS value after the dtor returned.
36 last_key: Option<TlsKey>,
37 // Keys that have destructors that we still need to run.
38 remaining_keys: VecDeque<TlsKey>,
39}
40
41#[derive(Debug)]
42pub struct TlsData<'tcx> {
43 /// The Key to use for the next thread-local allocation.
44 next_key: TlsKey,
45
46 /// pthreads-style thread-local storage.
47 keys: BTreeMap<TlsKey, TlsEntry<'tcx>>,
48
49 /// Linux and macOS allow registering callbacks that are run when the current thread exits.
50 thread_atexit: BTreeMap<ThreadId, Vec<(ty::Instance<'tcx>, Scalar, Span)>>,
51}
52
53impl<'tcx> Default for TlsData<'tcx> {
54 fn default() -> Self {
55 TlsData {
56 next_key: 1, // start with 1 as we must not use 0 on Windows
57 keys: Default::default(),
58 thread_atexit: Default::default(),
59 }
60 }
61}
62
63impl<'tcx> TlsData<'tcx> {
64 /// Generate a new TLS key with the given destructor.
65 /// `key_size` determines the integer size the key has to fit in.
66 pub fn create_tls_key(
67 &mut self,
68 dtor: Option<(ty::Instance<'tcx>, Span)>,
69 key_size: Size,
70 ) -> InterpResult<'tcx, TlsKey> {
71 let new_key = self.next_key;
72 self.next_key = self.next_key.strict_add(1);
73 self.keys.try_insert(new_key, TlsEntry { data: Default::default(), dtor }).unwrap();
74 trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
75
76 if u128::from(new_key) > key_size.unsigned_int_max() {
77 throw_unsup_format!("we ran out of TLS key space");
78 }
79 interp_ok(new_key)
80 }
81
82 pub fn delete_tls_key(&mut self, key: TlsKey) -> InterpResult<'tcx, TlsEntry<'tcx>> {
83 match self.keys.remove(&key) {
84 Some(entry) => {
85 trace!("TLS key {} removed", key);
86 interp_ok(entry)
87 }
88 None => throw_ub_format!("removing a nonexistent TLS key: {}", key),
89 }
90 }
91
92 pub fn load_tls_key(&self, key: TlsKey, thread_id: ThreadId) -> InterpResult<'tcx, Pointer> {
93 match self.keys.get(&key) {
94 Some(TlsEntry { data, .. }) => {
95 let value = data.get(&thread_id).copied();
96 trace!("TLS key {} for thread {:?} loaded: {:?}", key, thread_id, value);
97 interp_ok(value.unwrap_or_else(Pointer::null))
98 }
99 None => throw_ub_format!("loading from a non-existing TLS key: {}", key),
100 }
101 }
102
103 pub fn store_tls_key(
104 &mut self,
105 key: TlsKey,
106 thread_id: ThreadId,
107 new_data: Pointer,
108 ) -> InterpResult<'tcx> {
109 match self.keys.get_mut(&key) {
110 Some(TlsEntry { data, .. }) => {
111 if new_data.addr() != Size::ZERO {
112 trace!("TLS key {} for thread {:?} stored: {:?}", key, thread_id, new_data);
113 data.insert(thread_id, new_data);
114 } else {
115 trace!("TLS key {} for thread {:?} removed", key, thread_id);
116 data.remove(&thread_id);
117 }
118 interp_ok(())
119 }
120 None => throw_ub_format!("storing to a non-existing TLS key: {}", key),
121 }
122 }
123
124 /// Add a thread local storage destructor for the given thread. This function
125 /// is used to implement the `_tlv_atexit` shim on MacOS.
126 pub fn add_thread_atexit(
127 &mut self,
128 thread: ThreadId,
129 dtor: ty::Instance<'tcx>,
130 data: Scalar,
131 span: Span,
132 ) -> InterpResult<'tcx> {
133 self.thread_atexit.entry(thread).or_default().push((dtor, data, span));
134 interp_ok(())
135 }
136
137 /// Returns a dtor, its argument and its index, if one is supposed to run.
138 /// `key` is the last dtors that was run; we return the *next* one after that.
139 ///
140 /// An optional destructor function may be associated with each key value.
141 /// At thread exit, if a key value has a non-NULL destructor pointer,
142 /// and the thread has a non-NULL value associated with that key,
143 /// the value of the key is set to NULL, and then the function pointed
144 /// to is called with the previously associated value as its sole argument.
145 /// **The order of destructor calls is unspecified if more than one destructor
146 /// exists for a thread when it exits.**
147 ///
148 /// If, after all the destructors have been called for all non-NULL values
149 /// with associated destructors, there are still some non-NULL values with
150 /// associated destructors, then the process is repeated.
151 /// If, after at least {PTHREAD_DESTRUCTOR_ITERATIONS} iterations of destructor
152 /// calls for outstanding non-NULL values, there are still some non-NULL values
153 /// with associated destructors, implementations may stop calling destructors,
154 /// or they may continue calling destructors until no non-NULL values with
155 /// associated destructors exist, even though this might result in an infinite loop.
156 fn fetch_tls_key_dtor(
157 &mut self,
158 key: Option<TlsKey>,
159 thread_id: ThreadId,
160 ) -> Option<(ty::Instance<'tcx>, Pointer, TlsKey, Span)> {
161 use std::ops::Bound::*;
162
163 let thread_local = &mut self.keys;
164 let start = match key {
165 Some(key) => Excluded(key),
166 None => Unbounded,
167 };
168 // We interpret the documentation above (taken from POSIX) as saying that we need to iterate
169 // over all keys and run each destructor at least once before running any destructor a 2nd
170 // time. That's why we have `key` to indicate how far we got in the current iteration. If we
171 // return `None`, `schedule_next_pthread_tls_dtor` will re-try with `ket` set to `None` to
172 // start the next round.
173 // TODO: In the future, we might consider randomizing destructor order, but we still have to
174 // uphold this requirement.
175 for (&key, TlsEntry { data, dtor }) in thread_local.range_mut((start, Unbounded)) {
176 match data.entry(thread_id) {
177 BTreeEntry::Occupied(entry) => {
178 if let Some((dtor, span)) = dtor {
179 // Set TLS data to NULL, and call dtor with old value.
180 let data = entry.remove();
181 return Some((*dtor, data, key, *span));
182 }
183 }
184 BTreeEntry::Vacant(_) => {}
185 }
186 }
187 None
188 }
189
190 /// Delete all TLS entries for the given thread. This function should be
191 /// called after all TLS destructors have already finished.
192 fn delete_all_thread_tls_keys(&mut self, thread_id: ThreadId) {
193 for TlsEntry { data, .. } in self.keys.values_mut() {
194 data.remove(&thread_id);
195 }
196
197 if let Some(dtors) = self.thread_atexit.remove(&thread_id) {
198 assert!(dtors.is_empty(), "the destructors should have already been run");
199 }
200 }
201
202 pub fn leak_all_thread_tls_keys(&self, thread_id: ThreadId, static_roots: &mut Vec<AllocId>) {
203 for TlsEntry { data, .. } in self.keys.values() {
204 if let Some(ptr) = data.get(&thread_id) {
205 if let Some(alloc) = ptr.provenance.and_then(|p| p.get_alloc_id()) {
206 trace!("Thread-local key value leaked and stored as static root: {:?}", alloc);
207 static_roots.push(alloc);
208 }
209 }
210 }
211 }
212}
213
214impl VisitProvenance for TlsData<'_> {
215 fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
216 let TlsData { keys, thread_atexit: macos_thread_dtors, next_key: _ } = self;
217
218 for scalar in keys.values().flat_map(|v| v.data.values()) {
219 scalar.visit_provenance(visit);
220 }
221 for (_, scalar, _) in macos_thread_dtors.values().flatten() {
222 scalar.visit_provenance(visit);
223 }
224 }
225}
226
227#[derive(Debug)]
228pub struct TlsDtorsState<'tcx> {
229 state: TlsDtorsStatePriv<'tcx>,
230 /// Whether this is for program exit vs thread finish.
231 for_exit: bool,
232}
233
234#[derive(Debug)]
235enum TlsDtorsStatePriv<'tcx> {
236 Init,
237 /// Running native thread destructors (`TlsData::thread_atexit`).
238 ThreadAtexit,
239 /// Running pthread key destructors.
240 PthreadDtors(RunningPthreadDtorState),
241 /// For Windows, we support two different ways dtors can be registered.
242 /// 1. Functions that are registered via the `FlsAlloc` function, which are invoked one by one.
243 /// 2. Functions from the magic `.CRT$XLB` linker section.
244 /// We store these as a list of functions that we still have to call.
245 WindowsDtors(RunningWindowsDtorState, Vec<(ImmTy<'tcx>, Span)>),
246 Done,
247}
248
249impl<'tcx> TlsDtorsState<'tcx> {
250 /// Returns the state we should start running when the program is exiting.
251 pub fn new_for_exit() -> Self {
252 Self { state: TlsDtorsStatePriv::Init, for_exit: true }
253 }
254
255 /// Returns the state we should start running when a thread finished running.
256 pub fn new_for_thread_finish() -> Self {
257 Self { state: TlsDtorsStatePriv::Init, for_exit: false }
258 }
259
260 pub fn on_stack_empty(&mut self, ecx: &mut MiriInterpCx<'tcx>) -> InterpResult<'tcx, Poll<()>> {
261 use TlsDtorsStatePriv::*;
262 let new_state = 'new_state: {
263 match &mut self.state {
264 Init => {
265 break 'new_state ThreadAtexit;
266 }
267 ThreadAtexit => {
268 let Poll::Ready(()) = ecx.schedule_thread_atexit()? else {
269 return interp_ok(Poll::Pending);
270 };
271 // Native thread_atexit handlers are done.
272 // What's next? Depends on the target!
273 match ecx.tcx.sess.target.os {
274 _ if ecx.target_os_is_unix() => {
275 // On thread finish, we run pthread dtors. But not on exit!
276 if self.for_exit {
277 // Leak pthread dtor contents, like thread-local statics.
278 ecx.machine.tls.leak_all_thread_tls_keys(
279 ecx.active_thread(),
280 &mut ecx.machine.static_roots,
281 );
282 break 'new_state Done;
283 } else {
284 break 'new_state PthreadDtors(Default::default());
285 }
286 }
287 Os::Windows => {
288 // Determine which destructors to run.
289 let dtors = ecx.lookup_windows_tls_dtors()?;
290
291 // Fetch fls keys that have destructors. Keys registered during thread
292 // exit may or may not have their destructor called. We decide not to
293 // call them. See also: `schedule_next_windows_fls_dtor`.
294 let fls_keys_with_dtors = ecx.lookup_windows_fls_keys_with_dtors()?;
295
296 // And move to the next state, that runs them.
297 break 'new_state WindowsDtors(
298 RunningWindowsDtorState {
299 last_key: None,
300 remaining_keys: fls_keys_with_dtors,
301 },
302 dtors,
303 );
304 }
305 _ => {
306 break 'new_state Done;
307 }
308 }
309 }
310 PthreadDtors(state) => {
311 let Poll::Ready(()) = ecx.schedule_next_pthread_tls_dtor(state)? else {
312 return interp_ok(Poll::Pending);
313 };
314 break 'new_state Done;
315 }
316 WindowsDtors(state, dtors) => {
317 // Fls destructors are scheduled before the tls callback.
318 let Poll::Ready(()) = ecx.schedule_next_windows_fls_dtor(state)? else {
319 return interp_ok(Poll::Pending);
320 };
321
322 // See if there's another callback to run
323 if let Some((dtor, span)) = dtors.pop() {
324 ecx.schedule_windows_tls_dtor(dtor, span)?;
325 return interp_ok(Poll::Pending); // we stay in this state (but `dtors` got shorter)
326 } else {
327 // No more destructors to run.
328 break 'new_state Done;
329 }
330 }
331 Done => {
332 // All destructors are called. Clean up remaining keys so they don't linger in
333 // the interpreter state.
334 ecx.machine.tls.delete_all_thread_tls_keys(ecx.active_thread());
335 return interp_ok(Poll::Ready(()));
336 }
337 }
338 };
339
340 self.state = new_state;
341 interp_ok(Poll::Pending)
342 }
343}
344
345impl<'tcx> EvalContextPrivExt<'tcx> for crate::MiriInterpCx<'tcx> {}
346trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
347 /// Schedule TLS destructors for Windows.
348 /// On windows, TLS destructors are managed by std.
349 fn lookup_windows_tls_dtors(&mut self) -> InterpResult<'tcx, Vec<(ImmTy<'tcx>, Span)>> {
350 let ecx = self.eval_context_mut();
351
352 // Windows has a special magic linker section that is run on certain events.
353 // We don't support most of that, but just enough to make thread-local dtors in `std` work.
354 interp_ok(ecx.lookup_link_section(|section| section == ".CRT$XLB")?)
355 }
356
357 /// Lookup all the FLS keys (which are stored as TLS keys) that have a destructor.
358 /// See also: `schedule_next_windows_fls_dtor`.
359 fn lookup_windows_fls_keys_with_dtors(&self) -> InterpResult<'tcx, VecDeque<TlsKey>> {
360 let ecx = self.eval_context_ref();
361
362 interp_ok(
363 ecx.machine
364 .tls
365 .keys
366 .iter()
367 .filter(|(_, data)| data.dtor.is_some())
368 .map(|(key, _)| *key)
369 .collect(),
370 )
371 }
372
373 fn schedule_windows_tls_dtor(&mut self, dtor: ImmTy<'tcx>, span: Span) -> InterpResult<'tcx> {
374 let ecx = self.eval_context_mut();
375
376 let dtor = dtor.to_scalar().to_pointer(ecx);
377 let thread_callback = ecx.get_ptr_fn(dtor)?.as_instance()?;
378
379 // FIXME: Technically, the reason should be `DLL_PROCESS_DETACH` when the main thread exits
380 // but std treats both the same.
381 let reason = ecx.eval_windows("c", "DLL_THREAD_DETACH");
382 let null_ptr =
383 ImmTy::from_scalar(Scalar::null_ptr(ecx), ecx.machine.layouts.unit_ptr_const);
384
385 // The signature of this function is `unsafe extern "system" fn(h: c::LPVOID, dwReason: c::DWORD, pv: c::LPVOID)`.
386 // FIXME: `h` should be a handle to the current module and what `pv` should be is unknown
387 // but both are ignored by std.
388 ecx.call_thread_root_function(
389 thread_callback,
390 ExternAbi::System { unwind: false },
391 &[null_ptr.clone(), ImmTy::from_scalar(reason, ecx.machine.layouts.u32), null_ptr],
392 None,
393 span,
394 )?;
395 interp_ok(())
396 }
397
398 /// Schedule the macOS thread local storage destructors to be executed.
399 fn schedule_thread_atexit(&mut self) -> InterpResult<'tcx, Poll<()>> {
400 let ecx = self.eval_context_mut();
401 let thread_id = ecx.active_thread();
402 // macOS keeps track of TLS destructors in a stack. If a destructor
403 // registers another destructor, it will be run next.
404 // See https://github.com/apple-oss-distributions/dyld/blob/d552c40cd1de105f0ec95008e0e0c0972de43456/dyld/DyldRuntimeState.cpp#L2277
405 let dtor = ecx.machine.tls.thread_atexit.get_mut(&thread_id).and_then(Vec::pop);
406 if let Some((instance, data, span)) = dtor {
407 trace!("Running thread_atexit hook {:?} on {:?} at {:?}", instance, data, thread_id);
408
409 ecx.call_thread_root_function(
410 instance,
411 ExternAbi::C { unwind: false },
412 &[ImmTy::from_scalar(data, ecx.machine.layouts.unit_ptr_mut)],
413 None,
414 span,
415 )?;
416
417 return interp_ok(Poll::Pending);
418 }
419
420 interp_ok(Poll::Ready(()))
421 }
422
423 /// Schedule a pthread TLS destructor. Returns `true` if found
424 /// a destructor to schedule, and `false` otherwise.
425 fn schedule_next_pthread_tls_dtor(
426 &mut self,
427 state: &mut RunningPthreadDtorState,
428 ) -> InterpResult<'tcx, Poll<()>> {
429 let ecx = self.eval_context_mut();
430 let active_thread = ecx.active_thread();
431
432 // Fetch next dtor after `key`.
433 let dtor = match ecx.machine.tls.fetch_tls_key_dtor(state.last_key, active_thread) {
434 dtor @ Some(_) => dtor,
435 // We ran each dtor once, start over from the beginning.
436 None => ecx.machine.tls.fetch_tls_key_dtor(None, active_thread),
437 };
438 if let Some((instance, ptr, key, span)) = dtor {
439 state.last_key = Some(key);
440 trace!("Running TLS dtor {:?} on {:?} at {:?}", instance, ptr, active_thread);
441 assert!(ptr.addr() != Size::ZERO, "data can't be NULL when dtor is called!");
442
443 ecx.call_thread_root_function(
444 instance,
445 ExternAbi::C { unwind: false },
446 &[ImmTy::from_scalar(
447 Scalar::from_maybe_pointer(ptr, ecx),
448 ecx.machine.layouts.unit_ptr_mut,
449 )],
450 None,
451 span,
452 )?;
453
454 return interp_ok(Poll::Pending);
455 }
456
457 interp_ok(Poll::Ready(()))
458 }
459
460 /// Schedule a Windows FLS destructor, if one is found.
461 fn schedule_next_windows_fls_dtor(
462 &mut self,
463 state: &mut RunningWindowsDtorState,
464 ) -> InterpResult<'tcx, Poll<()>> {
465 let ecx = self.eval_context_mut();
466 let active_thread = ecx.active_thread();
467
468 // According to [PflsCallbackFunction's docs],
469 // > If the FLS slot is in use, `FlsCallback`` is called on .. thread exit ..
470 // However, the exact order and semantics are not defined.
471 // We use the following implementation, which matches both observed behavior and
472 // Wine's implementation of the same logic in the [`RtlProcessFlsData`] function.
473 // 1. Fetch all the keys once (in `lookup_windows_fls_keys_with_dtors`).
474 // 2. Go over them one by one, in order, skipping keys without dtors.
475 // 3. Fetch the value associated with the key.
476 // 4. If it is non-zero, call the registered dtor.
477 // 5. After the dtor is called, clear the key's value, setting it to zero.
478 // New keys registered during thread exit can be ignored (but sometimes they do run
479 // natively, just not reliably), but values set before the dtor is scheduled are visible.
480 // Keys without dtors will not be set to zero.
481 // [PflsCallbackFunction's docs]: https://learn.microsoft.com/en-us/windows/win32/api/winnt/nc-winnt-pfls_callback_function
482 // [`RtlProcessFlsData`]: https://github.com/wine-mirror/wine/blob/wine-11.0/dlls/ntdll/thread.c#L679
483
484 // We are done running the previous key's destructor, so set it's value to zero.
485 if let Some(last_key) = state.last_key.take() {
486 if let Some(TlsEntry { data, .. }) = ecx.machine.tls.keys.get_mut(&last_key) {
487 data.remove(&active_thread);
488 };
489 }
490
491 while let Some(key) = state.remaining_keys.pop_front() {
492 // Fetch dtor for this `key`.
493 // If the key doesn't have a dtor or does not exist any more, move on to the next key.
494 let Some(TlsEntry { data, dtor: Some(dtor) }) = ecx.machine.tls.keys.get(&key) else {
495 continue;
496 };
497
498 let (instance, span) = dtor.to_owned();
499
500 // If the key has no value in this thread, move on to the next key.
501 let Some(&ptr) = data.get(&active_thread) else { continue };
502
503 assert!(
504 ptr.addr() != Size::ZERO,
505 "TLS key's value can't be null (should be absent instead)"
506 );
507
508 trace!("Running TLS dtor {:?} on {:?} at {:?}", instance, ptr, active_thread);
509
510 // We'll clear this key's value next time we are called.
511 state.last_key = Some(key);
512
513 ecx.call_thread_root_function(
514 instance,
515 ExternAbi::System { unwind: false },
516 &[ImmTy::from_scalar(
517 Scalar::from_maybe_pointer(ptr, ecx),
518 ecx.machine.layouts.unit_ptr_mut,
519 )],
520 None,
521 span,
522 )?;
523
524 return interp_ok(Poll::Pending);
525 }
526
527 // We are done scheduling all the keys.
528 interp_ok(Poll::Ready(()))
529 }
530}