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