]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/src/shims/tls.rs
handle unknown targets more gracefully
[rust.git] / src / tools / miri / src / shims / tls.rs
1 //! Implement thread-local storage.
2
3 use std::collections::btree_map::Entry as BTreeEntry;
4 use std::collections::BTreeMap;
5 use std::task::Poll;
6
7 use log::trace;
8
9 use rustc_middle::ty;
10 use rustc_target::abi::{HasDataLayout, Size};
11 use rustc_target::spec::abi::Abi;
12
13 use crate::*;
14
15 pub type TlsKey = u128;
16
17 #[derive(Clone, Debug)]
18 pub struct TlsEntry<'tcx> {
19     /// The data for this key. None is used to represent NULL.
20     /// (We normalize this early to avoid having to do a NULL-ptr-test each time we access the data.)
21     data: BTreeMap<ThreadId, Scalar<Provenance>>,
22     dtor: Option<ty::Instance<'tcx>>,
23 }
24
25 #[derive(Default, Debug)]
26 struct RunningDtorState {
27     /// The last TlsKey used to retrieve a TLS destructor. `None` means that we
28     /// have not tried to retrieve a TLS destructor yet or that we already tried
29     /// all keys.
30     last_key: Option<TlsKey>,
31 }
32
33 #[derive(Debug)]
34 pub struct TlsData<'tcx> {
35     /// The Key to use for the next thread-local allocation.
36     next_key: TlsKey,
37
38     /// pthreads-style thread-local storage.
39     keys: BTreeMap<TlsKey, TlsEntry<'tcx>>,
40
41     /// A single per thread destructor of the thread local storage (that's how
42     /// things work on macOS) with a data argument.
43     macos_thread_dtors: BTreeMap<ThreadId, (ty::Instance<'tcx>, Scalar<Provenance>)>,
44 }
45
46 impl<'tcx> Default for TlsData<'tcx> {
47     fn default() -> Self {
48         TlsData {
49             next_key: 1, // start with 1 as we must not use 0 on Windows
50             keys: Default::default(),
51             macos_thread_dtors: Default::default(),
52         }
53     }
54 }
55
56 impl<'tcx> TlsData<'tcx> {
57     /// Generate a new TLS key with the given destructor.
58     /// `max_size` determines the integer size the key has to fit in.
59     #[allow(clippy::integer_arithmetic)]
60     pub fn create_tls_key(
61         &mut self,
62         dtor: Option<ty::Instance<'tcx>>,
63         max_size: Size,
64     ) -> InterpResult<'tcx, TlsKey> {
65         let new_key = self.next_key;
66         self.next_key += 1;
67         self.keys.try_insert(new_key, TlsEntry { data: Default::default(), dtor }).unwrap();
68         trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
69
70         if max_size.bits() < 128 && new_key >= (1u128 << max_size.bits()) {
71             throw_unsup_format!("we ran out of TLS key space");
72         }
73         Ok(new_key)
74     }
75
76     pub fn delete_tls_key(&mut self, key: TlsKey) -> InterpResult<'tcx> {
77         match self.keys.remove(&key) {
78             Some(_) => {
79                 trace!("TLS key {} removed", key);
80                 Ok(())
81             }
82             None => throw_ub_format!("removing a non-existig TLS key: {}", key),
83         }
84     }
85
86     pub fn load_tls(
87         &self,
88         key: TlsKey,
89         thread_id: ThreadId,
90         cx: &impl HasDataLayout,
91     ) -> InterpResult<'tcx, Scalar<Provenance>> {
92         match self.keys.get(&key) {
93             Some(TlsEntry { data, .. }) => {
94                 let value = data.get(&thread_id).copied();
95                 trace!("TLS key {} for thread {:?} loaded: {:?}", key, thread_id, value);
96                 Ok(value.unwrap_or_else(|| Scalar::null_ptr(cx)))
97             }
98             None => throw_ub_format!("loading from a non-existing TLS key: {}", key),
99         }
100     }
101
102     pub fn store_tls(
103         &mut self,
104         key: TlsKey,
105         thread_id: ThreadId,
106         new_data: Scalar<Provenance>,
107         cx: &impl HasDataLayout,
108     ) -> InterpResult<'tcx> {
109         match self.keys.get_mut(&key) {
110             Some(TlsEntry { data, .. }) => {
111                 if new_data.to_machine_usize(cx)? != 0 {
112                     trace!("TLS key {} for thread {:?} stored: {:?}", key, thread_id, new_data);
113                     data.insert(thread_id, new_data);
114                 } else {
115                     trace!("TLS key {} for thread {:?} removed", key, thread_id);
116                     data.remove(&thread_id);
117                 }
118                 Ok(())
119             }
120             None => throw_ub_format!("storing to a non-existing TLS key: {}", key),
121         }
122     }
123
124     /// Set the thread wide destructor of the thread local storage for the given
125     /// thread. This function is used to implement `_tlv_atexit` shim on MacOS.
126     ///
127     /// Thread wide dtors are available only on MacOS. There is one destructor
128     /// per thread as can be guessed from the following comment in the
129     /// [`_tlv_atexit`
130     /// implementation](https://github.com/opensource-apple/dyld/blob/195030646877261f0c8c7ad8b001f52d6a26f514/src/threadLocalVariables.c#L389):
131     ///
132     /// NOTE: this does not need locks because it only operates on current thread data
133     pub fn set_macos_thread_dtor(
134         &mut self,
135         thread: ThreadId,
136         dtor: ty::Instance<'tcx>,
137         data: Scalar<Provenance>,
138     ) -> InterpResult<'tcx> {
139         if self.macos_thread_dtors.insert(thread, (dtor, data)).is_some() {
140             throw_unsup_format!(
141                 "setting more than one thread local storage destructor for the same thread is not supported"
142             );
143         }
144         Ok(())
145     }
146
147     /// Returns a dtor, its argument and its index, if one is supposed to run.
148     /// `key` is the last dtors that was run; we return the *next* one after that.
149     ///
150     /// An optional destructor function may be associated with each key value.
151     /// At thread exit, if a key value has a non-NULL destructor pointer,
152     /// and the thread has a non-NULL value associated with that key,
153     /// the value of the key is set to NULL, and then the function pointed
154     /// to is called with the previously associated value as its sole argument.
155     /// **The order of destructor calls is unspecified if more than one destructor
156     /// exists for a thread when it exits.**
157     ///
158     /// If, after all the destructors have been called for all non-NULL values
159     /// with associated destructors, there are still some non-NULL values with
160     /// associated destructors, then the process is repeated.
161     /// If, after at least {PTHREAD_DESTRUCTOR_ITERATIONS} iterations of destructor
162     /// calls for outstanding non-NULL values, there are still some non-NULL values
163     /// with associated destructors, implementations may stop calling destructors,
164     /// or they may continue calling destructors until no non-NULL values with
165     /// associated destructors exist, even though this might result in an infinite loop.
166     fn fetch_tls_dtor(
167         &mut self,
168         key: Option<TlsKey>,
169         thread_id: ThreadId,
170     ) -> Option<(ty::Instance<'tcx>, Scalar<Provenance>, TlsKey)> {
171         use std::ops::Bound::*;
172
173         let thread_local = &mut self.keys;
174         let start = match key {
175             Some(key) => Excluded(key),
176             None => Unbounded,
177         };
178         // We interpret the documentaion above (taken from POSIX) as saying that we need to iterate
179         // over all keys and run each destructor at least once before running any destructor a 2nd
180         // time. That's why we have `key` to indicate how far we got in the current iteration. If we
181         // return `None`, `schedule_next_pthread_tls_dtor` will re-try with `ket` set to `None` to
182         // start the next round.
183         // TODO: In the future, we might consider randomizing destructor order, but we still have to
184         // uphold this requirement.
185         for (&key, TlsEntry { data, dtor }) in thread_local.range_mut((start, Unbounded)) {
186             match data.entry(thread_id) {
187                 BTreeEntry::Occupied(entry) => {
188                     if let Some(dtor) = dtor {
189                         // Set TLS data to NULL, and call dtor with old value.
190                         let data_scalar = entry.remove();
191                         let ret = Some((*dtor, data_scalar, key));
192                         return ret;
193                     }
194                 }
195                 BTreeEntry::Vacant(_) => {}
196             }
197         }
198         None
199     }
200
201     /// Delete all TLS entries for the given thread. This function should be
202     /// called after all TLS destructors have already finished.
203     fn delete_all_thread_tls(&mut self, thread_id: ThreadId) {
204         for TlsEntry { data, .. } in self.keys.values_mut() {
205             data.remove(&thread_id);
206         }
207     }
208 }
209
210 impl VisitTags for TlsData<'_> {
211     fn visit_tags(&self, visit: &mut dyn FnMut(BorTag)) {
212         let TlsData { keys, macos_thread_dtors, next_key: _ } = self;
213
214         for scalar in keys.values().flat_map(|v| v.data.values()) {
215             scalar.visit_tags(visit);
216         }
217         for (_, scalar) in macos_thread_dtors.values() {
218             scalar.visit_tags(visit);
219         }
220     }
221 }
222
223 #[derive(Debug, Default)]
224 pub struct TlsDtorsState(TlsDtorsStatePriv);
225
226 #[derive(Debug, Default)]
227 enum TlsDtorsStatePriv {
228     #[default]
229     Init,
230     PthreadDtors(RunningDtorState),
231     Done,
232 }
233
234 impl TlsDtorsState {
235     pub fn on_stack_empty<'tcx>(
236         &mut self,
237         this: &mut MiriInterpCx<'_, 'tcx>,
238     ) -> InterpResult<'tcx, Poll<()>> {
239         use TlsDtorsStatePriv::*;
240         match &mut self.0 {
241             Init => {
242                 match this.tcx.sess.target.os.as_ref() {
243                     "linux" | "freebsd" | "android" => {
244                         // Run the pthread dtors.
245                         self.0 = PthreadDtors(Default::default());
246                     }
247                     "macos" => {
248                         // The macOS thread wide destructor runs "before any TLS slots get
249                         // freed", so do that first.
250                         this.schedule_macos_tls_dtor()?;
251                         // When the stack is empty again, go on with the pthread dtors.
252                         self.0 = PthreadDtors(Default::default());
253                     }
254                     "windows" => {
255                         // Run the special magic hook.
256                         this.schedule_windows_tls_dtors()?;
257                         // And move to the final state.
258                         self.0 = Done;
259                     }
260                     _ => {
261                         // No TLS dtor support.
262                         // FIXME: should we do something on wasi?
263                         self.0 = Done;
264                     }
265                 }
266             }
267             PthreadDtors(state) => {
268                 match this.schedule_next_pthread_tls_dtor(state)? {
269                     Poll::Pending => {} // just keep going
270                     Poll::Ready(()) => self.0 = Done,
271                 }
272             }
273             Done => {
274                 this.machine.tls.delete_all_thread_tls(this.get_active_thread());
275                 return Ok(Poll::Ready(()));
276             }
277         }
278
279         Ok(Poll::Pending)
280     }
281 }
282
283 impl<'mir, 'tcx: 'mir> EvalContextPrivExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
284 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
285     /// Schedule TLS destructors for Windows.
286     /// On windows, TLS destructors are managed by std.
287     fn schedule_windows_tls_dtors(&mut self) -> InterpResult<'tcx> {
288         let this = self.eval_context_mut();
289
290         // Windows has a special magic linker section that is run on certain events.
291         // Instead of searching for that section and supporting arbitrary hooks in there
292         // (that would be basically https://github.com/rust-lang/miri/issues/450),
293         // we specifically look up the static in libstd that we know is placed
294         // in that section.
295         if !this.have_module(&["std"]) {
296             // Looks like we are running in a `no_std` crate.
297             // That also means no TLS dtors callback to call.
298             return Ok(());
299         }
300         let thread_callback =
301             this.eval_windows("thread_local_key", "p_thread_callback").to_pointer(this)?;
302         let thread_callback = this.get_ptr_fn(thread_callback)?.as_instance()?;
303
304         // FIXME: Technically, the reason should be `DLL_PROCESS_DETACH` when the main thread exits
305         // but std treats both the same.
306         let reason = this.eval_windows("c", "DLL_THREAD_DETACH");
307
308         // The signature of this function is `unsafe extern "system" fn(h: c::LPVOID, dwReason: c::DWORD, pv: c::LPVOID)`.
309         // FIXME: `h` should be a handle to the current module and what `pv` should be is unknown
310         // but both are ignored by std
311         this.call_function(
312             thread_callback,
313             Abi::System { unwind: false },
314             &[Scalar::null_ptr(this).into(), reason.into(), Scalar::null_ptr(this).into()],
315             None,
316             StackPopCleanup::Root { cleanup: true },
317         )?;
318         Ok(())
319     }
320
321     /// Schedule the MacOS thread destructor of the thread local storage to be
322     /// executed.
323     fn schedule_macos_tls_dtor(&mut self) -> InterpResult<'tcx> {
324         let this = self.eval_context_mut();
325         let thread_id = this.get_active_thread();
326         if let Some((instance, data)) = this.machine.tls.macos_thread_dtors.remove(&thread_id) {
327             trace!("Running macos dtor {:?} on {:?} at {:?}", instance, data, thread_id);
328
329             this.call_function(
330                 instance,
331                 Abi::C { unwind: false },
332                 &[data.into()],
333                 None,
334                 StackPopCleanup::Root { cleanup: true },
335             )?;
336         }
337         Ok(())
338     }
339
340     /// Schedule a pthread TLS destructor. Returns `true` if found
341     /// a destructor to schedule, and `false` otherwise.
342     fn schedule_next_pthread_tls_dtor(
343         &mut self,
344         state: &mut RunningDtorState,
345     ) -> InterpResult<'tcx, Poll<()>> {
346         let this = self.eval_context_mut();
347         let active_thread = this.get_active_thread();
348
349         // Fetch next dtor after `key`.
350         let dtor = match this.machine.tls.fetch_tls_dtor(state.last_key, active_thread) {
351             dtor @ Some(_) => dtor,
352             // We ran each dtor once, start over from the beginning.
353             None => this.machine.tls.fetch_tls_dtor(None, active_thread),
354         };
355         if let Some((instance, ptr, key)) = dtor {
356             state.last_key = Some(key);
357             trace!("Running TLS dtor {:?} on {:?} at {:?}", instance, ptr, active_thread);
358             assert!(
359                 !ptr.to_machine_usize(this).unwrap() != 0,
360                 "data can't be NULL when dtor is called!"
361             );
362
363             this.call_function(
364                 instance,
365                 Abi::C { unwind: false },
366                 &[ptr.into()],
367                 None,
368                 StackPopCleanup::Root { cleanup: true },
369             )?;
370
371             return Ok(Poll::Pending);
372         }
373
374         Ok(Poll::Ready(()))
375     }
376 }