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