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.
111 /// `key` is the last dtors that was run; we return the *next* one after that.
113 /// An optional destructor function may be associated with each key value.
114 /// At thread exit, if a key value has a non-NULL destructor pointer,
115 /// and the thread has a non-NULL value associated with that key,
116 /// the value of the key is set to NULL, and then the function pointed
117 /// to is called with the previously associated value as its sole argument.
118 /// The order of destructor calls is unspecified if more than one destructor
119 /// exists for a thread when it exits.
121 /// If, after all the destructors have been called for all non-NULL values
122 /// with associated destructors, there are still some non-NULL values with
123 /// associated destructors, then the process is repeated.
124 /// If, after at least {PTHREAD_DESTRUCTOR_ITERATIONS} iterations of destructor
125 /// calls for outstanding non-NULL values, there are still some non-NULL values
126 /// with associated destructors, implementations may stop calling destructors,
127 /// or they may continue calling destructors until no non-NULL values with
128 /// associated destructors exist, even though this might result in an infinite loop.
132 ) -> Option<(ty::Instance<'tcx>, Scalar<Tag>, TlsKey)> {
133 use std::collections::Bound::*;
135 let thread_local = &mut self.keys;
136 let start = match key {
137 Some(key) => Excluded(key),
140 for (&key, &mut TlsEntry { ref mut data, dtor }) in
141 thread_local.range_mut((start, Unbounded))
143 if let Some(data_scalar) = *data {
144 if let Some(dtor) = dtor {
145 let ret = Some((dtor, data_scalar, key));
155 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
156 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
157 fn run_tls_dtors(&mut self) -> InterpResult<'tcx> {
158 let this = self.eval_context_mut();
159 assert!(!this.machine.tls.dtors_running, "running TLS dtors twice");
160 this.machine.tls.dtors_running = true;
162 if this.tcx.sess.target.target.target_os == "windows" {
163 // Windows has a special magic linker section that is run on certain events.
164 // Instead of searching for that section and supporting arbitrary hooks in there
165 // (that would be basically https://github.com/rust-lang/miri/issues/450),
166 // we specifically look up the static in libstd that we know is placed
168 let thread_callback = this.eval_path_scalar(&["std", "sys", "windows", "thread_local", "p_thread_callback"])?;
169 let thread_callback = this.memory.get_fn(thread_callback.not_undef()?)?.as_instance()?;
171 // The signature of this function is `unsafe extern "system" fn(h: c::LPVOID, dwReason: c::DWORD, pv: c::LPVOID)`.
172 let reason = this.eval_path_scalar(&["std", "sys", "windows", "c", "DLL_PROCESS_DETACH"])?;
173 let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
176 &[Scalar::ptr_null(this).into(), reason.into(), Scalar::ptr_null(this).into()],
178 StackPopCleanup::None { cleanup: true },
181 // step until out of stackframes
184 // Windows doesn't have other destructors.
188 // The macOS global dtor runs "before any TLS slots get freed", so do that first.
189 if let Some((instance, data)) = this.machine.tls.global_dtor {
190 trace!("Running global dtor {:?} on {:?}", instance, data);
192 let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
197 StackPopCleanup::None { cleanup: true },
200 // step until out of stackframes
204 // Now run the "keyed" destructors.
205 let mut dtor = this.machine.tls.fetch_tls_dtor(None);
206 while let Some((instance, ptr, key)) = dtor {
207 trace!("Running TLS dtor {:?} on {:?}", instance, ptr);
208 assert!(!this.is_null(ptr).unwrap(), "data can't be NULL when dtor is called!");
210 let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
215 StackPopCleanup::None { cleanup: true },
218 // step until out of stackframes
221 // Fetch next dtor after `key`.
222 dtor = match this.machine.tls.fetch_tls_dtor(Some(key)) {
223 dtor @ Some(_) => dtor,
224 // We ran each dtor once, start over from the beginning.
225 None => this.machine.tls.fetch_tls_dtor(None),