1 //! Implement thread-local storage.
3 use std::collections::BTreeMap;
5 use rustc_target::abi::LayoutOf;
6 use rustc::{ty, ty::layout::HasDataLayout};
9 InterpResult, StackPopCleanup,
10 MPlaceTy, Scalar, Tag,
11 HelpersEvalContextExt,
14 pub type TlsKey = u128;
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>>,
26 pub struct TlsData<'tcx> {
27 /// The Key to use for the next thread-local allocation.
30 /// pthreads-style thread-local storage.
31 keys: BTreeMap<TlsKey, TlsEntry<'tcx>>,
34 impl<'tcx> Default for TlsData<'tcx> {
35 fn default() -> Self {
37 next_key: 1, // start with 1 as we must not use 0 on Windows
38 keys: Default::default(),
43 impl<'tcx> TlsData<'tcx> {
44 pub fn create_tls_key(
46 dtor: Option<ty::Instance<'tcx>>,
48 let new_key = self.next_key;
57 trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
61 pub fn delete_tls_key(&mut self, key: TlsKey) -> InterpResult<'tcx> {
62 match self.keys.remove(&key) {
64 trace!("TLS key {} removed", key);
67 None => throw_unsup!(TlsOutOfBounds),
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()))
81 None => throw_unsup!(TlsOutOfBounds),
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);
92 None => throw_unsup!(TlsOutOfBounds),
96 /// Returns a dtor, its argument and its index, if one is supposed to run
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.
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.
117 ) -> Option<(ty::Instance<'tcx>, Scalar<Tag>, TlsKey)> {
118 use std::collections::Bound::*;
120 let thread_local = &mut self.keys;
121 let start = match key {
122 Some(key) => Excluded(key),
125 for (&key, &mut TlsEntry { ref mut data, dtor }) in
126 thread_local.range_mut((start, Unbounded))
128 if let Some(data_scalar) = *data {
129 if let Some(dtor) = dtor {
130 let ret = Some((dtor, data_scalar, key));
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(
158 StackPopCleanup::None { cleanup: true },
160 let arg_local = this.frame().body.args_iter().next().ok_or_else(
161 || err_ub_format!("TLS dtor does not take enough arguments."),
163 let dest = this.local_place(arg_local)?;
164 this.write_scalar(ptr, dest)?;
166 // step until out of stackframes
169 dtor = match this.machine.tls.fetch_tls_dtor(Some(key)) {
170 dtor @ Some(_) => dtor,
171 None => this.machine.tls.fetch_tls_dtor(None),
174 // FIXME: On a windows target, call `unsafe extern "system" fn on_tls_callback`.