]> git.lizzy.rs Git - rust.git/blobdiff - src/shims/tls.rs
Replace deprecated `collections::Bound`
[rust.git] / src / shims / tls.rs
index 8a5bb7b42c5d2e949c868a72e640e73578b4613b..3339e3bee19990d2378759a9803fca3d842abdbf 100644 (file)
@@ -1,18 +1,17 @@
 //! Implement thread-local storage.
 
 use std::collections::BTreeMap;
-use std::collections::btree_map::Entry;
+use std::collections::btree_map::Entry as BTreeEntry;
+use std::collections::hash_map::Entry as HashMapEntry;
 
 use log::trace;
 
 use rustc_data_structures::fx::FxHashMap;
 use rustc_middle::ty;
 use rustc_target::abi::{Size, HasDataLayout};
+use rustc_target::spec::abi::Abi;
 
-use crate::{
-    HelpersEvalContextExt, InterpResult, MPlaceTy, Scalar, StackPopCleanup, Tag, ThreadId,
-    ThreadsEvalContextExt,
-};
+use crate::*;
 
 pub type TlsKey = u128;
 
@@ -67,7 +66,7 @@ impl<'tcx> TlsData<'tcx> {
     pub fn create_tls_key(&mut self, dtor: Option<ty::Instance<'tcx>>, max_size: Size) -> InterpResult<'tcx, TlsKey> {
         let new_key = self.next_key;
         self.next_key += 1;
-        self.keys.insert(new_key, TlsEntry { data: Default::default(), dtor }).unwrap_none();
+        self.keys.try_insert(new_key, TlsEntry { data: Default::default(), dtor }).unwrap();
         trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
 
         if max_size.bits() < 128 && new_key >= (1u128 << max_size.bits() as u128) {
@@ -135,7 +134,7 @@ pub fn store_tls(
     /// implementation](https://github.com/opensource-apple/dyld/blob/195030646877261f0c8c7ad8b001f52d6a26f514/src/threadLocalVariables.c#L389):
     ///
     ///     // NOTE: this does not need locks because it only operates on current thread data
-    pub fn set_thread_dtor(
+    pub fn set_macos_thread_dtor(
         &mut self,
         thread: ThreadId,
         dtor: ty::Instance<'tcx>,
@@ -175,7 +174,7 @@ fn fetch_tls_dtor(
         key: Option<TlsKey>,
         thread_id: ThreadId,
     ) -> Option<(ty::Instance<'tcx>, Scalar<Tag>, TlsKey)> {
-        use std::collections::Bound::*;
+        use std::ops::Bound::*;
 
         let thread_local = &mut self.keys;
         let start = match key {
@@ -186,7 +185,7 @@ fn fetch_tls_dtor(
             thread_local.range_mut((start, Unbounded))
         {
             match data.entry(thread_id) {
-                Entry::Occupied(entry) => {
+                BTreeEntry::Occupied(entry) => {
                     if let Some(dtor) = dtor {
                         // Set TLS data to NULL, and call dtor with old value.
                         let data_scalar = entry.remove();
@@ -194,7 +193,7 @@ fn fetch_tls_dtor(
                         return ret;
                     }
                 }
-                Entry::Vacant(_) => {}
+                BTreeEntry::Vacant(_) => {}
             }
         }
         None
@@ -204,16 +203,14 @@ fn fetch_tls_dtor(
     /// the existing values stored in `dtors_running` for this thread. Returns
     /// `true` if dtors for `thread` are already running.
     fn set_dtors_running_for_thread(&mut self, thread: ThreadId) -> bool {
-        if self.dtors_running.contains_key(&thread) {
-            true
-        } else {
-            // We need to guard this `insert` with a check because otherwise we
-            // would risk to overwrite `last_dtor_key` with `None`.
-            self.dtors_running.insert(
-                thread,
-                RunningDtorsState { last_dtor_key: None }
-            );
-            false
+        match self.dtors_running.entry(thread) {
+            HashMapEntry::Occupied(_) => true,
+            HashMapEntry::Vacant(entry) => {
+                // We cannot just do `self.dtors_running.insert` because that
+                // would overwrite `last_dtor_key` with `None`.
+                entry.insert(RunningDtorsState { last_dtor_key: None });
+                false
+            }
         }
     }
 
@@ -233,27 +230,28 @@ trait EvalContextPrivExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
     /// yet.
     fn schedule_windows_tls_dtors(&mut self) -> InterpResult<'tcx> {
         let this = self.eval_context_mut();
-        let active_thread = this.get_active_thread()?;
-        assert_eq!(this.get_total_thread_count()?, 1, "concurrency on Windows not supported");
+        let active_thread = this.get_active_thread();
+        assert_eq!(this.get_total_thread_count(), 1, "concurrency on Windows is not supported");
         // Windows has a special magic linker section that is run on certain events.
         // Instead of searching for that section and supporting arbitrary hooks in there
         // (that would be basically https://github.com/rust-lang/miri/issues/450),
         // we specifically look up the static in libstd that we know is placed
         // in that section.
-        let thread_callback = this.eval_path_scalar(&["std", "sys", "windows", "thread_local", "p_thread_callback"])?;
-        let thread_callback = this.memory.get_fn(thread_callback.not_undef()?)?.as_instance()?;
+        let thread_callback = this.eval_path_scalar(&["std", "sys", "windows", "thread_local_key", "p_thread_callback"])?;
+        let thread_callback = this.memory.get_fn(thread_callback.check_init()?)?.as_instance()?;
 
         // The signature of this function is `unsafe extern "system" fn(h: c::LPVOID, dwReason: c::DWORD, pv: c::LPVOID)`.
         let reason = this.eval_path_scalar(&["std", "sys", "windows", "c", "DLL_THREAD_DETACH"])?;
         let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
         this.call_function(
             thread_callback,
+            Abi::System { unwind: false },
             &[Scalar::null_ptr(this).into(), reason.into(), Scalar::null_ptr(this).into()],
-            Some(ret_place),
+            Some(&ret_place),
             StackPopCleanup::None { cleanup: true },
         )?;
 
-        this.enable_thread(active_thread)?;
+        this.enable_thread(active_thread);
         Ok(())
     }
 
@@ -263,15 +261,16 @@ fn schedule_windows_tls_dtors(&mut self) -> InterpResult<'tcx> {
     /// Note: It is safe to call this function also on other Unixes.
     fn schedule_macos_tls_dtor(&mut self) -> InterpResult<'tcx, bool> {
         let this = self.eval_context_mut();
-        let thread_id = this.get_active_thread()?;
+        let thread_id = this.get_active_thread();
         if let Some((instance, data)) = this.machine.tls.macos_thread_dtors.remove(&thread_id) {
             trace!("Running macos dtor {:?} on {:?} at {:?}", instance, data, thread_id);
 
             let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
             this.call_function(
                 instance,
+                Abi::C { unwind: false },
                 &[data.into()],
-                Some(ret_place),
+                Some(&ret_place),
                 StackPopCleanup::None { cleanup: true },
             )?;
 
@@ -279,7 +278,7 @@ fn schedule_macos_tls_dtor(&mut self) -> InterpResult<'tcx, bool> {
             // we just scheduled. Since we deleted the destructor, it is
             // guaranteed that we will schedule it again. The `dtors_running`
             // flag will prevent the code from adding the destructor again.
-            this.enable_thread(thread_id)?;
+            this.enable_thread(thread_id);
             Ok(true)
         } else {
             Ok(false)
@@ -290,9 +289,9 @@ fn schedule_macos_tls_dtor(&mut self) -> InterpResult<'tcx, bool> {
     /// a destructor to schedule, and `false` otherwise.
     fn schedule_next_pthread_tls_dtor(&mut self) -> InterpResult<'tcx, bool> {
         let this = self.eval_context_mut();
-        let active_thread = this.get_active_thread()?;
+        let active_thread = this.get_active_thread();
 
-        assert!(this.has_terminated(active_thread)?, "running TLS dtors for non-terminated thread");
+        assert!(this.has_terminated(active_thread), "running TLS dtors for non-terminated thread");
         // Fetch next dtor after `key`.
         let last_key = this.machine.tls.dtors_running[&active_thread].last_dtor_key.clone();
         let dtor = match this.machine.tls.fetch_tls_dtor(last_key, active_thread) {
@@ -310,12 +309,13 @@ fn schedule_next_pthread_tls_dtor(&mut self) -> InterpResult<'tcx, bool> {
             let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
             this.call_function(
                 instance,
+                Abi::C { unwind: false },
                 &[ptr.into()],
-                Some(ret_place),
+                Some(&ret_place),
                 StackPopCleanup::None { cleanup: true },
             )?;
 
-            this.enable_thread(active_thread)?;
+            this.enable_thread(active_thread);
             return Ok(true);
         }
         this.machine.tls.dtors_running.get_mut(&active_thread).unwrap().last_dtor_key = None;
@@ -332,22 +332,19 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
     /// schedules them one by one each time it is called and reenables the
     /// thread so that it can be executed normally by the main execution loop.
     ///
-    /// FIXME: we do not support yet deallocation of thread local statics.
-    /// Issue: https://github.com/rust-lang/miri/issues/1369
-    ///
     /// Note: we consistently run TLS destructors for all threads, including the
     /// main thread. However, it is not clear that we should run the TLS
     /// destructors for the main thread. See issue:
     /// https://github.com/rust-lang/rust/issues/28129.
     fn schedule_next_tls_dtor_for_active_thread(&mut self) -> InterpResult<'tcx> {
         let this = self.eval_context_mut();
-        let active_thread = this.get_active_thread()?;
+        let active_thread = this.get_active_thread();
 
-        if this.machine.tls.set_dtors_running_for_thread(active_thread) {
+        if !this.machine.tls.set_dtors_running_for_thread(active_thread) {
             // This is the first time we got asked to schedule a destructor. The
             // Windows schedule destructor function must be called exactly once,
             // this is why it is in this block.
-            if this.tcx.sess.target.target.target_os == "windows" {
+            if this.tcx.sess.target.os == "windows" {
                 // On Windows, we signal that the thread quit by starting the
                 // relevant function, reenabling the thread, and going back to
                 // the scheduler.
@@ -355,6 +352,9 @@ fn schedule_next_tls_dtor_for_active_thread(&mut self) -> InterpResult<'tcx> {
                 return Ok(())
             }
         }
+        // The remaining dtors make some progress each time around the scheduler loop,
+        // until they return `false` to indicate that they are done.
+
         // The macOS thread wide destructor runs "before any TLS slots get
         // freed", so do that first.
         if this.schedule_macos_tls_dtor()? {
@@ -371,6 +371,7 @@ fn schedule_next_tls_dtor_for_active_thread(&mut self) -> InterpResult<'tcx> {
 
         // All dtors done!
         this.machine.tls.delete_all_thread_tls(active_thread);
+        this.thread_terminated()?;
 
         Ok(())
     }