]> git.lizzy.rs Git - rust.git/blob - src/shims/tls.rs
Fix MacOS and Windows builds.
[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
6 use log::trace;
7
8 use rustc_data_structures::fx::FxHashMap;
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(Clone, Debug)]
28 struct RunningDtorsState {
29     /// The last TlsKey used to retrieve a TLS destructor.
30     last_dtor_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     thread_dtors: BTreeMap<ThreadId, (ty::Instance<'tcx>, Scalar<Tag>)>,
44
45     /// State for currently running TLS dtors. If this map contains a key for a
46     /// specific thread, it means that we are in the "destruct" phase, during
47     /// which some operations are UB.
48     dtors_running: FxHashMap<ThreadId, RunningDtorsState>,
49 }
50
51 impl<'tcx> Default for TlsData<'tcx> {
52     fn default() -> Self {
53         TlsData {
54             next_key: 1, // start with 1 as we must not use 0 on Windows
55             keys: Default::default(),
56             thread_dtors: Default::default(),
57             dtors_running: Default::default(),
58         }
59     }
60 }
61
62 impl<'tcx> TlsData<'tcx> {
63     /// Generate a new TLS key with the given destructor.
64     /// `max_size` determines the integer size the key has to fit in.
65     pub fn create_tls_key(&mut self, dtor: Option<ty::Instance<'tcx>>, max_size: Size) -> InterpResult<'tcx, TlsKey> {
66         let new_key = self.next_key;
67         self.next_key += 1;
68         self.keys.insert(new_key, TlsEntry { data: Default::default(), dtor }).unwrap_none();
69         trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
70
71         if max_size.bits() < 128 && new_key >= (1u128 << max_size.bits() as u128) {
72             throw_unsup_format!("we ran out of TLS key space");
73         }
74         Ok(new_key)
75     }
76
77     pub fn delete_tls_key(&mut self, key: TlsKey) -> InterpResult<'tcx> {
78         match self.keys.remove(&key) {
79             Some(_) => {
80                 trace!("TLS key {} removed", key);
81                 Ok(())
82             }
83             None => throw_ub_format!("removing a non-existig TLS key: {}", key),
84         }
85     }
86
87     pub fn load_tls(
88         &self,
89         key: TlsKey,
90         thread_id: ThreadId,
91         cx: &impl HasDataLayout,
92     ) -> InterpResult<'tcx, Scalar<Tag>> {
93         match self.keys.get(&key) {
94             Some(TlsEntry { data, .. }) => {
95                 let value = data.get(&thread_id).copied();
96                 trace!("TLS key {} for thread {:?} loaded: {:?}", key, thread_id, value);
97                 Ok(value.unwrap_or_else(|| Scalar::null_ptr(cx).into()))
98             }
99             None => throw_ub_format!("loading from a non-existing TLS key: {}", key),
100         }
101     }
102
103     pub fn store_tls(
104         &mut self,
105         key: TlsKey,
106         thread_id: ThreadId,
107         new_data: Option<Scalar<Tag>>
108     ) -> InterpResult<'tcx> {
109         match self.keys.get_mut(&key) {
110             Some(TlsEntry { data, .. }) => {
111                 match new_data {
112                     Some(scalar) => {
113                         trace!("TLS key {} for thread {:?} stored: {:?}", key, thread_id, scalar);
114                         data.insert(thread_id, scalar);
115                     }
116                     None => {
117                         trace!("TLS key {} for thread {:?} removed", key, thread_id);
118                         data.remove(&thread_id);
119                     }
120                 }
121                 Ok(())
122             }
123             None => throw_ub_format!("storing to a non-existing TLS key: {}", key),
124         }
125     }
126
127     /// Set the thread wide destructor of the thread local storage for the given
128     /// thread. This function is used to implement `_tlv_atexit` shim on MacOS.
129     ///
130     /// Thread wide dtors are available only on MacOS. There is one destructor
131     /// per thread as can be guessed from the following comment in the
132     /// [`_tlv_atexit`
133     /// implementation](https://github.com/opensource-apple/dyld/blob/195030646877261f0c8c7ad8b001f52d6a26f514/src/threadLocalVariables.c#L389):
134     ///
135     ///     // NOTE: this does not need locks because it only operates on current thread data
136     pub fn set_thread_dtor(
137         &mut self,
138         thread: ThreadId,
139         dtor: ty::Instance<'tcx>,
140         data: Scalar<Tag>
141     ) -> InterpResult<'tcx> {
142         if self.dtors_running.contains_key(&thread) {
143             // UB, according to libstd docs.
144             throw_ub_format!("setting thread's local storage destructor while destructors are already running");
145         }
146         if self.thread_dtors.insert(thread, (dtor, data)).is_some() {
147             throw_unsup_format!("setting more than one thread local storage destructor for the same thread is not supported");
148         }
149         Ok(())
150     }
151
152     /// Returns a dtor, its argument and its index, if one is supposed to run.
153     /// `key` is the last dtors that was run; we return the *next* one after that.
154     ///
155     /// An optional destructor function may be associated with each key value.
156     /// At thread exit, if a key value has a non-NULL destructor pointer,
157     /// and the thread has a non-NULL value associated with that key,
158     /// the value of the key is set to NULL, and then the function pointed
159     /// to is called with the previously associated value as its sole argument.
160     /// The order of destructor calls is unspecified if more than one destructor
161     /// exists for a thread when it exits.
162     ///
163     /// If, after all the destructors have been called for all non-NULL values
164     /// with associated destructors, there are still some non-NULL values with
165     /// associated destructors, then the process is repeated.
166     /// If, after at least {PTHREAD_DESTRUCTOR_ITERATIONS} iterations of destructor
167     /// calls for outstanding non-NULL values, there are still some non-NULL values
168     /// with associated destructors, implementations may stop calling destructors,
169     /// or they may continue calling destructors until no non-NULL values with
170     /// associated destructors exist, even though this might result in an infinite loop.
171     fn fetch_tls_dtor(
172         &mut self,
173         key: Option<TlsKey>,
174         thread_id: ThreadId,
175     ) -> Option<(ty::Instance<'tcx>, Scalar<Tag>, TlsKey)> {
176         use std::collections::Bound::*;
177
178         let thread_local = &mut self.keys;
179         let start = match key {
180             Some(key) => Excluded(key),
181             None => Unbounded,
182         };
183         for (&key, TlsEntry { data, dtor }) in
184             thread_local.range_mut((start, Unbounded))
185         {
186             match data.entry(thread_id) {
187                 Entry::Occupied(entry) => {
188                     if let Some(dtor) = dtor {
189                         let data_scalar = entry.remove();
190                         let ret = Some((*dtor, data_scalar, key));
191                         return ret;
192                     }
193                 }
194                 Entry::Vacant(_) => {}
195             }
196         }
197         None
198     }
199
200     /// Set that dtors are running for `thread`. It is guaranteed not to change
201     /// the existing values stored in `dtors_running` for this thread. Returns
202     /// `true` if dtors for `thread` are already running.
203     fn set_dtors_running_for_thread(&mut self, thread: ThreadId) -> bool {
204         if self.dtors_running.contains_key(&thread) {
205             true
206         } else {
207             self.dtors_running.insert(
208                 thread,
209                 RunningDtorsState { last_dtor_key: None }
210             );
211             false
212         }
213     }
214
215     /// Delete all TLS entries for the given thread. This function should be
216     /// called after all TLS destructors have already finished.
217     fn delete_all_thread_tls(&mut self, thread_id: ThreadId) {
218         for TlsEntry { data, .. } in self.keys.values_mut() {
219             data.remove(&thread_id);
220         }
221     }
222 }
223
224 impl<'mir, 'tcx: 'mir> EvalContextPrivExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
225 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
226     /// Schedule TLS destructors for the main thread on Windows. The
227     /// implementation assumes that we do not support concurrency on Windows
228     /// yet.
229     fn schedule_windows_tls_dtors(&mut self) -> InterpResult<'tcx> {
230         let this = self.eval_context_mut();
231         let active_thread = this.get_active_thread()?;
232         assert_eq!(this.get_total_thread_count()?, 1, "concurrency on Windows not supported");
233         // Windows has a special magic linker section that is run on certain events.
234         // Instead of searching for that section and supporting arbitrary hooks in there
235         // (that would be basically https://github.com/rust-lang/miri/issues/450),
236         // we specifically look up the static in libstd that we know is placed
237         // in that section.
238         let thread_callback = this.eval_path_scalar(&["std", "sys", "windows", "thread_local", "p_thread_callback"])?;
239         let thread_callback = this.memory.get_fn(thread_callback.not_undef()?)?.as_instance()?;
240
241         // The signature of this function is `unsafe extern "system" fn(h: c::LPVOID, dwReason: c::DWORD, pv: c::LPVOID)`.
242         let reason = this.eval_path_scalar(&["std", "sys", "windows", "c", "DLL_THREAD_DETACH"])?;
243         let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
244         this.call_function(
245             thread_callback,
246             &[Scalar::null_ptr(this).into(), reason.into(), Scalar::null_ptr(this).into()],
247             Some(ret_place),
248             StackPopCleanup::None { cleanup: true },
249         )?;
250
251         this.enable_thread(active_thread)?;
252         Ok(())
253     }
254
255     /// Schedule the MacOS thread destructor of the thread local storage to be
256     /// executed. Returns `true` if scheduled.
257     ///
258     /// Note: It is safe to call this function also on other Unixes.
259     fn schedule_macos_tls_dtor(&mut self) -> InterpResult<'tcx, bool> {
260         let this = self.eval_context_mut();
261         let thread_id = this.get_active_thread()?;
262         if let Some((instance, data)) = this.machine.tls.thread_dtors.remove(&thread_id) {
263             trace!("Running macos dtor {:?} on {:?} at {:?}", instance, data, thread_id);
264
265             let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
266             this.call_function(
267                 instance,
268                 &[data.into()],
269                 Some(ret_place),
270                 StackPopCleanup::None { cleanup: true },
271             )?;
272
273             // Enable the thread so that it steps through the destructor which
274             // we just scheduled. Since we deleted the destructor, it is
275             // guaranteed that we will schedule it again. The `dtors_running`
276             // flag will prevent the code from adding the destructor again.
277             this.enable_thread(thread_id)?;
278             Ok(true)
279         } else {
280             Ok(false)
281         }
282     }
283
284     /// Schedule a pthread TLS destructor. Returns `true` if found
285     /// a destructor to schedule, and `false` otherwise.
286     fn schedule_pthread_tls_dtors(&mut self) -> InterpResult<'tcx, bool> {
287         let this = self.eval_context_mut();
288         let active_thread = this.get_active_thread()?;
289
290         assert!(this.has_terminated(active_thread)?, "running TLS dtors for non-terminated thread");
291         // Fetch next dtor after `key`.
292         let last_key = this.machine.tls.dtors_running[&active_thread].last_dtor_key.clone();
293         let dtor = match this.machine.tls.fetch_tls_dtor(last_key, active_thread) {
294             dtor @ Some(_) => dtor,
295             // We ran each dtor once, start over from the beginning.
296             None => {
297                 this.machine.tls.fetch_tls_dtor(None, active_thread)
298             }
299         };
300         if let Some((instance, ptr, key)) = dtor {
301             this.machine.tls.dtors_running.get_mut(&active_thread).unwrap().last_dtor_key = Some(key);
302             trace!("Running TLS dtor {:?} on {:?} at {:?}", instance, ptr, active_thread);
303             assert!(!this.is_null(ptr).unwrap(), "data can't be NULL when dtor is called!");
304
305             let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
306             this.call_function(
307                 instance,
308                 &[ptr.into()],
309                 Some(ret_place),
310                 StackPopCleanup::None { cleanup: true },
311             )?;
312
313             this.enable_thread(active_thread)?;
314             return Ok(true);
315         }
316         this.machine.tls.dtors_running.get_mut(&active_thread).unwrap().last_dtor_key = None;
317
318         Ok(false)
319     }
320 }
321
322 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
323 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
324
325     /// Schedule an active thread's TLS destructor to run on the active thread.
326     /// Note that this function does not run the destructors itself, it just
327     /// schedules them one by one each time it is called and reenables the
328     /// thread so that it can be executed normally by the main execution loop.
329     ///
330     /// FIXME: we do not support yet deallocation of thread local statics.
331     /// Issue: https://github.com/rust-lang/miri/issues/1369
332     fn schedule_next_tls_dtor_for_active_thread(&mut self) -> InterpResult<'tcx> {
333         let this = self.eval_context_mut();
334         let active_thread = this.get_active_thread()?;
335
336         let scheduled_next = if this.tcx.sess.target.target.target_os == "windows" {
337             if !this.machine.tls.set_dtors_running_for_thread(active_thread) {
338                 this.schedule_windows_tls_dtors()?;
339                 true
340             } else {
341                 false
342             }
343         } else {
344             this.machine.tls.set_dtors_running_for_thread(active_thread);
345             // The macOS thread wide destructor runs "before any TLS slots get
346             // freed", so do that first.
347             if this.schedule_macos_tls_dtor()? {
348                 true
349             } else {
350                 this.schedule_pthread_tls_dtors()?
351             }
352         };
353
354         if !scheduled_next {
355             // No dtors scheduled means that we are finished. Delete the
356             // remaining TLS entries.
357             this.machine.tls.delete_all_thread_tls(active_thread);
358         }
359
360         Ok(())
361     }
362 }