]> git.lizzy.rs Git - rust.git/blob - src/thread.rs
Fail 80% of the time on weak cmpxchg, not 50%
[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::rc::Rc;
7 use std::num::TryFromIntError;
8 use std::time::{Duration, Instant, SystemTime};
9
10 use log::trace;
11
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_hir::def_id::DefId;
14 use rustc_index::vec::{Idx, IndexVec};
15
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(|id_u32| Self(id_u32))
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<'tcx>(&self) -> Scalar<Tag> {
74         Scalar::from_u32(u32::try_from(self.0).unwrap())
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 {
145             thread_name
146         } else {
147             b"<unnamed>"
148         }
149     }
150 }
151
152 impl<'mir, 'tcx> std::fmt::Debug for Thread<'mir, 'tcx> {
153     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154         write!(f, "{}({:?}, {:?})", String::from_utf8_lossy(self.thread_name()), self.state, self.join_status)
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), AllocId>>,
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<AllocId> {
250         self.thread_local_alloc_ids.borrow().get(&(def_id, self.active_thread)).cloned()
251     }
252
253     /// Set the allocation id as the allocation id 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_id(&self, def_id: DefId, new_alloc_id: AllocId) {
258         self.thread_local_alloc_ids
259             .borrow_mut()
260             .insert((def_id, self.active_thread), new_alloc_id)
261             .unwrap_none();
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     /// Enable the thread for execution. The thread must be terminated.
305     fn enable_thread(&mut self, thread_id: ThreadId) {
306         assert!(self.has_terminated(thread_id));
307         self.threads[thread_id].state = ThreadState::Enabled;
308     }
309
310     /// Get a mutable borrow of the currently active thread.
311     fn active_thread_mut(&mut self) -> &mut Thread<'mir, 'tcx> {
312         &mut self.threads[self.active_thread]
313     }
314
315     /// Get a shared borrow of the currently active thread.
316     fn active_thread_ref(&self) -> &Thread<'mir, 'tcx> {
317         &self.threads[self.active_thread]
318     }
319
320     /// Mark the thread as detached, which means that no other thread will try
321     /// to join it and the thread is responsible for cleaning up.
322     fn detach_thread(&mut self, id: ThreadId) -> InterpResult<'tcx> {
323         if self.threads[id].join_status != ThreadJoinStatus::Joinable {
324             throw_ub_format!("trying to detach thread that was already detached or joined");
325         }
326         self.threads[id].join_status = ThreadJoinStatus::Detached;
327         Ok(())
328     }
329
330     /// Mark that the active thread tries to join the thread with `joined_thread_id`.
331     fn join_thread(&mut self, joined_thread_id: ThreadId, data_race: &Option<Rc<data_race::GlobalState>>) -> InterpResult<'tcx> {
332         if self.threads[joined_thread_id].join_status != ThreadJoinStatus::Joinable {
333             throw_ub_format!("trying to join a detached or already joined thread");
334         }
335         if joined_thread_id == self.active_thread {
336             throw_ub_format!("trying to join itself");
337         }
338         assert!(
339             self.threads
340                 .iter()
341                 .all(|thread| thread.state != ThreadState::BlockedOnJoin(joined_thread_id)),
342             "a joinable thread already has threads waiting for its termination"
343         );
344         // Mark the joined thread as being joined so that we detect if other
345         // threads try to join it.
346         self.threads[joined_thread_id].join_status = ThreadJoinStatus::Joined;
347         if self.threads[joined_thread_id].state != ThreadState::Terminated {
348             // The joined thread is still running, we need to wait for it.
349             self.active_thread_mut().state = ThreadState::BlockedOnJoin(joined_thread_id);
350             trace!(
351                 "{:?} blocked on {:?} when trying to join",
352                 self.active_thread,
353                 joined_thread_id
354             );
355         } else {
356             // The thread has already terminated - mark join happens-before
357             if let Some(data_race) = data_race {
358                 data_race.thread_joined(self.active_thread, joined_thread_id);
359             }
360         }
361         Ok(())
362     }
363
364     /// Set the name of the active thread.
365     fn set_thread_name(&mut self, new_thread_name: Vec<u8>) {
366         self.active_thread_mut().thread_name = Some(new_thread_name);
367     }
368
369     /// Get the name of the active thread.
370     fn get_thread_name(&self) -> &[u8] {
371         self.active_thread_ref().thread_name()
372     }
373
374     /// Put the thread into the blocked state.
375     fn block_thread(&mut self, thread: ThreadId) {
376         let state = &mut self.threads[thread].state;
377         assert_eq!(*state, ThreadState::Enabled);
378         *state = ThreadState::BlockedOnSync;
379     }
380
381     /// Put the blocked thread into the enabled state.
382     fn unblock_thread(&mut self, thread: ThreadId) {
383         let state = &mut self.threads[thread].state;
384         assert_eq!(*state, ThreadState::BlockedOnSync);
385         *state = ThreadState::Enabled;
386     }
387
388     /// Change the active thread to some enabled thread.
389     fn yield_active_thread(&mut self) {
390         // We do not yield immediately, as swapping out the current stack while executing a MIR statement
391         // could lead to all sorts of confusion.
392         // We should only switch stacks between steps.
393         self.yield_active_thread = true;
394     }
395
396     /// Register the given `callback` to be called once the `call_time` passes.
397     ///
398     /// The callback will be called with `thread` being the active thread, and
399     /// the callback may not change the active thread.
400     fn register_timeout_callback(
401         &mut self,
402         thread: ThreadId,
403         call_time: Time,
404         callback: TimeoutCallback<'mir, 'tcx>,
405     ) {
406         self.timeout_callbacks
407             .insert(thread, TimeoutCallbackInfo { call_time, callback })
408             .unwrap_none();
409     }
410
411     /// Unregister the callback for the `thread`.
412     fn unregister_timeout_callback_if_exists(&mut self, thread: ThreadId) {
413         self.timeout_callbacks.remove(&thread);
414     }
415
416     /// Get a callback that is ready to be called.
417     fn get_ready_callback(&mut self) -> Option<(ThreadId, TimeoutCallback<'mir, 'tcx>)> {
418         // We iterate over all threads in the order of their indices because
419         // this allows us to have a deterministic scheduler.
420         for thread in self.threads.indices() {
421             match self.timeout_callbacks.entry(thread) {
422                 Entry::Occupied(entry) =>
423                     if entry.get().call_time.get_wait_time() == Duration::new(0, 0) {
424                         return Some((thread, entry.remove().callback));
425                     },
426                 Entry::Vacant(_) => {}
427             }
428         }
429         None
430     }
431
432     /// Wakes up threads joining on the active one and deallocates thread-local statics.
433     /// The `AllocId` that can now be freed is returned.
434     fn thread_terminated(&mut self, data_race: &Option<Rc<data_race::GlobalState>>) -> Vec<AllocId> {
435         let mut free_tls_statics = Vec::new();
436         {
437             let mut thread_local_statics = self.thread_local_alloc_ids.borrow_mut();
438             thread_local_statics.retain(|&(_def_id, thread), &mut alloc_id| {
439                 if thread != self.active_thread {
440                     // Keep this static around.
441                     return true;
442                 }
443                 // Delete this static from the map and from memory.
444                 // We cannot free directly here as we cannot use `?` in this context.
445                 free_tls_statics.push(alloc_id);
446                 return false;
447             });
448         }
449         // Set the thread into a terminated state in the data-race detector
450         if let Some(data_race) = data_race {
451             data_race.thread_terminated();
452         }
453         // Check if we need to unblock any threads.
454         for (i, thread) in self.threads.iter_enumerated_mut() {
455             if thread.state == ThreadState::BlockedOnJoin(self.active_thread) {
456                 // The thread has terminated, mark happens-before edge to joining thread
457                 if let Some(data_race) = data_race {
458                     data_race.thread_joined(i, self.active_thread);
459                 }
460                 trace!("unblocking {:?} because {:?} terminated", i, self.active_thread);
461                 thread.state = ThreadState::Enabled;
462             }
463         }
464         return free_tls_statics;
465     }
466
467     /// Decide which action to take next and on which thread.
468     ///
469     /// The currently implemented scheduling policy is the one that is commonly
470     /// used in stateless model checkers such as Loom: run the active thread as
471     /// long as we can and switch only when we have to (the active thread was
472     /// blocked, terminated, or has explicitly asked to be preempted).
473     fn schedule(&mut self, data_race: &Option<Rc<data_race::GlobalState>>) -> InterpResult<'tcx, SchedulingAction> {
474         // Check whether the thread has **just** terminated (`check_terminated`
475         // checks whether the thread has popped all its stack and if yes, sets
476         // the thread state to terminated).
477         if self.threads[self.active_thread].check_terminated() {
478             return Ok(SchedulingAction::ExecuteDtors);
479         }
480         if self.threads[MAIN_THREAD].state == ThreadState::Terminated {
481             // The main thread terminated; stop the program.
482             if self.threads.iter().any(|thread| thread.state != ThreadState::Terminated) {
483                 // FIXME: This check should be either configurable or just emit
484                 // a warning. For example, it seems normal for a program to
485                 // terminate without waiting for its detached threads to
486                 // terminate. However, this case is not trivial to support
487                 // because we also probably do not want to consider the memory
488                 // owned by these threads as leaked.
489                 throw_unsup_format!("the main thread terminated without waiting for other threads");
490             }
491             return Ok(SchedulingAction::Stop);
492         }
493         // At least for `pthread_cond_timedwait` we need to report timeout when
494         // the function is called already after the specified time even if a
495         // signal is received before the thread gets scheduled. Therefore, we
496         // need to schedule all timeout callbacks before we continue regular
497         // execution.
498         //
499         // Documentation:
500         // https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html#
501         let potential_sleep_time =
502             self.timeout_callbacks.values().map(|info| info.call_time.get_wait_time()).min();
503         if potential_sleep_time == Some(Duration::new(0, 0)) {
504             return Ok(SchedulingAction::ExecuteTimeoutCallback);
505         }
506         // No callbacks scheduled, pick a regular thread to execute.
507         if self.threads[self.active_thread].state == ThreadState::Enabled
508             && !self.yield_active_thread
509         {
510             // The currently active thread is still enabled, just continue with it.
511             return Ok(SchedulingAction::ExecuteStep);
512         }
513         // We need to pick a new thread for execution.
514         for (id, thread) in self.threads.iter_enumerated() {
515             if thread.state == ThreadState::Enabled {
516                 if !self.yield_active_thread || id != self.active_thread {
517                     self.active_thread = id;
518                     if let Some(data_race) = data_race {
519                         data_race.thread_set_active(self.active_thread);
520                     }
521                     break;
522                 }
523             }
524         }
525         self.yield_active_thread = false;
526         if self.threads[self.active_thread].state == ThreadState::Enabled {
527             return Ok(SchedulingAction::ExecuteStep);
528         }
529         // We have not found a thread to execute.
530         if self.threads.iter().all(|thread| thread.state == ThreadState::Terminated) {
531             unreachable!("all threads terminated without the main thread terminating?!");
532         } else if let Some(sleep_time) = potential_sleep_time {
533             // All threads are currently blocked, but we have unexecuted
534             // timeout_callbacks, which may unblock some of the threads. Hence,
535             // sleep until the first callback.
536             std::thread::sleep(sleep_time);
537             Ok(SchedulingAction::ExecuteTimeoutCallback)
538         } else {
539             throw_machine_stop!(TerminationInfo::Deadlock);
540         }
541     }
542 }
543
544 // Public interface to thread management.
545 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
546 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
547     /// Get a thread-specific allocation id for the given thread-local static.
548     /// If needed, allocate a new one.
549     fn get_or_create_thread_local_alloc_id(&mut self, def_id: DefId) -> InterpResult<'tcx, AllocId> {
550         let this = self.eval_context_mut();
551         let tcx = this.tcx;
552         if let Some(new_alloc_id) = this.machine.threads.get_thread_local_alloc_id(def_id) {
553             // We already have a thread-specific allocation id for this
554             // thread-local static.
555             Ok(new_alloc_id)
556         } else {
557             // We need to allocate a thread-specific allocation id for this
558             // thread-local static.
559             // First, we compute the initial value for this static.
560             if tcx.is_foreign_item(def_id) {
561                 throw_unsup_format!("foreign thread-local statics are not supported");
562             }
563             let allocation = tcx.eval_static_initializer(def_id)?;
564             // Create a fresh allocation with this content.
565             let new_alloc_id = this.memory.allocate_with(allocation.clone(), MiriMemoryKind::Tls.into()).alloc_id;
566             this.machine.threads.set_thread_local_alloc_id(def_id, new_alloc_id);
567             Ok(new_alloc_id)
568         }
569     }
570
571     #[inline]
572     fn create_thread(&mut self) -> ThreadId {
573         let this = self.eval_context_mut();
574         let id = this.machine.threads.create_thread();
575         if let Some(data_race) = &this.memory.extra.data_race {
576             data_race.thread_created(id);
577         }
578         id
579     }
580
581     #[inline]
582     fn detach_thread(&mut self, thread_id: ThreadId) -> InterpResult<'tcx> {
583         let this = self.eval_context_mut();
584         this.machine.threads.detach_thread(thread_id)
585     }
586
587     #[inline]
588     fn join_thread(&mut self, joined_thread_id: ThreadId) -> InterpResult<'tcx> {
589         let this = self.eval_context_mut();
590         let data_race = &this.memory.extra.data_race;
591         this.machine.threads.join_thread(joined_thread_id, data_race)?;
592         Ok(())
593     }
594
595     #[inline]
596     fn set_active_thread(&mut self, thread_id: ThreadId) -> ThreadId {
597         let this = self.eval_context_mut();
598         if let Some(data_race) = &this.memory.extra.data_race {
599             data_race.thread_set_active(thread_id);
600         }
601         this.machine.threads.set_active_thread_id(thread_id)
602     }
603
604     #[inline]
605     fn get_active_thread(&self) -> ThreadId {
606         let this = self.eval_context_ref();
607         this.machine.threads.get_active_thread_id()
608     }
609
610     #[inline]
611     fn active_thread_mut(&mut self) -> &mut Thread<'mir, 'tcx> {
612         let this = self.eval_context_mut();
613         this.machine.threads.active_thread_mut()
614     }
615
616     #[inline]
617     fn active_thread_ref(&self) -> &Thread<'mir, 'tcx> {
618         let this = self.eval_context_ref();
619         this.machine.threads.active_thread_ref()
620     }
621
622     #[inline]
623     fn get_total_thread_count(&self) -> usize {
624         let this = self.eval_context_ref();
625         this.machine.threads.get_total_thread_count()
626     }
627
628     #[inline]
629     fn has_terminated(&self, thread_id: ThreadId) -> bool {
630         let this = self.eval_context_ref();
631         this.machine.threads.has_terminated(thread_id)
632     }
633
634     #[inline]
635     fn enable_thread(&mut self, thread_id: ThreadId) {
636         let this = self.eval_context_mut();
637         this.machine.threads.enable_thread(thread_id);
638     }
639
640     #[inline]
641     fn active_thread_stack(&self) -> &[Frame<'mir, 'tcx, Tag, FrameData<'tcx>>] {
642         let this = self.eval_context_ref();
643         this.machine.threads.active_thread_stack()
644     }
645
646     #[inline]
647     fn active_thread_stack_mut(&mut self) -> &mut Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
648         let this = self.eval_context_mut();
649         this.machine.threads.active_thread_stack_mut()
650     }
651
652     #[inline]
653     fn set_active_thread_name(&mut self, new_thread_name: Vec<u8>) {
654         let this = self.eval_context_mut();
655         if let Some(data_race) = &this.memory.extra.data_race {
656             if let Ok(string) = String::from_utf8(new_thread_name.clone()) {
657                 data_race.thread_set_name(
658                     this.machine.threads.active_thread, string
659                 );
660             }
661         }
662         this.machine.threads.set_thread_name(new_thread_name);
663     }
664
665     #[inline]
666     fn get_active_thread_name<'c>(&'c self) -> &'c [u8]
667     where
668         'mir: 'c,
669     {
670         let this = self.eval_context_ref();
671         this.machine.threads.get_thread_name()
672     }
673
674     #[inline]
675     fn block_thread(&mut self, thread: ThreadId) {
676         let this = self.eval_context_mut();
677         this.machine.threads.block_thread(thread);
678     }
679
680     #[inline]
681     fn unblock_thread(&mut self, thread: ThreadId) {
682         let this = self.eval_context_mut();
683         this.machine.threads.unblock_thread(thread);
684     }
685
686     #[inline]
687     fn yield_active_thread(&mut self) {
688         let this = self.eval_context_mut();
689         this.machine.threads.yield_active_thread();
690     }
691
692     #[inline]
693     fn register_timeout_callback(
694         &mut self,
695         thread: ThreadId,
696         call_time: Time,
697         callback: TimeoutCallback<'mir, 'tcx>,
698     ) {
699         let this = self.eval_context_mut();
700         this.machine.threads.register_timeout_callback(thread, call_time, callback);
701     }
702
703     #[inline]
704     fn unregister_timeout_callback_if_exists(&mut self, thread: ThreadId) {
705         let this = self.eval_context_mut();
706         this.machine.threads.unregister_timeout_callback_if_exists(thread);
707     }
708
709     /// Execute a timeout callback on the callback's thread.
710     #[inline]
711     fn run_timeout_callback(&mut self) -> InterpResult<'tcx> {
712         let this = self.eval_context_mut();
713         let (thread, callback) =
714             this.machine.threads.get_ready_callback().expect("no callback found");
715         // This back-and-forth with `set_active_thread` is here because of two
716         // design decisions:
717         // 1. Make the caller and not the callback responsible for changing
718         //    thread.
719         // 2. Make the scheduler the only place that can change the active
720         //    thread.
721         let old_thread = this.set_active_thread(thread);
722         callback(this)?;
723         this.set_active_thread(old_thread);
724         Ok(())
725     }
726
727     /// Decide which action to take next and on which thread.
728     #[inline]
729     fn schedule(&mut self) -> InterpResult<'tcx, SchedulingAction> {
730         let this = self.eval_context_mut();
731         let data_race = &this.memory.extra.data_race;
732         this.machine.threads.schedule(data_race)
733     }
734
735     /// Handles thread termination of the active thread: wakes up threads joining on this one,
736     /// and deallocated thread-local statics.
737     ///
738     /// This is called from `tls.rs` after handling the TLS dtors.
739     #[inline]
740     fn thread_terminated(&mut self) -> InterpResult<'tcx> {
741         let this = self.eval_context_mut();
742         let data_race = &this.memory.extra.data_race;
743         for alloc_id in this.machine.threads.thread_terminated(data_race) {
744             let ptr = this.memory.global_base_pointer(alloc_id.into())?;
745             this.memory.deallocate(ptr, None, MiriMemoryKind::Tls.into())?;
746         }
747         Ok(())
748     }
749 }