]> git.lizzy.rs Git - rust.git/blob - src/shims/tls.rs
Auto merge of #926 - RalfJung:rustup, r=RalfJung
[rust.git] / src / shims / tls.rs
1 //! Implement thread-local storage.
2
3 use std::collections::BTreeMap;
4
5 use rustc_target::abi::LayoutOf;
6 use rustc::{ty, ty::layout::HasDataLayout};
7
8 use crate::{
9     InterpResult, StackPopCleanup,
10     MPlaceTy, Scalar, Tag,
11     HelpersEvalContextExt,
12 };
13
14 pub type TlsKey = u128;
15
16 #[derive(Copy, 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: Option<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
34 impl<'tcx> Default for TlsData<'tcx> {
35     fn default() -> Self {
36         TlsData {
37             next_key: 1, // start with 1 as we must not use 0 on Windows
38             keys: Default::default(),
39         }
40     }
41 }
42
43 impl<'tcx> TlsData<'tcx> {
44     pub fn create_tls_key(
45         &mut self,
46         dtor: Option<ty::Instance<'tcx>>,
47     ) -> TlsKey {
48         let new_key = self.next_key;
49         self.next_key += 1;
50         self.keys.insert(
51             new_key,
52             TlsEntry {
53                 data: None,
54                 dtor,
55             },
56         );
57         trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
58         new_key
59     }
60
61     pub fn delete_tls_key(&mut self, key: TlsKey) -> InterpResult<'tcx> {
62         match self.keys.remove(&key) {
63             Some(_) => {
64                 trace!("TLS key {} removed", key);
65                 Ok(())
66             }
67             None => throw_unsup!(TlsOutOfBounds),
68         }
69     }
70
71     pub fn load_tls(
72         &mut self,
73         key: TlsKey,
74         cx: &impl HasDataLayout,
75     ) -> InterpResult<'tcx, Scalar<Tag>> {
76         match self.keys.get(&key) {
77             Some(&TlsEntry { data, .. }) => {
78                 trace!("TLS key {} loaded: {:?}", key, data);
79                 Ok(data.unwrap_or_else(|| Scalar::ptr_null(cx).into()))
80             }
81             None => throw_unsup!(TlsOutOfBounds),
82         }
83     }
84
85     pub fn store_tls(&mut self, key: TlsKey, new_data: Option<Scalar<Tag>>) -> InterpResult<'tcx> {
86         match self.keys.get_mut(&key) {
87             Some(&mut TlsEntry { ref mut data, .. }) => {
88                 trace!("TLS key {} stored: {:?}", key, new_data);
89                 *data = new_data;
90                 Ok(())
91             }
92             None => throw_unsup!(TlsOutOfBounds),
93         }
94     }
95
96     /// Returns a dtor, its argument and its index, if one is supposed to run
97     ///
98     /// An optional destructor function may be associated with each key value.
99     /// At thread exit, if a key value has a non-NULL destructor pointer,
100     /// and the thread has a non-NULL value associated with that key,
101     /// the value of the key is set to NULL, and then the function pointed
102     /// to is called with the previously associated value as its sole argument.
103     /// The order of destructor calls is unspecified if more than one destructor
104     /// exists for a thread when it exits.
105     ///
106     /// If, after all the destructors have been called for all non-NULL values
107     /// with associated destructors, there are still some non-NULL values with
108     /// associated destructors, then the process is repeated.
109     /// If, after at least {PTHREAD_DESTRUCTOR_ITERATIONS} iterations of destructor
110     /// calls for outstanding non-NULL values, there are still some non-NULL values
111     /// with associated destructors, implementations may stop calling destructors,
112     /// or they may continue calling destructors until no non-NULL values with
113     /// associated destructors exist, even though this might result in an infinite loop.
114     fn fetch_tls_dtor(
115         &mut self,
116         key: Option<TlsKey>,
117     ) -> Option<(ty::Instance<'tcx>, Scalar<Tag>, TlsKey)> {
118         use std::collections::Bound::*;
119
120         let thread_local = &mut self.keys;
121         let start = match key {
122             Some(key) => Excluded(key),
123             None => Unbounded,
124         };
125         for (&key, &mut TlsEntry { ref mut data, dtor }) in
126             thread_local.range_mut((start, Unbounded))
127         {
128             if let Some(data_scalar) = *data {
129                 if let Some(dtor) = dtor {
130                     let ret = Some((dtor, data_scalar, key));
131                     *data = None;
132                     return ret;
133                 }
134             }
135         }
136         None
137     }
138 }
139
140 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
141 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
142     fn run_tls_dtors(&mut self) -> InterpResult<'tcx> {
143         let this = self.eval_context_mut();
144         let mut dtor = this.machine.tls.fetch_tls_dtor(None);
145         // FIXME: replace loop by some structure that works with stepping
146         while let Some((instance, ptr, key)) = dtor {
147             trace!("Running TLS dtor {:?} on {:?}", instance, ptr);
148             assert!(!this.is_null(ptr).unwrap(), "Data can't be NULL when dtor is called!");
149             // TODO: Potentially, this has to support all the other possible instances?
150             // See eval_fn_call in interpret/terminator/mod.rs
151             let mir = this.load_mir(instance.def, None)?;
152             let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
153             this.push_stack_frame(
154                 instance,
155                 mir.span,
156                 mir,
157                 Some(ret_place),
158                 StackPopCleanup::None { cleanup: true },
159             )?;
160             let arg_local = this.frame().body.args_iter().next().ok_or_else(
161                 || err_ub_format!("TLS dtor does not take enough arguments."),
162             )?;
163             let dest = this.local_place(arg_local)?;
164             this.write_scalar(ptr, dest)?;
165
166             // step until out of stackframes
167             this.run()?;
168
169             dtor = match this.machine.tls.fetch_tls_dtor(Some(key)) {
170                 dtor @ Some(_) => dtor,
171                 None => this.machine.tls.fetch_tls_dtor(None),
172             };
173         }
174         // FIXME: On a windows target, call `unsafe extern "system" fn on_tls_callback`.
175         Ok(())
176     }
177 }