]> git.lizzy.rs Git - rust.git/blob - src/thread.rs
Auto merge of #2305 - RalfJung:rustup, r=RalfJung
[rust.git] / src / thread.rs
1 //! Implements threads.
2
3 use std::cell::RefCell;
4 use std::collections::hash_map::Entry;
5 use std::num::TryFromIntError;
6 use std::time::{Duration, Instant, SystemTime};
7
8 use log::trace;
9
10 use rustc_data_structures::fx::FxHashMap;
11 use rustc_hir::def_id::DefId;
12 use rustc_index::vec::{Idx, IndexVec};
13 use rustc_middle::mir::Mutability;
14
15 use crate::concurrency::data_race;
16 use crate::sync::SynchronizationState;
17 use crate::*;
18
19 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
20 pub enum SchedulingAction {
21     /// Execute step on the active thread.
22     ExecuteStep,
23     /// Execute a timeout callback.
24     ExecuteTimeoutCallback,
25     /// Execute destructors of the active thread.
26     ExecuteDtors,
27     /// Stop the program.
28     Stop,
29 }
30
31 /// Timeout callbacks can be created by synchronization primitives to tell the
32 /// scheduler that they should be called once some period of time passes.
33 type TimeoutCallback<'mir, 'tcx> =
34     Box<dyn FnOnce(&mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>) -> InterpResult<'tcx> + 'tcx>;
35
36 /// A thread identifier.
37 #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
38 pub struct ThreadId(u32);
39
40 /// The main thread. When it terminates, the whole application terminates.
41 const MAIN_THREAD: ThreadId = ThreadId(0);
42
43 impl ThreadId {
44     pub fn to_u32(self) -> u32 {
45         self.0
46     }
47 }
48
49 impl Idx for ThreadId {
50     fn new(idx: usize) -> Self {
51         ThreadId(u32::try_from(idx).unwrap())
52     }
53
54     fn index(self) -> usize {
55         usize::try_from(self.0).unwrap()
56     }
57 }
58
59 impl TryFrom<u64> for ThreadId {
60     type Error = TryFromIntError;
61     fn try_from(id: u64) -> Result<Self, Self::Error> {
62         u32::try_from(id).map(Self)
63     }
64 }
65
66 impl From<u32> for ThreadId {
67     fn from(id: u32) -> Self {
68         Self(id)
69     }
70 }
71
72 impl ThreadId {
73     pub fn to_u32_scalar(&self) -> Scalar<Tag> {
74         Scalar::from_u32(self.0)
75     }
76 }
77
78 /// The state of a thread.
79 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
80 pub enum ThreadState {
81     /// The thread is enabled and can be executed.
82     Enabled,
83     /// The thread tried to join the specified thread and is blocked until that
84     /// thread terminates.
85     BlockedOnJoin(ThreadId),
86     /// The thread is blocked on some synchronization primitive. It is the
87     /// responsibility of the synchronization primitives to track threads that
88     /// are blocked by them.
89     BlockedOnSync,
90     /// The thread has terminated its execution. We do not delete terminated
91     /// threads (FIXME: why?).
92     Terminated,
93 }
94
95 /// The join status of a thread.
96 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
97 enum ThreadJoinStatus {
98     /// The thread can be joined.
99     Joinable,
100     /// A thread is detached if its join handle was destroyed and no other
101     /// thread can join it.
102     Detached,
103     /// The thread was already joined by some thread and cannot be joined again.
104     Joined,
105 }
106
107 /// A thread.
108 pub struct Thread<'mir, 'tcx> {
109     state: ThreadState,
110
111     /// Name of the thread.
112     thread_name: Option<Vec<u8>>,
113
114     /// The virtual call stack.
115     stack: Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>>,
116
117     /// The join status.
118     join_status: ThreadJoinStatus,
119
120     /// The temporary used for storing the argument of
121     /// the call to `miri_start_panic` (the panic payload) when unwinding.
122     /// This is pointer-sized, and matches the `Payload` type in `src/libpanic_unwind/miri.rs`.
123     pub(crate) panic_payload: Option<Scalar<Tag>>,
124
125     /// Last OS error location in memory. It is a 32-bit integer.
126     pub(crate) last_error: Option<MPlaceTy<'tcx, Tag>>,
127 }
128
129 impl<'mir, 'tcx> Thread<'mir, 'tcx> {
130     /// Check if the thread is done executing (no more stack frames). If yes,
131     /// change the state to terminated and return `true`.
132     fn check_terminated(&mut self) -> bool {
133         if self.state == ThreadState::Enabled {
134             if self.stack.is_empty() {
135                 self.state = ThreadState::Terminated;
136                 return true;
137             }
138         }
139         false
140     }
141
142     /// Get the name of the current thread, or `<unnamed>` if it was not set.
143     fn thread_name(&self) -> &[u8] {
144         if let Some(ref thread_name) = self.thread_name { thread_name } else { b"<unnamed>" }
145     }
146 }
147
148 impl<'mir, 'tcx> std::fmt::Debug for Thread<'mir, 'tcx> {
149     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150         write!(
151             f,
152             "{}({:?}, {:?})",
153             String::from_utf8_lossy(self.thread_name()),
154             self.state,
155             self.join_status
156         )
157     }
158 }
159
160 impl<'mir, 'tcx> Default for Thread<'mir, 'tcx> {
161     fn default() -> Self {
162         Self {
163             state: ThreadState::Enabled,
164             thread_name: None,
165             stack: Vec::new(),
166             join_status: ThreadJoinStatus::Joinable,
167             panic_payload: None,
168             last_error: None,
169         }
170     }
171 }
172
173 impl<'mir, 'tcx> Thread<'mir, 'tcx> {
174     fn new(name: &str) -> Self {
175         let mut thread = Thread::default();
176         thread.thread_name = Some(Vec::from(name.as_bytes()));
177         thread
178     }
179 }
180
181 /// A specific moment in time.
182 #[derive(Debug)]
183 pub enum Time {
184     Monotonic(Instant),
185     RealTime(SystemTime),
186 }
187
188 impl Time {
189     /// How long do we have to wait from now until the specified time?
190     fn get_wait_time(&self) -> Duration {
191         match self {
192             Time::Monotonic(instant) => instant.saturating_duration_since(Instant::now()),
193             Time::RealTime(time) =>
194                 time.duration_since(SystemTime::now()).unwrap_or(Duration::new(0, 0)),
195         }
196     }
197 }
198
199 /// Callbacks are used to implement timeouts. For example, waiting on a
200 /// conditional variable with a timeout creates a callback that is called after
201 /// the specified time and unblocks the thread. If another thread signals on the
202 /// conditional variable, the signal handler deletes the callback.
203 struct TimeoutCallbackInfo<'mir, 'tcx> {
204     /// The callback should be called no earlier than this time.
205     call_time: Time,
206     /// The called function.
207     callback: TimeoutCallback<'mir, 'tcx>,
208 }
209
210 impl<'mir, 'tcx> std::fmt::Debug for TimeoutCallbackInfo<'mir, 'tcx> {
211     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212         write!(f, "TimeoutCallback({:?})", self.call_time)
213     }
214 }
215
216 /// A set of threads.
217 #[derive(Debug)]
218 pub struct ThreadManager<'mir, 'tcx> {
219     /// Identifier of the currently active thread.
220     active_thread: ThreadId,
221     /// Threads used in the program.
222     ///
223     /// Note that this vector also contains terminated threads.
224     threads: IndexVec<ThreadId, Thread<'mir, 'tcx>>,
225     /// This field is pub(crate) because the synchronization primitives
226     /// (`crate::sync`) need a way to access it.
227     pub(crate) sync: SynchronizationState,
228     /// A mapping from a thread-local static to an allocation id of a thread
229     /// specific allocation.
230     thread_local_alloc_ids: RefCell<FxHashMap<(DefId, ThreadId), Pointer<Tag>>>,
231     /// A flag that indicates that we should change the active thread.
232     yield_active_thread: bool,
233     /// Callbacks that are called once the specified time passes.
234     timeout_callbacks: FxHashMap<ThreadId, TimeoutCallbackInfo<'mir, 'tcx>>,
235 }
236
237 impl<'mir, 'tcx> Default for ThreadManager<'mir, 'tcx> {
238     fn default() -> Self {
239         let mut threads = IndexVec::new();
240         // Create the main thread and add it to the list of threads.
241         let mut main_thread = Thread::new("main");
242         // The main thread can *not* be joined on.
243         main_thread.join_status = ThreadJoinStatus::Detached;
244         threads.push(main_thread);
245         Self {
246             active_thread: ThreadId::new(0),
247             threads,
248             sync: SynchronizationState::default(),
249             thread_local_alloc_ids: Default::default(),
250             yield_active_thread: false,
251             timeout_callbacks: FxHashMap::default(),
252         }
253     }
254 }
255
256 impl<'mir, 'tcx: 'mir> ThreadManager<'mir, 'tcx> {
257     /// Check if we have an allocation for the given thread local static for the
258     /// active thread.
259     fn get_thread_local_alloc_id(&self, def_id: DefId) -> Option<Pointer<Tag>> {
260         self.thread_local_alloc_ids.borrow().get(&(def_id, self.active_thread)).cloned()
261     }
262
263     /// Set the pointer for the allocation of the given thread local
264     /// static for the active thread.
265     ///
266     /// Panics if a thread local is initialized twice for the same thread.
267     fn set_thread_local_alloc(&self, def_id: DefId, ptr: Pointer<Tag>) {
268         self.thread_local_alloc_ids
269             .borrow_mut()
270             .try_insert((def_id, self.active_thread), ptr)
271             .unwrap();
272     }
273
274     /// Borrow the stack of the active thread.
275     pub fn active_thread_stack(&self) -> &[Frame<'mir, 'tcx, Tag, FrameData<'tcx>>] {
276         &self.threads[self.active_thread].stack
277     }
278
279     /// Mutably borrow the stack of the active thread.
280     fn active_thread_stack_mut(&mut self) -> &mut Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
281         &mut self.threads[self.active_thread].stack
282     }
283
284     /// Create a new thread and returns its id.
285     fn create_thread(&mut self) -> ThreadId {
286         let new_thread_id = ThreadId::new(self.threads.len());
287         self.threads.push(Default::default());
288         new_thread_id
289     }
290
291     /// Set an active thread and return the id of the thread that was active before.
292     fn set_active_thread_id(&mut self, id: ThreadId) -> ThreadId {
293         let active_thread_id = self.active_thread;
294         self.active_thread = id;
295         assert!(self.active_thread.index() < self.threads.len());
296         active_thread_id
297     }
298
299     /// Get the id of the currently active thread.
300     pub fn get_active_thread_id(&self) -> ThreadId {
301         self.active_thread
302     }
303
304     /// Get the total number of threads that were ever spawn by this program.
305     pub fn get_total_thread_count(&self) -> usize {
306         self.threads.len()
307     }
308
309     /// Get the total of threads that are currently live, i.e., not yet terminated.
310     /// (They might be blocked.)
311     pub fn get_live_thread_count(&self) -> usize {
312         self.threads.iter().filter(|t| !matches!(t.state, ThreadState::Terminated)).count()
313     }
314
315     /// Has the given thread terminated?
316     fn has_terminated(&self, thread_id: ThreadId) -> bool {
317         self.threads[thread_id].state == ThreadState::Terminated
318     }
319
320     /// Have all threads terminated?
321     fn have_all_terminated(&self) -> bool {
322         self.threads.iter().all(|thread| thread.state == ThreadState::Terminated)
323     }
324
325     /// Enable the thread for execution. The thread must be terminated.
326     fn enable_thread(&mut self, thread_id: ThreadId) {
327         assert!(self.has_terminated(thread_id));
328         self.threads[thread_id].state = ThreadState::Enabled;
329     }
330
331     /// Get a mutable borrow of the currently active thread.
332     fn active_thread_mut(&mut self) -> &mut Thread<'mir, 'tcx> {
333         &mut self.threads[self.active_thread]
334     }
335
336     /// Get a shared borrow of the currently active thread.
337     fn active_thread_ref(&self) -> &Thread<'mir, 'tcx> {
338         &self.threads[self.active_thread]
339     }
340
341     /// Mark the thread as detached, which means that no other thread will try
342     /// to join it and the thread is responsible for cleaning up.
343     fn detach_thread(&mut self, id: ThreadId) -> InterpResult<'tcx> {
344         if self.threads[id].join_status != ThreadJoinStatus::Joinable {
345             throw_ub_format!("trying to detach thread that was already detached or joined");
346         }
347         self.threads[id].join_status = ThreadJoinStatus::Detached;
348         Ok(())
349     }
350
351     /// Mark that the active thread tries to join the thread with `joined_thread_id`.
352     fn join_thread(
353         &mut self,
354         joined_thread_id: ThreadId,
355         data_race: Option<&mut data_race::GlobalState>,
356     ) -> InterpResult<'tcx> {
357         if self.threads[joined_thread_id].join_status != ThreadJoinStatus::Joinable {
358             throw_ub_format!("trying to join a detached or already joined thread");
359         }
360         if joined_thread_id == self.active_thread {
361             throw_ub_format!("trying to join itself");
362         }
363         assert!(
364             self.threads
365                 .iter()
366                 .all(|thread| thread.state != ThreadState::BlockedOnJoin(joined_thread_id)),
367             "a joinable thread already has threads waiting for its termination"
368         );
369         // Mark the joined thread as being joined so that we detect if other
370         // threads try to join it.
371         self.threads[joined_thread_id].join_status = ThreadJoinStatus::Joined;
372         if self.threads[joined_thread_id].state != ThreadState::Terminated {
373             // The joined thread is still running, we need to wait for it.
374             self.active_thread_mut().state = ThreadState::BlockedOnJoin(joined_thread_id);
375             trace!(
376                 "{:?} blocked on {:?} when trying to join",
377                 self.active_thread,
378                 joined_thread_id
379             );
380         } else {
381             // The thread has already terminated - mark join happens-before
382             if let Some(data_race) = data_race {
383                 data_race.thread_joined(self, self.active_thread, joined_thread_id);
384             }
385         }
386         Ok(())
387     }
388
389     /// Set the name of the active thread.
390     fn set_active_thread_name(&mut self, new_thread_name: Vec<u8>) {
391         self.active_thread_mut().thread_name = Some(new_thread_name);
392     }
393
394     /// Get the name of the active thread.
395     pub fn get_active_thread_name(&self) -> &[u8] {
396         self.active_thread_ref().thread_name()
397     }
398
399     /// Get the name of the given thread.
400     pub fn get_thread_name(&self, thread: ThreadId) -> &[u8] {
401         self.threads[thread].thread_name()
402     }
403
404     /// Put the thread into the blocked state.
405     fn block_thread(&mut self, thread: ThreadId) {
406         let state = &mut self.threads[thread].state;
407         assert_eq!(*state, ThreadState::Enabled);
408         *state = ThreadState::BlockedOnSync;
409     }
410
411     /// Put the blocked thread into the enabled state.
412     fn unblock_thread(&mut self, thread: ThreadId) {
413         let state = &mut self.threads[thread].state;
414         assert_eq!(*state, ThreadState::BlockedOnSync);
415         *state = ThreadState::Enabled;
416     }
417
418     /// Change the active thread to some enabled thread.
419     fn yield_active_thread(&mut self) {
420         // We do not yield immediately, as swapping out the current stack while executing a MIR statement
421         // could lead to all sorts of confusion.
422         // We should only switch stacks between steps.
423         self.yield_active_thread = true;
424     }
425
426     /// Register the given `callback` to be called once the `call_time` passes.
427     ///
428     /// The callback will be called with `thread` being the active thread, and
429     /// the callback may not change the active thread.
430     fn register_timeout_callback(
431         &mut self,
432         thread: ThreadId,
433         call_time: Time,
434         callback: TimeoutCallback<'mir, 'tcx>,
435     ) {
436         self.timeout_callbacks
437             .try_insert(thread, TimeoutCallbackInfo { call_time, callback })
438             .unwrap();
439     }
440
441     /// Unregister the callback for the `thread`.
442     fn unregister_timeout_callback_if_exists(&mut self, thread: ThreadId) {
443         self.timeout_callbacks.remove(&thread);
444     }
445
446     /// Get a callback that is ready to be called.
447     fn get_ready_callback(&mut self) -> Option<(ThreadId, TimeoutCallback<'mir, 'tcx>)> {
448         // We iterate over all threads in the order of their indices because
449         // this allows us to have a deterministic scheduler.
450         for thread in self.threads.indices() {
451             match self.timeout_callbacks.entry(thread) {
452                 Entry::Occupied(entry) =>
453                     if entry.get().call_time.get_wait_time() == Duration::new(0, 0) {
454                         return Some((thread, entry.remove().callback));
455                     },
456                 Entry::Vacant(_) => {}
457             }
458         }
459         None
460     }
461
462     /// Wakes up threads joining on the active one and deallocates thread-local statics.
463     /// The `AllocId` that can now be freed are returned.
464     fn thread_terminated(
465         &mut self,
466         mut data_race: Option<&mut data_race::GlobalState>,
467     ) -> Vec<Pointer<Tag>> {
468         let mut free_tls_statics = Vec::new();
469         {
470             let mut thread_local_statics = self.thread_local_alloc_ids.borrow_mut();
471             thread_local_statics.retain(|&(_def_id, thread), &mut alloc_id| {
472                 if thread != self.active_thread {
473                     // Keep this static around.
474                     return true;
475                 }
476                 // Delete this static from the map and from memory.
477                 // We cannot free directly here as we cannot use `?` in this context.
478                 free_tls_statics.push(alloc_id);
479                 false
480             });
481         }
482         // Set the thread into a terminated state in the data-race detector.
483         if let Some(ref mut data_race) = data_race {
484             data_race.thread_terminated(self);
485         }
486         // Check if we need to unblock any threads.
487         let mut joined_threads = vec![]; // store which threads joined, we'll need it
488         for (i, thread) in self.threads.iter_enumerated_mut() {
489             if thread.state == ThreadState::BlockedOnJoin(self.active_thread) {
490                 // The thread has terminated, mark happens-before edge to joining thread
491                 if data_race.is_some() {
492                     joined_threads.push(i);
493                 }
494                 trace!("unblocking {:?} because {:?} terminated", i, self.active_thread);
495                 thread.state = ThreadState::Enabled;
496             }
497         }
498         for &i in &joined_threads {
499             data_race.as_mut().unwrap().thread_joined(self, i, self.active_thread);
500         }
501         free_tls_statics
502     }
503
504     /// Decide which action to take next and on which thread.
505     ///
506     /// The currently implemented scheduling policy is the one that is commonly
507     /// used in stateless model checkers such as Loom: run the active thread as
508     /// long as we can and switch only when we have to (the active thread was
509     /// blocked, terminated, or has explicitly asked to be preempted).
510     fn schedule(&mut self) -> InterpResult<'tcx, SchedulingAction> {
511         // Check whether the thread has **just** terminated (`check_terminated`
512         // checks whether the thread has popped all its stack and if yes, sets
513         // the thread state to terminated).
514         if self.threads[self.active_thread].check_terminated() {
515             return Ok(SchedulingAction::ExecuteDtors);
516         }
517         // If we get here again and the thread is *still* terminated, there are no more dtors to run.
518         if self.threads[MAIN_THREAD].state == ThreadState::Terminated {
519             // The main thread terminated; stop the program.
520             // We do *not* run TLS dtors of remaining threads, which seems to match rustc behavior.
521             return Ok(SchedulingAction::Stop);
522         }
523         // This thread and the program can keep going.
524         if self.threads[self.active_thread].state == ThreadState::Enabled
525             && !self.yield_active_thread
526         {
527             // The currently active thread is still enabled, just continue with it.
528             return Ok(SchedulingAction::ExecuteStep);
529         }
530         // The active thread yielded. Let's see if there are any timeouts to take care of. We do
531         // this *before* running any other thread, to ensure that timeouts "in the past" fire before
532         // any other thread can take an action. This ensures that for `pthread_cond_timedwait`, "an
533         // error is returned if [...] the absolute time specified by abstime has already been passed
534         // at the time of the call".
535         // <https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html>
536         let potential_sleep_time =
537             self.timeout_callbacks.values().map(|info| info.call_time.get_wait_time()).min();
538         if potential_sleep_time == Some(Duration::new(0, 0)) {
539             return Ok(SchedulingAction::ExecuteTimeoutCallback);
540         }
541         // No callbacks scheduled, pick a regular thread to execute.
542         // The active thread blocked or yielded. So we go search for another enabled thread.
543         // Curcially, we start searching at the current active thread ID, rather than at 0, since we
544         // want to avoid always scheduling threads 0 and 1 without ever making progress in thread 2.
545         //
546         // `skip(N)` means we start iterating at thread N, so we skip 1 more to start just *after*
547         // the active thread. Then after that we look at `take(N)`, i.e., the threads *before* the
548         // active thread.
549         let threads = self
550             .threads
551             .iter_enumerated()
552             .skip(self.active_thread.index() + 1)
553             .chain(self.threads.iter_enumerated().take(self.active_thread.index()));
554         for (id, thread) in threads {
555             debug_assert_ne!(self.active_thread, id);
556             if thread.state == ThreadState::Enabled {
557                 self.active_thread = id;
558                 break;
559             }
560         }
561         self.yield_active_thread = false;
562         if self.threads[self.active_thread].state == ThreadState::Enabled {
563             return Ok(SchedulingAction::ExecuteStep);
564         }
565         // We have not found a thread to execute.
566         if self.threads.iter().all(|thread| thread.state == ThreadState::Terminated) {
567             unreachable!("all threads terminated without the main thread terminating?!");
568         } else if let Some(sleep_time) = potential_sleep_time {
569             // All threads are currently blocked, but we have unexecuted
570             // timeout_callbacks, which may unblock some of the threads. Hence,
571             // sleep until the first callback.
572             std::thread::sleep(sleep_time);
573             Ok(SchedulingAction::ExecuteTimeoutCallback)
574         } else {
575             throw_machine_stop!(TerminationInfo::Deadlock);
576         }
577     }
578 }
579
580 // Public interface to thread management.
581 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
582 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
583     /// Get a thread-specific allocation id for the given thread-local static.
584     /// If needed, allocate a new one.
585     fn get_or_create_thread_local_alloc(
586         &mut self,
587         def_id: DefId,
588     ) -> InterpResult<'tcx, Pointer<Tag>> {
589         let this = self.eval_context_mut();
590         let tcx = this.tcx;
591         if let Some(old_alloc) = this.machine.threads.get_thread_local_alloc_id(def_id) {
592             // We already have a thread-specific allocation id for this
593             // thread-local static.
594             Ok(old_alloc)
595         } else {
596             // We need to allocate a thread-specific allocation id for this
597             // thread-local static.
598             // First, we compute the initial value for this static.
599             if tcx.is_foreign_item(def_id) {
600                 throw_unsup_format!("foreign thread-local statics are not supported");
601             }
602             let allocation = tcx.eval_static_initializer(def_id)?;
603             let mut allocation = allocation.inner().clone();
604             // This allocation will be deallocated when the thread dies, so it is not in read-only memory.
605             allocation.mutability = Mutability::Mut;
606             // Create a fresh allocation with this content.
607             let new_alloc = this.allocate_raw_ptr(allocation, MiriMemoryKind::Tls.into())?;
608             this.machine.threads.set_thread_local_alloc(def_id, new_alloc);
609             Ok(new_alloc)
610         }
611     }
612
613     #[inline]
614     fn create_thread(&mut self) -> ThreadId {
615         let this = self.eval_context_mut();
616         let id = this.machine.threads.create_thread();
617         if let Some(data_race) = &mut this.machine.data_race {
618             data_race.thread_created(&this.machine.threads, id);
619         }
620         id
621     }
622
623     #[inline]
624     fn detach_thread(&mut self, thread_id: ThreadId) -> InterpResult<'tcx> {
625         let this = self.eval_context_mut();
626         this.machine.threads.detach_thread(thread_id)
627     }
628
629     #[inline]
630     fn join_thread(&mut self, joined_thread_id: ThreadId) -> InterpResult<'tcx> {
631         let this = self.eval_context_mut();
632         this.machine.threads.join_thread(joined_thread_id, this.machine.data_race.as_mut())?;
633         Ok(())
634     }
635
636     #[inline]
637     fn set_active_thread(&mut self, thread_id: ThreadId) -> ThreadId {
638         let this = self.eval_context_mut();
639         this.machine.threads.set_active_thread_id(thread_id)
640     }
641
642     #[inline]
643     fn get_active_thread(&self) -> ThreadId {
644         let this = self.eval_context_ref();
645         this.machine.threads.get_active_thread_id()
646     }
647
648     #[inline]
649     fn active_thread_mut(&mut self) -> &mut Thread<'mir, 'tcx> {
650         let this = self.eval_context_mut();
651         this.machine.threads.active_thread_mut()
652     }
653
654     #[inline]
655     fn active_thread_ref(&self) -> &Thread<'mir, 'tcx> {
656         let this = self.eval_context_ref();
657         this.machine.threads.active_thread_ref()
658     }
659
660     #[inline]
661     fn get_total_thread_count(&self) -> usize {
662         let this = self.eval_context_ref();
663         this.machine.threads.get_total_thread_count()
664     }
665
666     #[inline]
667     fn has_terminated(&self, thread_id: ThreadId) -> bool {
668         let this = self.eval_context_ref();
669         this.machine.threads.has_terminated(thread_id)
670     }
671
672     #[inline]
673     fn have_all_terminated(&self) -> bool {
674         let this = self.eval_context_ref();
675         this.machine.threads.have_all_terminated()
676     }
677
678     #[inline]
679     fn enable_thread(&mut self, thread_id: ThreadId) {
680         let this = self.eval_context_mut();
681         this.machine.threads.enable_thread(thread_id);
682     }
683
684     #[inline]
685     fn active_thread_stack(&self) -> &[Frame<'mir, 'tcx, Tag, FrameData<'tcx>>] {
686         let this = self.eval_context_ref();
687         this.machine.threads.active_thread_stack()
688     }
689
690     #[inline]
691     fn active_thread_stack_mut(&mut self) -> &mut Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
692         let this = self.eval_context_mut();
693         this.machine.threads.active_thread_stack_mut()
694     }
695
696     #[inline]
697     fn set_active_thread_name(&mut self, new_thread_name: Vec<u8>) {
698         let this = self.eval_context_mut();
699         this.machine.threads.set_active_thread_name(new_thread_name);
700     }
701
702     #[inline]
703     fn get_active_thread_name<'c>(&'c self) -> &'c [u8]
704     where
705         'mir: 'c,
706     {
707         let this = self.eval_context_ref();
708         this.machine.threads.get_active_thread_name()
709     }
710
711     #[inline]
712     fn block_thread(&mut self, thread: ThreadId) {
713         let this = self.eval_context_mut();
714         this.machine.threads.block_thread(thread);
715     }
716
717     #[inline]
718     fn unblock_thread(&mut self, thread: ThreadId) {
719         let this = self.eval_context_mut();
720         this.machine.threads.unblock_thread(thread);
721     }
722
723     #[inline]
724     fn yield_active_thread(&mut self) {
725         let this = self.eval_context_mut();
726         this.machine.threads.yield_active_thread();
727     }
728
729     #[inline]
730     fn maybe_preempt_active_thread(&mut self) {
731         use rand::Rng as _;
732
733         let this = self.eval_context_mut();
734         if this.machine.rng.get_mut().gen_bool(this.machine.preemption_rate) {
735             this.yield_active_thread();
736         }
737     }
738
739     #[inline]
740     fn register_timeout_callback(
741         &mut self,
742         thread: ThreadId,
743         call_time: Time,
744         callback: TimeoutCallback<'mir, 'tcx>,
745     ) {
746         let this = self.eval_context_mut();
747         this.machine.threads.register_timeout_callback(thread, call_time, callback);
748     }
749
750     #[inline]
751     fn unregister_timeout_callback_if_exists(&mut self, thread: ThreadId) {
752         let this = self.eval_context_mut();
753         this.machine.threads.unregister_timeout_callback_if_exists(thread);
754     }
755
756     /// Execute a timeout callback on the callback's thread.
757     #[inline]
758     fn run_timeout_callback(&mut self) -> InterpResult<'tcx> {
759         let this = self.eval_context_mut();
760         let (thread, callback) =
761             if let Some((thread, callback)) = this.machine.threads.get_ready_callback() {
762                 (thread, callback)
763             } else {
764                 // get_ready_callback can return None if the computer's clock
765                 // was shifted after calling the scheduler and before the call
766                 // to get_ready_callback (see issue
767                 // https://github.com/rust-lang/miri/issues/1763). In this case,
768                 // just do nothing, which effectively just returns to the
769                 // scheduler.
770                 return Ok(());
771             };
772         // This back-and-forth with `set_active_thread` is here because of two
773         // design decisions:
774         // 1. Make the caller and not the callback responsible for changing
775         //    thread.
776         // 2. Make the scheduler the only place that can change the active
777         //    thread.
778         let old_thread = this.set_active_thread(thread);
779         callback(this)?;
780         this.set_active_thread(old_thread);
781         Ok(())
782     }
783
784     /// Decide which action to take next and on which thread.
785     #[inline]
786     fn schedule(&mut self) -> InterpResult<'tcx, SchedulingAction> {
787         let this = self.eval_context_mut();
788         this.machine.threads.schedule()
789     }
790
791     /// Handles thread termination of the active thread: wakes up threads joining on this one,
792     /// and deallocated thread-local statics.
793     ///
794     /// This is called from `tls.rs` after handling the TLS dtors.
795     #[inline]
796     fn thread_terminated(&mut self) -> InterpResult<'tcx> {
797         let this = self.eval_context_mut();
798         for ptr in this.machine.threads.thread_terminated(this.machine.data_race.as_mut()) {
799             this.deallocate_ptr(ptr.into(), None, MiriMemoryKind::Tls.into())?;
800         }
801         Ok(())
802     }
803 }