1 //! Implement thread-local storage.
3 use std::collections::BTreeMap;
4 use std::collections::btree_map::Entry;
5 use std::collections::HashSet;
9 use rustc_index::vec::Idx;
11 use rustc_target::abi::{Size, HasDataLayout};
14 HelpersEvalContextExt, InterpResult, MPlaceTy, Scalar, StackPopCleanup, Tag, ThreadId,
15 ThreadsEvalContextExt,
18 pub type TlsKey = u128;
20 #[derive(Clone, Debug)]
21 pub struct TlsEntry<'tcx> {
22 /// The data for this key. None is used to represent NULL.
23 /// (We normalize this early to avoid having to do a NULL-ptr-test each time we access the data.)
24 /// Will eventually become a map from thread IDs to `Scalar`s, if we ever support more than one thread.
25 data: BTreeMap<ThreadId, Scalar<Tag>>,
26 dtor: Option<ty::Instance<'tcx>>,
30 pub struct TlsData<'tcx> {
31 /// The Key to use for the next thread-local allocation.
34 /// pthreads-style thread-local storage.
35 keys: BTreeMap<TlsKey, TlsEntry<'tcx>>,
37 /// A single global per thread dtor (that's how things work on macOS) with a data argument.
38 global_dtors: BTreeMap<ThreadId, (ty::Instance<'tcx>, Scalar<Tag>)>,
40 /// Whether we are in the "destruct" phase, during which some operations are UB.
41 dtors_running: HashSet<ThreadId>,
44 impl<'tcx> Default for TlsData<'tcx> {
45 fn default() -> Self {
47 next_key: 1, // start with 1 as we must not use 0 on Windows
48 keys: Default::default(),
49 global_dtors: Default::default(),
50 dtors_running: Default::default(),
55 impl<'tcx> TlsData<'tcx> {
56 /// Generate a new TLS key with the given destructor.
57 /// `max_size` determines the integer size the key has to fit in.
58 pub fn create_tls_key(&mut self, dtor: Option<ty::Instance<'tcx>>, max_size: Size) -> InterpResult<'tcx, TlsKey> {
59 let new_key = self.next_key;
61 self.keys.insert(new_key, TlsEntry { data: Default::default(), dtor }).unwrap_none();
62 trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
64 if max_size.bits() < 128 && new_key >= (1u128 << max_size.bits() as u128) {
65 throw_unsup_format!("we ran out of TLS key space");
70 pub fn delete_tls_key(&mut self, key: TlsKey) -> InterpResult<'tcx> {
71 match self.keys.remove(&key) {
73 trace!("TLS key {} removed", key);
76 None => throw_ub_format!("removing a non-existig TLS key: {}", key),
84 cx: &impl HasDataLayout,
85 ) -> InterpResult<'tcx, Scalar<Tag>> {
86 match self.keys.get(&key) {
87 Some(TlsEntry { data, .. }) => {
88 let value = data.get(&thread_id).cloned();
89 trace!("TLS key {} for thread {:?} loaded: {:?}", key, thread_id, value);
90 Ok(value.unwrap_or_else(|| Scalar::null_ptr(cx).into()))
92 None => throw_ub_format!("loading from a non-existing TLS key: {}", key),
98 key: TlsKey, thread_id: ThreadId, new_data: Option<Scalar<Tag>>) -> InterpResult<'tcx> {
99 match self.keys.get_mut(&key) {
100 Some(TlsEntry { data, .. }) => {
103 trace!("TLS key {} for thread {:?} stored: {:?}", key, thread_id, ptr);
104 data.insert(thread_id, ptr);
107 trace!("TLS key {} for thread {:?} removed", key, thread_id);
108 data.remove(&thread_id);
113 None => throw_ub_format!("storing to a non-existing TLS key: {}", key),
117 /// Set global dtor for the given thread. This function is used to implement
118 /// `_tlv_atexit` shim on MacOS.
120 /// Global destructors are available only on MacOS and (potentially
121 /// confusingly) they seem to be still per thread as can be guessed from the
122 /// following comment in the [`_tlv_atexit`
123 /// implementation](https://github.com/opensource-apple/dyld/blob/195030646877261f0c8c7ad8b001f52d6a26f514/src/threadLocalVariables.c#L389):
125 /// // NOTE: this does not need locks because it only operates on current thread data
126 pub fn set_global_dtor(
129 dtor: ty::Instance<'tcx>,
131 ) -> InterpResult<'tcx> {
132 if self.dtors_running.contains(&thread) {
133 // UB, according to libstd docs.
134 throw_ub_format!("setting global destructor while destructors are already running");
136 if self.global_dtors.insert(thread, (dtor, data)).is_some() {
137 throw_unsup_format!("setting more than one global destructor for the same thread is not supported");
142 /// Returns a dtor, its argument and its index, if one is supposed to run.
143 /// `key` is the last dtors that was run; we return the *next* one after that.
145 /// An optional destructor function may be associated with each key value.
146 /// At thread exit, if a key value has a non-NULL destructor pointer,
147 /// and the thread has a non-NULL value associated with that key,
148 /// the value of the key is set to NULL, and then the function pointed
149 /// to is called with the previously associated value as its sole argument.
150 /// The order of destructor calls is unspecified if more than one destructor
151 /// exists for a thread when it exits.
153 /// If, after all the destructors have been called for all non-NULL values
154 /// with associated destructors, there are still some non-NULL values with
155 /// associated destructors, then the process is repeated.
156 /// If, after at least {PTHREAD_DESTRUCTOR_ITERATIONS} iterations of destructor
157 /// calls for outstanding non-NULL values, there are still some non-NULL values
158 /// with associated destructors, implementations may stop calling destructors,
159 /// or they may continue calling destructors until no non-NULL values with
160 /// associated destructors exist, even though this might result in an infinite loop.
165 ) -> Option<(ty::Instance<'tcx>, Scalar<Tag>, TlsKey)> {
166 use std::collections::Bound::*;
168 let thread_local = &mut self.keys;
169 let start = match key {
170 Some(key) => Excluded(key),
173 for (&key, TlsEntry { data, dtor }) in
174 thread_local.range_mut((start, Unbounded))
176 match data.entry(thread_id) {
177 Entry::Occupied(entry) => {
178 let data_scalar = entry.remove();
179 if let Some(dtor) = dtor {
180 let ret = Some((*dtor, data_scalar, key));
184 Entry::Vacant(_) => {}
191 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
192 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
194 /// Run TLS destructors for the main thread on Windows. The implementation
195 /// assumes that we do not support concurrency on Windows yet.
197 /// Note: on non-Windows OS this function is a no-op.
198 fn run_windows_tls_dtors(&mut self) -> InterpResult<'tcx> {
199 let this = self.eval_context_mut();
200 if this.tcx.sess.target.target.target_os != "windows" {
203 let active_thread = this.get_active_thread()?;
204 assert_eq!(active_thread.index(), 0, "concurrency on Windows not supported");
205 assert!(!this.machine.tls.dtors_running.contains(&active_thread), "running TLS dtors twice");
206 this.machine.tls.dtors_running.insert(active_thread);
207 // Windows has a special magic linker section that is run on certain events.
208 // Instead of searching for that section and supporting arbitrary hooks in there
209 // (that would be basically https://github.com/rust-lang/miri/issues/450),
210 // we specifically look up the static in libstd that we know is placed
212 let thread_callback = this.eval_path_scalar(&["std", "sys", "windows", "thread_local", "p_thread_callback"])?;
213 let thread_callback = this.memory.get_fn(thread_callback.not_undef()?)?.as_instance()?;
215 // The signature of this function is `unsafe extern "system" fn(h: c::LPVOID, dwReason: c::DWORD, pv: c::LPVOID)`.
216 let reason = this.eval_path_scalar(&["std", "sys", "windows", "c", "DLL_PROCESS_DETACH"])?;
217 let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
220 &[Scalar::null_ptr(this).into(), reason.into(), Scalar::null_ptr(this).into()],
222 StackPopCleanup::None { cleanup: true },
225 // step until out of stackframes
228 // Windows doesn't have other destructors.
232 /// Run TLS destructors for the active thread.
234 /// Note: on Windows OS this function is a no-op because we do not support
235 /// concurrency on Windows yet.
237 /// FIXME: we do not support yet deallocation of thread local statics.
238 fn run_tls_dtors_for_active_thread(&mut self) -> InterpResult<'tcx> {
239 let this = self.eval_context_mut();
240 if this.tcx.sess.target.target.target_os == "windows" {
243 let thread_id = this.get_active_thread()?;
244 assert!(!this.machine.tls.dtors_running.contains(&thread_id), "running TLS dtors twice");
245 this.machine.tls.dtors_running.insert(thread_id);
247 // The macOS global dtor runs "before any TLS slots get freed", so do that first.
248 if let Some(&(instance, data)) = this.machine.tls.global_dtors.get(&thread_id) {
249 trace!("Running global dtor {:?} on {:?} at {:?}", instance, data, thread_id);
251 let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
256 StackPopCleanup::None { cleanup: true },
259 // step until out of stackframes
263 assert!(this.has_terminated(thread_id)?, "running TLS dtors for non-terminated thread");
264 let mut dtor = this.machine.tls.fetch_tls_dtor(None, thread_id);
265 while let Some((instance, ptr, key)) = dtor {
266 trace!("Running TLS dtor {:?} on {:?} at {:?}", instance, ptr, thread_id);
267 assert!(!this.is_null(ptr).unwrap(), "Data can't be NULL when dtor is called!");
269 let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
274 StackPopCleanup::None { cleanup: true },
277 // step until out of stackframes
280 // Fetch next dtor after `key`.
281 dtor = match this.machine.tls.fetch_tls_dtor(Some(key), thread_id) {
282 dtor @ Some(_) => dtor,
283 // We ran each dtor once, start over from the beginning.
284 None => this.machine.tls.fetch_tls_dtor(None, thread_id),