]> git.lizzy.rs Git - rust.git/blob - src/shims/tls.rs
Improve style and comments.
[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     data: BTreeMap<ThreadId, Scalar<Tag>>,
24     dtor: Option<ty::Instance<'tcx>>,
25 }
26
27 #[derive(Debug)]
28 pub struct TlsData<'tcx> {
29     /// The Key to use for the next thread-local allocation.
30     next_key: TlsKey,
31
32     /// pthreads-style thread-local storage.
33     keys: BTreeMap<TlsKey, TlsEntry<'tcx>>,
34
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>)>,
38
39     /// Whether we are in the "destruct" phase, during which some operations are UB.
40     dtors_running: HashSet<ThreadId>,
41
42     /// The last TlsKey used to retrieve a TLS destructor.
43     last_dtor_key: BTreeMap<ThreadId, TlsKey>,
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             thread_dtors: Default::default(),
52             dtors_running: Default::default(),
53             last_dtor_key: Default::default(),
54         }
55     }
56 }
57
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;
63         self.next_key += 1;
64         self.keys.insert(new_key, TlsEntry { data: Default::default(), dtor }).unwrap_none();
65         trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
66
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");
69         }
70         Ok(new_key)
71     }
72
73     pub fn delete_tls_key(&mut self, key: TlsKey) -> InterpResult<'tcx> {
74         match self.keys.remove(&key) {
75             Some(_) => {
76                 trace!("TLS key {} removed", key);
77                 Ok(())
78             }
79             None => throw_ub_format!("removing a non-existig TLS key: {}", key),
80         }
81     }
82
83     pub fn load_tls(
84         &self,
85         key: TlsKey,
86         thread_id: ThreadId,
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()))
94             }
95             None => throw_ub_format!("loading from a non-existing TLS key: {}", key),
96         }
97     }
98
99     pub fn store_tls(
100         &mut self,
101         key: TlsKey,
102         thread_id: ThreadId,
103         new_data: Option<Scalar<Tag>>
104     ) -> InterpResult<'tcx> {
105         match self.keys.get_mut(&key) {
106             Some(TlsEntry { data, .. }) => {
107                 match new_data {
108                     Some(scalar) => {
109                         trace!("TLS key {} for thread {:?} stored: {:?}", key, thread_id, scalar);
110                         data.insert(thread_id, scalar);
111                     }
112                     None => {
113                         trace!("TLS key {} for thread {:?} removed", key, thread_id);
114                         data.remove(&thread_id);
115                     }
116                 }
117                 Ok(())
118             }
119             None => throw_ub_format!("storing to a non-existing TLS key: {}", key),
120         }
121     }
122
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.
125     ///
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
128     /// [`_tlv_atexit`
129     /// implementation](https://github.com/opensource-apple/dyld/blob/195030646877261f0c8c7ad8b001f52d6a26f514/src/threadLocalVariables.c#L389):
130     ///
131     ///     // NOTE: this does not need locks because it only operates on current thread data
132     pub fn set_thread_dtor(
133         &mut self,
134         thread: ThreadId,
135         dtor: ty::Instance<'tcx>,
136         data: Scalar<Tag>
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");
141         }
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");
144         }
145         Ok(())
146     }
147
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.
150     ///
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.
158     ///
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.
167     fn fetch_tls_dtor(
168         &mut self,
169         key: Option<TlsKey>,
170         thread_id: ThreadId,
171     ) -> Option<(ty::Instance<'tcx>, Scalar<Tag>, TlsKey)> {
172         use std::collections::Bound::*;
173
174         let thread_local = &mut self.keys;
175         let start = match key {
176             Some(key) => Excluded(key),
177             None => Unbounded,
178         };
179         for (&key, TlsEntry { data, dtor }) in
180             thread_local.range_mut((start, Unbounded))
181         {
182             match data.entry(thread_id) {
183                 Entry::Occupied(entry) => {
184                     let data_scalar = entry.remove();
185                     if let Some(dtor) = dtor {
186                         let ret = Some((*dtor, data_scalar, key));
187                         return ret;
188                     }
189                 }
190                 Entry::Vacant(_) => {}
191             }
192         }
193         None
194     }
195 }
196
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
201     /// yet.
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
211         // in that section.
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()?;
214
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();
218         this.call_function(
219             thread_callback,
220             &[Scalar::null_ptr(this).into(), reason.into(), Scalar::null_ptr(this).into()],
221             Some(ret_place),
222             StackPopCleanup::None { cleanup: true },
223         )?;
224
225         this.enable_thread(active_thread)?;
226         Ok(())
227     }
228
229     /// Schedule the MacOS thread destructor of the thread local storage to be
230     /// executed.
231     ///
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);
238
239             let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
240             this.call_function(
241                 instance,
242                 &[data.into()],
243                 Some(ret_place),
244                 StackPopCleanup::None { cleanup: true },
245             )?;
246
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)?;
252         }
253         Ok(())
254     }
255
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()?;
260
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.
267             None => {
268                 this.machine.tls.fetch_tls_dtor(None, active_thread)
269             }
270         };
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!");
275
276             let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
277             this.call_function(
278                 instance,
279                 &[ptr.into()],
280                 Some(ret_place),
281                 StackPopCleanup::None { cleanup: true },
282             )?;
283
284             this.enable_thread(active_thread)?;
285             return Ok(());
286         }
287         this.machine.tls.last_dtor_key.remove(&active_thread);
288
289         Ok(())
290     }
291 }
292
293 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
294 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
295
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.
300     ///
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()?;
306
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()?;
311             }
312         } else {
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()?;
318         }
319
320         Ok(())
321     }
322 }