1 //! Implement thread-local storage.
3 use std::collections::BTreeMap;
4 use std::collections::btree_map::Entry;
9 use rustc_target::abi::{Size, HasDataLayout};
11 use crate::{HelpersEvalContextExt, ThreadsEvalContextExt, InterpResult, MPlaceTy, Scalar, StackPopCleanup, Tag};
12 use crate::machine::{ThreadId, ThreadState};
14 pub type TlsKey = u128;
16 #[derive(Clone, Debug)]
17 pub struct TlsEntry<'tcx> {
18 /// The data for this key. None 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 /// Will eventually become a map from thread IDs to `Scalar`s, if we ever support more than one thread.
21 data: BTreeMap<ThreadId, Scalar<Tag>>,
22 dtor: Option<ty::Instance<'tcx>>,
26 pub struct TlsData<'tcx> {
27 /// The Key to use for the next thread-local allocation.
30 /// pthreads-style thread-local storage.
31 keys: BTreeMap<TlsKey, TlsEntry<'tcx>>,
33 /// A single global dtor (that's how things work on macOS) with a data argument.
34 global_dtor: Option<(ty::Instance<'tcx>, Scalar<Tag>)>,
36 /// Whether we are in the "destruct" phase, during which some operations are UB.
40 impl<'tcx> Default for TlsData<'tcx> {
41 fn default() -> Self {
43 next_key: 1, // start with 1 as we must not use 0 on Windows
44 keys: Default::default(),
51 impl<'tcx> TlsData<'tcx> {
52 /// Generate a new TLS key with the given destructor.
53 /// `max_size` determines the integer size the key has to fit in.
54 pub fn create_tls_key(&mut self, dtor: Option<ty::Instance<'tcx>>, max_size: Size) -> InterpResult<'tcx, TlsKey> {
55 let new_key = self.next_key;
57 self.keys.insert(new_key, TlsEntry { data: Default::default(), dtor }).unwrap_none();
58 trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
60 if max_size.bits() < 128 && new_key >= (1u128 << max_size.bits() as u128) {
61 throw_unsup_format!("we ran out of TLS key space");
66 pub fn delete_tls_key(&mut self, key: TlsKey) -> InterpResult<'tcx> {
67 match self.keys.remove(&key) {
69 trace!("TLS key {} removed", key);
72 None => throw_ub_format!("removing a non-existig TLS key: {}", key),
80 cx: &impl HasDataLayout,
81 ) -> InterpResult<'tcx, Scalar<Tag>> {
82 match self.keys.get(&key) {
83 Some(TlsEntry { data, .. }) => {
84 let value = data.get(&thread_id).cloned();
85 trace!("TLS key {} for thread {:?} loaded: {:?}", key, thread_id, value);
86 Ok(value.unwrap_or_else(|| Scalar::null_ptr(cx).into()))
88 None => throw_ub_format!("loading from a non-existing TLS key: {}", key),
94 key: TlsKey, thread_id: ThreadId, new_data: Option<Scalar<Tag>>) -> InterpResult<'tcx> {
95 match self.keys.get_mut(&key) {
96 Some(TlsEntry { data, .. }) => {
99 trace!("TLS key {} for thread {:?} stored: {:?}", key, thread_id, ptr);
100 data.insert(thread_id, ptr);
103 trace!("TLS key {} for thread {:?} removed", key, thread_id);
104 data.remove(&thread_id);
109 None => throw_ub_format!("storing to a non-existing TLS key: {}", key),
113 pub fn set_global_dtor(&mut self, dtor: ty::Instance<'tcx>, data: Scalar<Tag>) -> InterpResult<'tcx> {
114 if self.dtors_running {
115 // UB, according to libstd docs.
116 throw_ub_format!("setting global destructor while destructors are already running");
118 if self.global_dtor.is_some() {
119 throw_unsup_format!("setting more than one global destructor is not supported");
122 self.global_dtor = Some((dtor, data));
126 /// Returns a dtor, its argument and its index, if one is supposed to run.
127 /// `key` is the last dtors that was run; we return the *next* one after that.
129 /// An optional destructor function may be associated with each key value.
130 /// At thread exit, if a key value has a non-NULL destructor pointer,
131 /// and the thread has a non-NULL value associated with that key,
132 /// the value of the key is set to NULL, and then the function pointed
133 /// to is called with the previously associated value as its sole argument.
134 /// The order of destructor calls is unspecified if more than one destructor
135 /// exists for a thread when it exits.
137 /// If, after all the destructors have been called for all non-NULL values
138 /// with associated destructors, there are still some non-NULL values with
139 /// associated destructors, then the process is repeated.
140 /// If, after at least {PTHREAD_DESTRUCTOR_ITERATIONS} iterations of destructor
141 /// calls for outstanding non-NULL values, there are still some non-NULL values
142 /// with associated destructors, implementations may stop calling destructors,
143 /// or they may continue calling destructors until no non-NULL values with
144 /// associated destructors exist, even though this might result in an infinite loop.
149 ) -> Option<(ty::Instance<'tcx>, ThreadId, Scalar<Tag>, TlsKey)> {
150 use std::collections::Bound::*;
152 let thread_local = &mut self.keys;
153 let start = match key {
154 Some(key) => Excluded(key),
157 for (&key, TlsEntry { data, dtor }) in
158 thread_local.range_mut((start, Unbounded))
160 match data.entry(thread_id) {
161 Entry::Occupied(entry) => {
162 let (thread_id, data_scalar) = entry.remove_entry();
163 if let Some(dtor) = dtor {
164 let ret = Some((*dtor, thread_id, data_scalar, key));
168 Entry::Vacant(_) => {}
175 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
176 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
177 /// Run TLS destructors for all threads.
178 fn run_tls_dtors(&mut self) -> InterpResult<'tcx> {
179 let this = self.eval_context_mut();
180 assert!(!this.machine.tls.dtors_running, "running TLS dtors twice");
181 this.machine.tls.dtors_running = true;
183 if this.tcx.sess.target.target.target_os == "windows" {
184 // Windows has a special magic linker section that is run on certain events.
185 // Instead of searching for that section and supporting arbitrary hooks in there
186 // (that would be basically https://github.com/rust-lang/miri/issues/450),
187 // we specifically look up the static in libstd that we know is placed
189 let thread_callback = this.eval_path_scalar(&["std", "sys", "windows", "thread_local", "p_thread_callback"])?;
190 let thread_callback = this.memory.get_fn(thread_callback.not_undef()?)?.as_instance()?;
192 // The signature of this function is `unsafe extern "system" fn(h: c::LPVOID, dwReason: c::DWORD, pv: c::LPVOID)`.
193 let reason = this.eval_path_scalar(&["std", "sys", "windows", "c", "DLL_PROCESS_DETACH"])?;
194 let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
197 &[Scalar::null_ptr(this).into(), reason.into(), Scalar::null_ptr(this).into()],
199 StackPopCleanup::None { cleanup: true },
202 // step until out of stackframes
205 // Windows doesn't have other destructors.
209 // The macOS global dtor runs "before any TLS slots get freed", so do that first.
210 if let Some((instance, data)) = this.machine.tls.global_dtor {
211 trace!("Running global dtor {:?} on {:?}", instance, data);
213 let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
218 StackPopCleanup::None { cleanup: true },
221 // step until out of stackframes
225 // Now run the "keyed" destructors.
226 for (thread_id, thread_state) in this.get_all_thread_ids_with_states() {
227 assert!(thread_state == ThreadState::Terminated,
228 "TLS destructors should be executed after all threads terminated.");
229 this.set_active_thread(thread_id)?;
230 let mut dtor = this.machine.tls.fetch_tls_dtor(None, thread_id);
231 while let Some((instance, thread_id, ptr, key)) = dtor {
232 trace!("Running TLS dtor {:?} on {:?} at {:?}", instance, ptr, thread_id);
233 assert!(!this.is_null(ptr).unwrap(), "Data can't be NULL when dtor is called!");
235 let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
240 StackPopCleanup::None { cleanup: true },
243 // step until out of stackframes
246 // Fetch next dtor after `key`.
247 dtor = match this.machine.tls.fetch_tls_dtor(Some(key), thread_id) {
248 dtor @ Some(_) => dtor,
249 // We ran each dtor once, start over from the beginning.
250 None => this.machine.tls.fetch_tls_dtor(None, thread_id),