1 //! Implement thread-local storage.
3 use std::collections::btree_map::Entry as BTreeEntry;
4 use std::collections::hash_map::Entry as HashMapEntry;
5 use std::collections::BTreeMap;
9 use rustc_data_structures::fx::FxHashMap;
11 use rustc_target::abi::{HasDataLayout, Size};
12 use rustc_target::spec::abi::Abi;
16 pub type TlsKey = u128;
18 #[derive(Clone, Debug)]
19 pub struct TlsEntry<'tcx> {
20 /// The data for this key. None is used to represent NULL.
21 /// (We normalize this early to avoid having to do a NULL-ptr-test each time we access the data.)
22 data: BTreeMap<ThreadId, Scalar<Tag>>,
23 dtor: Option<ty::Instance<'tcx>>,
26 #[derive(Clone, Debug)]
27 struct RunningDtorsState {
28 /// The last TlsKey used to retrieve a TLS destructor. `None` means that we
29 /// have not tried to retrieve a TLS destructor yet or that we already tried
31 last_dtor_key: Option<TlsKey>,
35 pub struct TlsData<'tcx> {
36 /// The Key to use for the next thread-local allocation.
39 /// pthreads-style thread-local storage.
40 keys: BTreeMap<TlsKey, TlsEntry<'tcx>>,
42 /// A single per thread destructor of the thread local storage (that's how
43 /// things work on macOS) with a data argument.
44 macos_thread_dtors: BTreeMap<ThreadId, (ty::Instance<'tcx>, Scalar<Tag>)>,
46 /// State for currently running TLS dtors. If this map contains a key for a
47 /// specific thread, it means that we are in the "destruct" phase, during
48 /// which some operations are UB.
49 dtors_running: FxHashMap<ThreadId, RunningDtorsState>,
52 impl<'tcx> Default for TlsData<'tcx> {
53 fn default() -> Self {
55 next_key: 1, // start with 1 as we must not use 0 on Windows
56 keys: Default::default(),
57 macos_thread_dtors: Default::default(),
58 dtors_running: Default::default(),
63 impl<'tcx> TlsData<'tcx> {
64 /// Generate a new TLS key with the given destructor.
65 /// `max_size` determines the integer size the key has to fit in.
66 pub fn create_tls_key(
68 dtor: Option<ty::Instance<'tcx>>,
70 ) -> InterpResult<'tcx, TlsKey> {
71 let new_key = self.next_key;
73 self.keys.try_insert(new_key, TlsEntry { data: Default::default(), dtor }).unwrap();
74 trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
76 if max_size.bits() < 128 && new_key >= (1u128 << max_size.bits() as u128) {
77 throw_unsup_format!("we ran out of TLS key space");
82 pub fn delete_tls_key(&mut self, key: TlsKey) -> InterpResult<'tcx> {
83 match self.keys.remove(&key) {
85 trace!("TLS key {} removed", key);
88 None => throw_ub_format!("removing a non-existig TLS key: {}", key),
96 cx: &impl HasDataLayout,
97 ) -> InterpResult<'tcx, Scalar<Tag>> {
98 match self.keys.get(&key) {
99 Some(TlsEntry { data, .. }) => {
100 let value = data.get(&thread_id).copied();
101 trace!("TLS key {} for thread {:?} loaded: {:?}", key, thread_id, value);
102 Ok(value.unwrap_or_else(|| Scalar::null_ptr(cx).into()))
104 None => throw_ub_format!("loading from a non-existing TLS key: {}", key),
112 new_data: Option<Scalar<Tag>>,
113 ) -> InterpResult<'tcx> {
114 match self.keys.get_mut(&key) {
115 Some(TlsEntry { data, .. }) => {
118 trace!("TLS key {} for thread {:?} stored: {:?}", key, thread_id, scalar);
119 data.insert(thread_id, scalar);
122 trace!("TLS key {} for thread {:?} removed", key, thread_id);
123 data.remove(&thread_id);
128 None => throw_ub_format!("storing to a non-existing TLS key: {}", key),
132 /// Set the thread wide destructor of the thread local storage for the given
133 /// thread. This function is used to implement `_tlv_atexit` shim on MacOS.
135 /// Thread wide dtors are available only on MacOS. There is one destructor
136 /// per thread as can be guessed from the following comment in the
138 /// implementation](https://github.com/opensource-apple/dyld/blob/195030646877261f0c8c7ad8b001f52d6a26f514/src/threadLocalVariables.c#L389):
140 /// // NOTE: this does not need locks because it only operates on current thread data
141 pub fn set_macos_thread_dtor(
144 dtor: ty::Instance<'tcx>,
146 ) -> InterpResult<'tcx> {
147 if self.dtors_running.contains_key(&thread) {
148 // UB, according to libstd docs.
150 "setting thread's local storage destructor while destructors are already running"
153 if self.macos_thread_dtors.insert(thread, (dtor, data)).is_some() {
155 "setting more than one thread local storage destructor for the same thread is not supported"
161 /// Returns a dtor, its argument and its index, if one is supposed to run.
162 /// `key` is the last dtors that was run; we return the *next* one after that.
164 /// An optional destructor function may be associated with each key value.
165 /// At thread exit, if a key value has a non-NULL destructor pointer,
166 /// and the thread has a non-NULL value associated with that key,
167 /// the value of the key is set to NULL, and then the function pointed
168 /// to is called with the previously associated value as its sole argument.
169 /// The order of destructor calls is unspecified if more than one destructor
170 /// exists for a thread when it exits.
172 /// If, after all the destructors have been called for all non-NULL values
173 /// with associated destructors, there are still some non-NULL values with
174 /// associated destructors, then the process is repeated.
175 /// If, after at least {PTHREAD_DESTRUCTOR_ITERATIONS} iterations of destructor
176 /// calls for outstanding non-NULL values, there are still some non-NULL values
177 /// with associated destructors, implementations may stop calling destructors,
178 /// or they may continue calling destructors until no non-NULL values with
179 /// associated destructors exist, even though this might result in an infinite loop.
184 ) -> Option<(ty::Instance<'tcx>, Scalar<Tag>, TlsKey)> {
185 use std::ops::Bound::*;
187 let thread_local = &mut self.keys;
188 let start = match key {
189 Some(key) => Excluded(key),
192 for (&key, TlsEntry { data, dtor }) in thread_local.range_mut((start, Unbounded)) {
193 match data.entry(thread_id) {
194 BTreeEntry::Occupied(entry) => {
195 if let Some(dtor) = dtor {
196 // Set TLS data to NULL, and call dtor with old value.
197 let data_scalar = entry.remove();
198 let ret = Some((*dtor, data_scalar, key));
202 BTreeEntry::Vacant(_) => {}
208 /// Set that dtors are running for `thread`. It is guaranteed not to change
209 /// the existing values stored in `dtors_running` for this thread. Returns
210 /// `true` if dtors for `thread` are already running.
211 fn set_dtors_running_for_thread(&mut self, thread: ThreadId) -> bool {
212 match self.dtors_running.entry(thread) {
213 HashMapEntry::Occupied(_) => true,
214 HashMapEntry::Vacant(entry) => {
215 // We cannot just do `self.dtors_running.insert` because that
216 // would overwrite `last_dtor_key` with `None`.
217 entry.insert(RunningDtorsState { last_dtor_key: None });
223 /// Delete all TLS entries for the given thread. This function should be
224 /// called after all TLS destructors have already finished.
225 fn delete_all_thread_tls(&mut self, thread_id: ThreadId) {
226 for TlsEntry { data, .. } in self.keys.values_mut() {
227 data.remove(&thread_id);
232 impl<'mir, 'tcx: 'mir> EvalContextPrivExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
233 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
234 /// Schedule TLS destructors for the main thread on Windows. The
235 /// implementation assumes that we do not support concurrency on Windows
237 fn schedule_windows_tls_dtors(&mut self) -> InterpResult<'tcx> {
238 let this = self.eval_context_mut();
239 let active_thread = this.get_active_thread();
240 assert_eq!(this.get_total_thread_count(), 1, "concurrency on Windows is not supported");
241 // Windows has a special magic linker section that is run on certain events.
242 // Instead of searching for that section and supporting arbitrary hooks in there
243 // (that would be basically https://github.com/rust-lang/miri/issues/450),
244 // we specifically look up the static in libstd that we know is placed
246 let thread_callback = this.eval_path_scalar(&[
253 let thread_callback = this.memory.get_fn(thread_callback.check_init()?)?.as_instance()?;
255 // The signature of this function is `unsafe extern "system" fn(h: c::LPVOID, dwReason: c::DWORD, pv: c::LPVOID)`.
256 let reason = this.eval_path_scalar(&["std", "sys", "windows", "c", "DLL_THREAD_DETACH"])?;
257 let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
260 Abi::System { unwind: false },
261 &[Scalar::null_ptr(this).into(), reason.into(), Scalar::null_ptr(this).into()],
263 StackPopCleanup::None { cleanup: true },
266 this.enable_thread(active_thread);
270 /// Schedule the MacOS thread destructor of the thread local storage to be
271 /// executed. Returns `true` if scheduled.
273 /// Note: It is safe to call this function also on other Unixes.
274 fn schedule_macos_tls_dtor(&mut self) -> InterpResult<'tcx, bool> {
275 let this = self.eval_context_mut();
276 let thread_id = this.get_active_thread();
277 if let Some((instance, data)) = this.machine.tls.macos_thread_dtors.remove(&thread_id) {
278 trace!("Running macos dtor {:?} on {:?} at {:?}", instance, data, thread_id);
280 let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
283 Abi::C { unwind: false },
286 StackPopCleanup::None { cleanup: true },
289 // Enable the thread so that it steps through the destructor which
290 // we just scheduled. Since we deleted the destructor, it is
291 // guaranteed that we will schedule it again. The `dtors_running`
292 // flag will prevent the code from adding the destructor again.
293 this.enable_thread(thread_id);
300 /// Schedule a pthread TLS destructor. Returns `true` if found
301 /// a destructor to schedule, and `false` otherwise.
302 fn schedule_next_pthread_tls_dtor(&mut self) -> InterpResult<'tcx, bool> {
303 let this = self.eval_context_mut();
304 let active_thread = this.get_active_thread();
306 assert!(this.has_terminated(active_thread), "running TLS dtors for non-terminated thread");
307 // Fetch next dtor after `key`.
308 let last_key = this.machine.tls.dtors_running[&active_thread].last_dtor_key.clone();
309 let dtor = match this.machine.tls.fetch_tls_dtor(last_key, active_thread) {
310 dtor @ Some(_) => dtor,
311 // We ran each dtor once, start over from the beginning.
312 None => this.machine.tls.fetch_tls_dtor(None, active_thread),
314 if let Some((instance, ptr, key)) = dtor {
315 this.machine.tls.dtors_running.get_mut(&active_thread).unwrap().last_dtor_key =
317 trace!("Running TLS dtor {:?} on {:?} at {:?}", instance, ptr, active_thread);
318 assert!(!this.is_null(ptr).unwrap(), "data can't be NULL when dtor is called!");
320 let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
323 Abi::C { unwind: false },
326 StackPopCleanup::None { cleanup: true },
329 this.enable_thread(active_thread);
332 this.machine.tls.dtors_running.get_mut(&active_thread).unwrap().last_dtor_key = None;
338 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
339 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
340 /// Schedule an active thread's TLS destructor to run on the active thread.
341 /// Note that this function does not run the destructors itself, it just
342 /// schedules them one by one each time it is called and reenables the
343 /// thread so that it can be executed normally by the main execution loop.
345 /// Note: we consistently run TLS destructors for all threads, including the
346 /// main thread. However, it is not clear that we should run the TLS
347 /// destructors for the main thread. See issue:
348 /// https://github.com/rust-lang/rust/issues/28129.
349 fn schedule_next_tls_dtor_for_active_thread(&mut self) -> InterpResult<'tcx> {
350 let this = self.eval_context_mut();
351 let active_thread = this.get_active_thread();
353 if !this.machine.tls.set_dtors_running_for_thread(active_thread) {
354 // This is the first time we got asked to schedule a destructor. The
355 // Windows schedule destructor function must be called exactly once,
356 // this is why it is in this block.
357 if this.tcx.sess.target.os == "windows" {
358 // On Windows, we signal that the thread quit by starting the
359 // relevant function, reenabling the thread, and going back to
361 this.schedule_windows_tls_dtors()?;
365 // The remaining dtors make some progress each time around the scheduler loop,
366 // until they return `false` to indicate that they are done.
368 // The macOS thread wide destructor runs "before any TLS slots get
369 // freed", so do that first.
370 if this.schedule_macos_tls_dtor()? {
371 // We have scheduled a MacOS dtor to run on the thread. Execute it
372 // to completion and come back here. Scheduling a destructor
373 // destroys it, so we will not enter this branch again.
376 if this.schedule_next_pthread_tls_dtor()? {
377 // We have scheduled a pthread destructor and removed it from the
378 // destructors list. Run it to completion and come back here.
383 this.machine.tls.delete_all_thread_tls(active_thread);
384 this.thread_terminated()?;