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