1 //! Implement thread-local storage.
3 use std::collections::BTreeMap;
4 use std::collections::btree_map::Entry;
5 use std::collections::HashSet;
10 use rustc_target::abi::{Size, HasDataLayout};
13 HelpersEvalContextExt, InterpResult, MPlaceTy, Scalar, StackPopCleanup, Tag, ThreadId,
14 ThreadsEvalContextExt,
17 pub type TlsKey = u128;
19 #[derive(Clone, Debug)]
20 pub struct TlsEntry<'tcx> {
21 /// The data for this key. None is used to represent NULL.
22 /// (We normalize this early to avoid having to do a NULL-ptr-test each time we access the data.)
23 data: BTreeMap<ThreadId, Scalar<Tag>>,
24 dtor: Option<ty::Instance<'tcx>>,
28 pub struct TlsData<'tcx> {
29 /// The Key to use for the next thread-local allocation.
32 /// pthreads-style thread-local storage.
33 keys: BTreeMap<TlsKey, TlsEntry<'tcx>>,
35 /// A single per thread destructor of the thread local storage (that's how
36 /// things work on macOS) with a data argument.
37 thread_dtors: BTreeMap<ThreadId, (ty::Instance<'tcx>, Scalar<Tag>)>,
39 /// Whether we are in the "destruct" phase, during which some operations are UB.
40 dtors_running: HashSet<ThreadId>,
42 /// The last TlsKey used to retrieve a TLS destructor.
43 last_dtor_key: BTreeMap<ThreadId, TlsKey>,
46 impl<'tcx> Default for TlsData<'tcx> {
47 fn default() -> Self {
49 next_key: 1, // start with 1 as we must not use 0 on Windows
50 keys: Default::default(),
51 thread_dtors: Default::default(),
52 dtors_running: Default::default(),
53 last_dtor_key: Default::default(),
58 impl<'tcx> TlsData<'tcx> {
59 /// Generate a new TLS key with the given destructor.
60 /// `max_size` determines the integer size the key has to fit in.
61 pub fn create_tls_key(&mut self, dtor: Option<ty::Instance<'tcx>>, max_size: Size) -> InterpResult<'tcx, TlsKey> {
62 let new_key = self.next_key;
64 self.keys.insert(new_key, TlsEntry { data: Default::default(), dtor }).unwrap_none();
65 trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
67 if max_size.bits() < 128 && new_key >= (1u128 << max_size.bits() as u128) {
68 throw_unsup_format!("we ran out of TLS key space");
73 pub fn delete_tls_key(&mut self, key: TlsKey) -> InterpResult<'tcx> {
74 match self.keys.remove(&key) {
76 trace!("TLS key {} removed", key);
79 None => throw_ub_format!("removing a non-existig TLS key: {}", key),
87 cx: &impl HasDataLayout,
88 ) -> InterpResult<'tcx, Scalar<Tag>> {
89 match self.keys.get(&key) {
90 Some(TlsEntry { data, .. }) => {
91 let value = data.get(&thread_id).copied();
92 trace!("TLS key {} for thread {:?} loaded: {:?}", key, thread_id, value);
93 Ok(value.unwrap_or_else(|| Scalar::null_ptr(cx).into()))
95 None => throw_ub_format!("loading from a non-existing TLS key: {}", key),
103 new_data: Option<Scalar<Tag>>
104 ) -> InterpResult<'tcx> {
105 match self.keys.get_mut(&key) {
106 Some(TlsEntry { data, .. }) => {
109 trace!("TLS key {} for thread {:?} stored: {:?}", key, thread_id, scalar);
110 data.insert(thread_id, scalar);
113 trace!("TLS key {} for thread {:?} removed", key, thread_id);
114 data.remove(&thread_id);
119 None => throw_ub_format!("storing to a non-existing TLS key: {}", key),
123 /// Set the thread wide destructor of the thread local storage for the given
124 /// thread. This function is used to implement `_tlv_atexit` shim on MacOS.
126 /// Thread wide dtors are available only on MacOS. There is one destructor
127 /// per thread as can be guessed from the following comment in the
129 /// implementation](https://github.com/opensource-apple/dyld/blob/195030646877261f0c8c7ad8b001f52d6a26f514/src/threadLocalVariables.c#L389):
131 /// // NOTE: this does not need locks because it only operates on current thread data
132 pub fn set_thread_dtor(
135 dtor: ty::Instance<'tcx>,
137 ) -> InterpResult<'tcx> {
138 if self.dtors_running.contains(&thread) {
139 // UB, according to libstd docs.
140 throw_ub_format!("setting thread's local storage destructor while destructors are already running");
142 if self.thread_dtors.insert(thread, (dtor, data)).is_some() {
143 throw_unsup_format!("setting more than one thread local storage destructor for the same thread is not supported");
148 /// Returns a dtor, its argument and its index, if one is supposed to run.
149 /// `key` is the last dtors that was run; we return the *next* one after that.
151 /// An optional destructor function may be associated with each key value.
152 /// At thread exit, if a key value has a non-NULL destructor pointer,
153 /// and the thread has a non-NULL value associated with that key,
154 /// the value of the key is set to NULL, and then the function pointed
155 /// to is called with the previously associated value as its sole argument.
156 /// The order of destructor calls is unspecified if more than one destructor
157 /// exists for a thread when it exits.
159 /// If, after all the destructors have been called for all non-NULL values
160 /// with associated destructors, there are still some non-NULL values with
161 /// associated destructors, then the process is repeated.
162 /// If, after at least {PTHREAD_DESTRUCTOR_ITERATIONS} iterations of destructor
163 /// calls for outstanding non-NULL values, there are still some non-NULL values
164 /// with associated destructors, implementations may stop calling destructors,
165 /// or they may continue calling destructors until no non-NULL values with
166 /// associated destructors exist, even though this might result in an infinite loop.
171 ) -> Option<(ty::Instance<'tcx>, Scalar<Tag>, TlsKey)> {
172 use std::collections::Bound::*;
174 let thread_local = &mut self.keys;
175 let start = match key {
176 Some(key) => Excluded(key),
179 for (&key, TlsEntry { data, dtor }) in
180 thread_local.range_mut((start, Unbounded))
182 match data.entry(thread_id) {
183 Entry::Occupied(entry) => {
184 if let Some(dtor) = dtor {
185 let data_scalar = entry.remove();
186 let ret = Some((*dtor, data_scalar, key));
190 Entry::Vacant(_) => {}
197 impl<'mir, 'tcx: 'mir> EvalContextPrivExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
198 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
199 /// Schedule TLS destructors for the main thread on Windows. The
200 /// implementation assumes that we do not support concurrency on Windows
202 fn schedule_windows_tls_dtors(&mut self) -> InterpResult<'tcx> {
203 let this = self.eval_context_mut();
204 let active_thread = this.get_active_thread()?;
205 assert_eq!(this.get_total_thread_count()?, 1, "concurrency on Windows not supported");
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_THREAD_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 this.enable_thread(active_thread)?;
229 /// Schedule the MacOS thread destructor of the thread local storage to be
232 /// Note: It is safe to call this function also on other Unixes.
233 fn schedule_macos_tls_dtor(&mut self) -> InterpResult<'tcx> {
234 let this = self.eval_context_mut();
235 let thread_id = this.get_active_thread()?;
236 if let Some((instance, data)) = this.machine.tls.thread_dtors.remove(&thread_id) {
237 trace!("Running macos dtor {:?} on {:?} at {:?}", instance, data, thread_id);
239 let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
244 StackPopCleanup::None { cleanup: true },
247 // Enable the thread so that it steps through the destructor which
248 // we just scheduled. Since we deleted the destructor, it is
249 // guaranteed that we will schedule it again. The `dtors_running`
250 // flag will prevent the code from adding the destructor again.
251 this.enable_thread(thread_id)?;
256 /// Schedule a pthread TLS destructor.
257 fn schedule_pthread_tls_dtors(&mut self) -> InterpResult<'tcx> {
258 let this = self.eval_context_mut();
259 let active_thread = this.get_active_thread()?;
261 assert!(this.has_terminated(active_thread)?, "running TLS dtors for non-terminated thread");
262 // Fetch next dtor after `key`.
263 let last_key = this.machine.tls.last_dtor_key.get(&active_thread).cloned();
264 let dtor = match this.machine.tls.fetch_tls_dtor(last_key, active_thread) {
265 dtor @ Some(_) => dtor,
266 // We ran each dtor once, start over from the beginning.
268 this.machine.tls.fetch_tls_dtor(None, active_thread)
271 if let Some((instance, ptr, key)) = dtor {
272 this.machine.tls.last_dtor_key.insert(active_thread, key);
273 trace!("Running TLS dtor {:?} on {:?} at {:?}", instance, ptr, active_thread);
274 assert!(!this.is_null(ptr).unwrap(), "data can't be NULL when dtor is called!");
276 let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
281 StackPopCleanup::None { cleanup: true },
284 this.enable_thread(active_thread)?;
287 this.machine.tls.last_dtor_key.remove(&active_thread);
293 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
294 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
296 /// Schedule an active thread's TLS destructor to run on the active thread.
297 /// Note that this function does not run the destructors itself, it just
298 /// schedules them one by one each time it is called and reenables the
299 /// thread so that it can be executed normally by the main execution loop.
301 /// FIXME: we do not support yet deallocation of thread local statics.
302 /// Issue: https://github.com/rust-lang/miri/issues/1369
303 fn schedule_next_tls_dtor_for_active_thread(&mut self) -> InterpResult<'tcx> {
304 let this = self.eval_context_mut();
305 let active_thread = this.get_active_thread()?;
307 if this.tcx.sess.target.target.target_os == "windows" {
308 if !this.machine.tls.dtors_running.contains(&active_thread) {
309 this.machine.tls.dtors_running.insert(active_thread);
310 this.schedule_windows_tls_dtors()?;
313 this.machine.tls.dtors_running.insert(active_thread);
314 // The macOS thread wide destructor runs "before any TLS slots get
315 // freed", so do that first.
316 this.schedule_macos_tls_dtor()?;
317 this.schedule_pthread_tls_dtors()?;