]> git.lizzy.rs Git - rust.git/blob - src/shims/tls.rs
Auto merge of #1267 - RalfJung:macos-dtors, 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         &mut 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     ///
112     /// An optional destructor function may be associated with each key value.
113     /// At thread exit, if a key value has a non-NULL destructor pointer,
114     /// and the thread has a non-NULL value associated with that key,
115     /// the value of the key is set to NULL, and then the function pointed
116     /// to is called with the previously associated value as its sole argument.
117     /// The order of destructor calls is unspecified if more than one destructor
118     /// exists for a thread when it exits.
119     ///
120     /// If, after all the destructors have been called for all non-NULL values
121     /// with associated destructors, there are still some non-NULL values with
122     /// associated destructors, then the process is repeated.
123     /// If, after at least {PTHREAD_DESTRUCTOR_ITERATIONS} iterations of destructor
124     /// calls for outstanding non-NULL values, there are still some non-NULL values
125     /// with associated destructors, implementations may stop calling destructors,
126     /// or they may continue calling destructors until no non-NULL values with
127     /// associated destructors exist, even though this might result in an infinite loop.
128     fn fetch_tls_dtor(
129         &mut self,
130         key: Option<TlsKey>,
131     ) -> Option<(ty::Instance<'tcx>, Scalar<Tag>, TlsKey)> {
132         use std::collections::Bound::*;
133
134         let thread_local = &mut self.keys;
135         let start = match key {
136             Some(key) => Excluded(key),
137             None => Unbounded,
138         };
139         for (&key, &mut TlsEntry { ref mut data, dtor }) in
140             thread_local.range_mut((start, Unbounded))
141         {
142             if let Some(data_scalar) = *data {
143                 if let Some(dtor) = dtor {
144                     let ret = Some((dtor, data_scalar, key));
145                     *data = None;
146                     return ret;
147                 }
148             }
149         }
150         None
151     }
152 }
153
154 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
155 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
156     fn run_tls_dtors(&mut self) -> InterpResult<'tcx> {
157         let this = self.eval_context_mut();
158         assert!(!this.machine.tls.dtors_running, "running TLS dtors twice");
159         this.machine.tls.dtors_running = true;
160
161         // The macOS global dtor runs "before any TLS slots get freed", so do that first.
162         if let Some((instance, data)) = this.machine.tls.global_dtor {
163             trace!("Running global dtor {:?} on {:?}", instance, data);
164
165             let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
166             this.call_function(
167                 instance,
168                 &[data.into()],
169                 Some(ret_place),
170                 StackPopCleanup::None { cleanup: true },
171             )?;
172
173             // step until out of stackframes
174             this.run()?;
175         }
176
177         // Now run the "keyed" destructors.
178         let mut dtor = this.machine.tls.fetch_tls_dtor(None);
179         while let Some((instance, ptr, key)) = dtor {
180             trace!("Running TLS dtor {:?} on {:?}", instance, ptr);
181             assert!(!this.is_null(ptr).unwrap(), "data can't be NULL when dtor is called!");
182
183             let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
184             this.call_function(
185                 instance,
186                 &[ptr.into()],
187                 Some(ret_place),
188                 StackPopCleanup::None { cleanup: true },
189             )?;
190
191             // step until out of stackframes
192             this.run()?;
193
194             dtor = match this.machine.tls.fetch_tls_dtor(Some(key)) {
195                 dtor @ Some(_) => dtor,
196                 None => this.machine.tls.fetch_tls_dtor(None),
197             };
198         }
199         // FIXME: On a windows target, call `unsafe extern "system" fn on_tls_callback`.
200         Ok(())
201     }
202 }