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