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