]> git.lizzy.rs Git - rust.git/blob - src/shims/tls.rs
Clarify comments about TLS destructor handling in Windows, add a test for TLS destruc...
[rust.git] / src / shims / tls.rs
1 //! Implement thread-local storage.
2
3 use std::collections::BTreeMap;
4 use std::collections::btree_map::Entry;
5 use std::collections::HashSet;
6
7 use log::trace;
8
9 use rustc_middle::ty;
10 use rustc_target::abi::{Size, HasDataLayout};
11
12 use crate::{
13     HelpersEvalContextExt, InterpResult, MPlaceTy, Scalar, StackPopCleanup, Tag, ThreadId,
14     ThreadsEvalContextExt,
15 };
16
17 pub type TlsKey = u128;
18
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     /// Will eventually become a map from thread IDs to `Scalar`s, if we ever support more than one thread.
24     data: BTreeMap<ThreadId, Scalar<Tag>>,
25     dtor: Option<ty::Instance<'tcx>>,
26 }
27
28 #[derive(Debug)]
29 pub struct TlsData<'tcx> {
30     /// The Key to use for the next thread-local allocation.
31     next_key: TlsKey,
32
33     /// pthreads-style thread-local storage.
34     keys: BTreeMap<TlsKey, TlsEntry<'tcx>>,
35
36     /// A single global per thread dtor (that's how things work on macOS) with a data argument.
37     global_dtors: BTreeMap<ThreadId, (ty::Instance<'tcx>, Scalar<Tag>)>,
38
39     /// Whether we are in the "destruct" phase, during which some operations are UB.
40     dtors_running: HashSet<ThreadId>,
41 }
42
43 impl<'tcx> Default for TlsData<'tcx> {
44     fn default() -> Self {
45         TlsData {
46             next_key: 1, // start with 1 as we must not use 0 on Windows
47             keys: Default::default(),
48             global_dtors: Default::default(),
49             dtors_running: Default::default(),
50         }
51     }
52 }
53
54 impl<'tcx> TlsData<'tcx> {
55     /// Generate a new TLS key with the given destructor.
56     /// `max_size` determines the integer size the key has to fit in.
57     pub fn create_tls_key(&mut self, dtor: Option<ty::Instance<'tcx>>, max_size: Size) -> InterpResult<'tcx, TlsKey> {
58         let new_key = self.next_key;
59         self.next_key += 1;
60         self.keys.insert(new_key, TlsEntry { data: Default::default(), dtor }).unwrap_none();
61         trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
62
63         if max_size.bits() < 128 && new_key >= (1u128 << max_size.bits() as u128) {
64             throw_unsup_format!("we ran out of TLS key space");
65         }
66         Ok(new_key)
67     }
68
69     pub fn delete_tls_key(&mut self, key: TlsKey) -> InterpResult<'tcx> {
70         match self.keys.remove(&key) {
71             Some(_) => {
72                 trace!("TLS key {} removed", key);
73                 Ok(())
74             }
75             None => throw_ub_format!("removing a non-existig TLS key: {}", key),
76         }
77     }
78
79     pub fn load_tls(
80         &self,
81         key: TlsKey,
82         thread_id: ThreadId,
83         cx: &impl HasDataLayout,
84     ) -> InterpResult<'tcx, Scalar<Tag>> {
85         match self.keys.get(&key) {
86             Some(TlsEntry { data, .. }) => {
87                 let value = data.get(&thread_id).cloned();
88                 trace!("TLS key {} for thread {:?} loaded: {:?}", key, thread_id, value);
89                 Ok(value.unwrap_or_else(|| Scalar::null_ptr(cx).into()))
90             }
91             None => throw_ub_format!("loading from a non-existing TLS key: {}", key),
92         }
93     }
94
95     pub fn store_tls(
96         &mut self,
97          key: TlsKey, thread_id: ThreadId, new_data: Option<Scalar<Tag>>) -> InterpResult<'tcx> {
98         match self.keys.get_mut(&key) {
99             Some(TlsEntry { data, .. }) => {
100                 match new_data {
101                     Some(ptr) => {
102                         trace!("TLS key {} for thread {:?} stored: {:?}", key, thread_id, ptr);
103                         data.insert(thread_id, ptr);
104                     }
105                     None => {
106                         trace!("TLS key {} for thread {:?} removed", key, thread_id);
107                         data.remove(&thread_id);
108                     }
109                 }
110                 Ok(())
111             }
112             None => throw_ub_format!("storing to a non-existing TLS key: {}", key),
113         }
114     }
115
116     /// Set global dtor for the given thread. This function is used to implement
117     /// `_tlv_atexit` shim on MacOS.
118     ///
119     /// Global destructors are available only on MacOS and (potentially
120     /// confusingly) they seem to be still per thread as can be guessed from the
121     /// following comment in the [`_tlv_atexit`
122     /// implementation](https://github.com/opensource-apple/dyld/blob/195030646877261f0c8c7ad8b001f52d6a26f514/src/threadLocalVariables.c#L389):
123     ///
124     ///     // NOTE: this does not need locks because it only operates on current thread data
125     pub fn set_thread_global_dtor(
126         &mut self,
127         thread: ThreadId,
128         dtor: ty::Instance<'tcx>,
129         data: Scalar<Tag>
130     ) -> InterpResult<'tcx> {
131         if self.dtors_running.contains(&thread) {
132             // UB, according to libstd docs.
133             throw_ub_format!("setting global destructor while destructors are already running");
134         }
135         if self.global_dtors.insert(thread, (dtor, data)).is_some() {
136             throw_unsup_format!("setting more than one global destructor for the same thread is not supported");
137         }
138         Ok(())
139     }
140
141     /// Returns a dtor, its argument and its index, if one is supposed to run.
142     /// `key` is the last dtors that was run; we return the *next* one after that.
143     ///
144     /// An optional destructor function may be associated with each key value.
145     /// At thread exit, if a key value has a non-NULL destructor pointer,
146     /// and the thread has a non-NULL value associated with that key,
147     /// the value of the key is set to NULL, and then the function pointed
148     /// to is called with the previously associated value as its sole argument.
149     /// The order of destructor calls is unspecified if more than one destructor
150     /// exists for a thread when it exits.
151     ///
152     /// If, after all the destructors have been called for all non-NULL values
153     /// with associated destructors, there are still some non-NULL values with
154     /// associated destructors, then the process is repeated.
155     /// If, after at least {PTHREAD_DESTRUCTOR_ITERATIONS} iterations of destructor
156     /// calls for outstanding non-NULL values, there are still some non-NULL values
157     /// with associated destructors, implementations may stop calling destructors,
158     /// or they may continue calling destructors until no non-NULL values with
159     /// associated destructors exist, even though this might result in an infinite loop.
160     fn fetch_tls_dtor(
161         &mut self,
162         key: Option<TlsKey>,
163         thread_id: ThreadId,
164     ) -> Option<(ty::Instance<'tcx>, Scalar<Tag>, TlsKey)> {
165         use std::collections::Bound::*;
166
167         let thread_local = &mut self.keys;
168         let start = match key {
169             Some(key) => Excluded(key),
170             None => Unbounded,
171         };
172         for (&key, TlsEntry { data, dtor }) in
173             thread_local.range_mut((start, Unbounded))
174         {
175             match data.entry(thread_id) {
176                 Entry::Occupied(entry) => {
177                     let data_scalar = entry.remove();
178                     if let Some(dtor) = dtor {
179                         let ret = Some((*dtor, data_scalar, key));
180                         return ret;
181                     }
182                 }
183                 Entry::Vacant(_) => {}
184             }
185         }
186         None
187     }
188 }
189
190 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
191 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
192
193     /// Run TLS destructors for the main thread on Windows. The implementation
194     /// assumes that we do not support concurrency on Windows yet.
195     ///
196     /// Note: on non-Windows OS this function is a no-op.
197     fn run_windows_tls_dtors(&mut self) -> InterpResult<'tcx> {
198         let this = self.eval_context_mut();
199         if this.tcx.sess.target.target.target_os != "windows" {
200             return Ok(());
201         }
202         let active_thread = this.get_active_thread()?;
203         assert_eq!(this.get_total_thread_count()?, 1, "concurrency on Windows not supported");
204         assert!(!this.machine.tls.dtors_running.contains(&active_thread), "running TLS dtors twice");
205         this.machine.tls.dtors_running.insert(active_thread);
206         // Windows has a special magic linker section that is run on certain events.
207         // Instead of searching for that section and supporting arbitrary hooks in there
208         // (that would be basically https://github.com/rust-lang/miri/issues/450),
209         // we specifically look up the static in libstd that we know is placed
210         // in that section.
211         let thread_callback = this.eval_path_scalar(&["std", "sys", "windows", "thread_local", "p_thread_callback"])?;
212         let thread_callback = this.memory.get_fn(thread_callback.not_undef()?)?.as_instance()?;
213
214         // The signature of this function is `unsafe extern "system" fn(h: c::LPVOID, dwReason: c::DWORD, pv: c::LPVOID)`.
215         let reason = this.eval_path_scalar(&["std", "sys", "windows", "c", "DLL_PROCESS_DETACH"])?;
216         let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
217         this.call_function(
218             thread_callback,
219             &[Scalar::null_ptr(this).into(), reason.into(), Scalar::null_ptr(this).into()],
220             Some(ret_place),
221             StackPopCleanup::None { cleanup: true },
222         )?;
223
224         // step until out of stackframes
225         this.run()?;
226
227         // Windows doesn't have other destructors.
228         Ok(())
229     }
230
231     /// Run TLS destructors for the active thread.
232     ///
233     /// Note: on Windows OS this function is a no-op because we do not support
234     /// concurrency on Windows yet.
235     ///
236     /// FIXME: we do not support yet deallocation of thread local statics.
237     fn run_tls_dtors_for_active_thread(&mut self) -> InterpResult<'tcx> {
238         let this = self.eval_context_mut();
239         if this.tcx.sess.target.target.target_os == "windows" {
240             return Ok(());
241         }
242         let thread_id = this.get_active_thread()?;
243         assert!(!this.machine.tls.dtors_running.contains(&thread_id), "running TLS dtors twice");
244         this.machine.tls.dtors_running.insert(thread_id);
245
246         // The macOS global dtor runs "before any TLS slots get freed", so do that first.
247         if let Some(&(instance, data)) = this.machine.tls.global_dtors.get(&thread_id) {
248             trace!("Running global dtor {:?} on {:?} at {:?}", instance, data, thread_id);
249
250             let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
251             this.call_function(
252                 instance,
253                 &[data.into()],
254                 Some(ret_place),
255                 StackPopCleanup::None { cleanup: true },
256             )?;
257
258             // step until out of stackframes
259             this.run()?;
260         }
261
262         assert!(this.has_terminated(thread_id)?, "running TLS dtors for non-terminated thread");
263         let mut dtor = this.machine.tls.fetch_tls_dtor(None, thread_id);
264         while let Some((instance, ptr, key)) = dtor {
265             trace!("Running TLS dtor {:?} on {:?} at {:?}", instance, ptr, thread_id);
266             assert!(!this.is_null(ptr).unwrap(), "Data can't be NULL when dtor is called!");
267
268             let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
269             this.call_function(
270                 instance,
271                 &[ptr.into()],
272                 Some(ret_place),
273                 StackPopCleanup::None { cleanup: true },
274             )?;
275
276             // step until out of stackframes
277             this.run()?;
278
279             // Fetch next dtor after `key`.
280             dtor = match this.machine.tls.fetch_tls_dtor(Some(key), thread_id) {
281                 dtor @ Some(_) => dtor,
282                 // We ran each dtor once, start over from the beginning.
283                 None => this.machine.tls.fetch_tls_dtor(None, thread_id),
284             };
285         }
286
287         Ok(())
288     }
289 }