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