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