1 //! Implement thread-local storage.
3 use std::collections::BTreeMap;
5 use rustc::{ty, ty::layout::HasDataLayout};
6 use rustc_target::abi::LayoutOf;
8 use crate::{HelpersEvalContextExt, InterpResult, MPlaceTy, Scalar, StackPopCleanup, Tag};
10 pub type TlsKey = u128;
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>>,
22 pub struct TlsData<'tcx> {
23 /// The Key to use for the next thread-local allocation.
26 /// pthreads-style thread-local storage.
27 keys: BTreeMap<TlsKey, TlsEntry<'tcx>>,
30 impl<'tcx> Default for TlsData<'tcx> {
31 fn default() -> Self {
33 next_key: 1, // start with 1 as we must not use 0 on Windows
34 keys: Default::default(),
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;
43 self.keys.insert(new_key, TlsEntry { data: None, dtor }).unwrap_none();
44 trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
48 pub fn delete_tls_key(&mut self, key: TlsKey) -> InterpResult<'tcx> {
49 match self.keys.remove(&key) {
51 trace!("TLS key {} removed", key);
54 None => throw_unsup!(TlsOutOfBounds),
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()))
68 None => throw_unsup!(TlsOutOfBounds),
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);
79 None => throw_unsup!(TlsOutOfBounds),
83 /// Returns a dtor, its argument and its index, if one is supposed to run
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.
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.
104 ) -> Option<(ty::Instance<'tcx>, Scalar<Tag>, TlsKey)> {
105 use std::collections::Bound::*;
107 let thread_local = &mut self.keys;
108 let start = match key {
109 Some(key) => Excluded(key),
112 for (&key, &mut TlsEntry { ref mut data, dtor }) in
113 thread_local.range_mut((start, Unbounded))
115 if let Some(data_scalar) = *data {
116 if let Some(dtor) = dtor {
117 let ret = Some((dtor, data_scalar, key));
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!");
137 let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
142 StackPopCleanup::None { cleanup: true },
145 // step until out of stackframes
148 dtor = match this.machine.tls.fetch_tls_dtor(Some(key)) {
149 dtor @ Some(_) => dtor,
150 None => this.machine.tls.fetch_tls_dtor(None),
153 // FIXME: On a windows target, call `unsafe extern "system" fn on_tls_callback`.