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