1 //! Implement thread-local storage.
3 use std::collections::BTreeMap;
5 use rustc::{ty, ty::layout::{Size, 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 /// 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;
45 self.keys.insert(new_key, TlsEntry { data: None, dtor }).unwrap_none();
46 trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
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");
54 pub fn delete_tls_key(&mut self, key: TlsKey) -> InterpResult<'tcx> {
55 match self.keys.remove(&key) {
57 trace!("TLS key {} removed", key);
60 None => throw_ub_format!("removing a non-existig TLS key: {}", key),
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()))
74 None => throw_ub_format!("loading from a non-existing TLS key: {}", key),
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);
85 None => throw_ub_format!("storing to a non-existing TLS key: {}", key),
89 /// Returns a dtor, its argument and its index, if one is supposed to run
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.
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.
110 ) -> Option<(ty::Instance<'tcx>, Scalar<Tag>, TlsKey)> {
111 use std::collections::Bound::*;
113 let thread_local = &mut self.keys;
114 let start = match key {
115 Some(key) => Excluded(key),
118 for (&key, &mut TlsEntry { ref mut data, dtor }) in
119 thread_local.range_mut((start, Unbounded))
121 if let Some(data_scalar) = *data {
122 if let Some(dtor) = dtor {
123 let ret = Some((dtor, data_scalar, key));
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!");
143 let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
148 StackPopCleanup::None { cleanup: true },
151 // step until out of stackframes
154 dtor = match this.machine.tls.fetch_tls_dtor(Some(key)) {
155 dtor @ Some(_) => dtor,
156 None => this.machine.tls.fetch_tls_dtor(None),
159 // FIXME: On a windows target, call `unsafe extern "system" fn on_tls_callback`.