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>>,
29 /// A single global dtor (that's how things work on macOS) with a data argument.
30 global_dtor: Option<(ty::Instance<'tcx>, Scalar<Tag>)>,
32 /// Whether we are in the "destruct" phase, during which some operations are UB.
36 impl<'tcx> Default for TlsData<'tcx> {
37 fn default() -> Self {
39 next_key: 1, // start with 1 as we must not use 0 on Windows
40 keys: Default::default(),
47 impl<'tcx> TlsData<'tcx> {
48 /// Generate a new TLS key with the given destructor.
49 /// `max_size` determines the integer size the key has to fit in.
50 pub fn create_tls_key(&mut self, dtor: Option<ty::Instance<'tcx>>, max_size: Size) -> InterpResult<'tcx, TlsKey> {
51 let new_key = self.next_key;
53 self.keys.insert(new_key, TlsEntry { data: None, dtor }).unwrap_none();
54 trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
56 if max_size.bits() < 128 && new_key >= (1u128 << max_size.bits() as u128) {
57 throw_unsup_format!("we ran out of TLS key space");
62 pub fn delete_tls_key(&mut self, key: TlsKey) -> InterpResult<'tcx> {
63 match self.keys.remove(&key) {
65 trace!("TLS key {} removed", key);
68 None => throw_ub_format!("removing a non-existig TLS key: {}", key),
75 cx: &impl HasDataLayout,
76 ) -> InterpResult<'tcx, Scalar<Tag>> {
77 match self.keys.get(&key) {
78 Some(&TlsEntry { data, .. }) => {
79 trace!("TLS key {} loaded: {:?}", key, data);
80 Ok(data.unwrap_or_else(|| Scalar::ptr_null(cx).into()))
82 None => throw_ub_format!("loading from a non-existing TLS key: {}", key),
86 pub fn store_tls(&mut self, key: TlsKey, new_data: Option<Scalar<Tag>>) -> InterpResult<'tcx> {
87 match self.keys.get_mut(&key) {
88 Some(&mut TlsEntry { ref mut data, .. }) => {
89 trace!("TLS key {} stored: {:?}", key, new_data);
93 None => throw_ub_format!("storing to a non-existing TLS key: {}", key),
97 pub fn set_global_dtor(&mut self, dtor: ty::Instance<'tcx>, data: Scalar<Tag>) -> InterpResult<'tcx> {
98 if self.dtors_running {
99 // UB, according to libstd docs.
100 throw_ub_format!("setting global destructor while destructors are already running");
102 if self.global_dtor.is_some() {
103 throw_unsup_format!("setting more than one global destructor is not supported");
106 self.global_dtor = Some((dtor, data));
110 /// Returns a dtor, its argument and its index, if one is supposed to run
112 /// An optional destructor function may be associated with each key value.
113 /// At thread exit, if a key value has a non-NULL destructor pointer,
114 /// and the thread has a non-NULL value associated with that key,
115 /// the value of the key is set to NULL, and then the function pointed
116 /// to is called with the previously associated value as its sole argument.
117 /// The order of destructor calls is unspecified if more than one destructor
118 /// exists for a thread when it exits.
120 /// If, after all the destructors have been called for all non-NULL values
121 /// with associated destructors, there are still some non-NULL values with
122 /// associated destructors, then the process is repeated.
123 /// If, after at least {PTHREAD_DESTRUCTOR_ITERATIONS} iterations of destructor
124 /// calls for outstanding non-NULL values, there are still some non-NULL values
125 /// with associated destructors, implementations may stop calling destructors,
126 /// or they may continue calling destructors until no non-NULL values with
127 /// associated destructors exist, even though this might result in an infinite loop.
131 ) -> Option<(ty::Instance<'tcx>, Scalar<Tag>, TlsKey)> {
132 use std::collections::Bound::*;
134 let thread_local = &mut self.keys;
135 let start = match key {
136 Some(key) => Excluded(key),
139 for (&key, &mut TlsEntry { ref mut data, dtor }) in
140 thread_local.range_mut((start, Unbounded))
142 if let Some(data_scalar) = *data {
143 if let Some(dtor) = dtor {
144 let ret = Some((dtor, data_scalar, key));
154 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
155 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
156 fn run_tls_dtors(&mut self) -> InterpResult<'tcx> {
157 let this = self.eval_context_mut();
158 assert!(!this.machine.tls.dtors_running, "running TLS dtors twice");
159 this.machine.tls.dtors_running = true;
161 // The macOS global dtor runs "before any TLS slots get freed", so do that first.
162 if let Some((instance, data)) = this.machine.tls.global_dtor {
163 trace!("Running global dtor {:?} on {:?}", instance, data);
165 let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
170 StackPopCleanup::None { cleanup: true },
173 // step until out of stackframes
177 // Now run the "keyed" destructors.
178 let mut dtor = this.machine.tls.fetch_tls_dtor(None);
179 while let Some((instance, ptr, key)) = dtor {
180 trace!("Running TLS dtor {:?} on {:?}", instance, ptr);
181 assert!(!this.is_null(ptr).unwrap(), "data can't be NULL when dtor is called!");
183 let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
188 StackPopCleanup::None { cleanup: true },
191 // step until out of stackframes
194 dtor = match this.machine.tls.fetch_tls_dtor(Some(key)) {
195 dtor @ Some(_) => dtor,
196 None => this.machine.tls.fetch_tls_dtor(None),
199 // FIXME: On a windows target, call `unsafe extern "system" fn on_tls_callback`.