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