]> git.lizzy.rs Git - rust.git/blob - src/thread.rs
get_or_create_thread_local_alloc_id: share code with Memory::get_global_alloc
[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     /// Name of the thread.
110     thread_name: Option<Vec<u8>>,
111     /// The virtual call stack.
112     stack: Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>>,
113     /// The join status.
114     join_status: ThreadJoinStatus,
115 }
116
117 impl<'mir, 'tcx> Thread<'mir, 'tcx> {
118     /// Check if the thread is done executing (no more stack frames). If yes,
119     /// change the state to terminated and return `true`.
120     fn check_terminated(&mut self) -> bool {
121         if self.state == ThreadState::Enabled {
122             if self.stack.is_empty() {
123                 self.state = ThreadState::Terminated;
124                 return true;
125             }
126         }
127         false
128     }
129
130     /// Get the name of the current thread, or `<unnamed>` if it was not set.
131     fn thread_name(&self) -> &[u8] {
132         if let Some(ref thread_name) = self.thread_name {
133             thread_name
134         } else {
135             b"<unnamed>"
136         }
137     }
138 }
139
140 impl<'mir, 'tcx> std::fmt::Debug for Thread<'mir, 'tcx> {
141     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142         write!(f, "{}({:?}, {:?})", String::from_utf8_lossy(self.thread_name()), self.state, self.join_status)
143     }
144 }
145
146 impl<'mir, 'tcx> Default for Thread<'mir, 'tcx> {
147     fn default() -> Self {
148         Self {
149             state: ThreadState::Enabled,
150             thread_name: None,
151             stack: Vec::new(),
152             join_status: ThreadJoinStatus::Joinable,
153         }
154     }
155 }
156
157 /// A specific moment in time.
158 #[derive(Debug)]
159 pub enum Time {
160     Monotonic(Instant),
161     RealTime(SystemTime),
162 }
163
164 impl Time {
165     /// How long do we have to wait from now until the specified time?
166     fn get_wait_time(&self) -> Duration {
167         match self {
168             Time::Monotonic(instant) => instant.saturating_duration_since(Instant::now()),
169             Time::RealTime(time) =>
170                 time.duration_since(SystemTime::now()).unwrap_or(Duration::new(0, 0)),
171         }
172     }
173 }
174
175 /// Callbacks are used to implement timeouts. For example, waiting on a
176 /// conditional variable with a timeout creates a callback that is called after
177 /// the specified time and unblocks the thread. If another thread signals on the
178 /// conditional variable, the signal handler deletes the callback.
179 struct TimeoutCallbackInfo<'mir, 'tcx> {
180     /// The callback should be called no earlier than this time.
181     call_time: Time,
182     /// The called function.
183     callback: TimeoutCallback<'mir, 'tcx>,
184 }
185
186 impl<'mir, 'tcx> std::fmt::Debug for TimeoutCallbackInfo<'mir, 'tcx> {
187     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
188         write!(f, "TimeoutCallback({:?})", self.call_time)
189     }
190 }
191
192 /// A set of threads.
193 #[derive(Debug)]
194 pub struct ThreadManager<'mir, 'tcx> {
195     /// Identifier of the currently active thread.
196     active_thread: ThreadId,
197     /// Threads used in the program.
198     ///
199     /// Note that this vector also contains terminated threads.
200     threads: IndexVec<ThreadId, Thread<'mir, 'tcx>>,
201     /// This field is pub(crate) because the synchronization primitives
202     /// (`crate::sync`) need a way to access it.
203     pub(crate) sync: SynchronizationState,
204     /// A mapping from a thread-local static to an allocation id of a thread
205     /// specific allocation.
206     thread_local_alloc_ids: RefCell<FxHashMap<(DefId, ThreadId), AllocId>>,
207     /// A flag that indicates that we should change the active thread.
208     yield_active_thread: bool,
209     /// Callbacks that are called once the specified time passes.
210     timeout_callbacks: FxHashMap<ThreadId, TimeoutCallbackInfo<'mir, 'tcx>>,
211 }
212
213 impl<'mir, 'tcx> Default for ThreadManager<'mir, 'tcx> {
214     fn default() -> Self {
215         let mut threads = IndexVec::new();
216         // Create the main thread and add it to the list of threads.
217         let mut main_thread = Thread::default();
218         // The main thread can *not* be joined on.
219         main_thread.join_status = ThreadJoinStatus::Detached;
220         threads.push(main_thread);
221         Self {
222             active_thread: ThreadId::new(0),
223             threads: threads,
224             sync: SynchronizationState::default(),
225             thread_local_alloc_ids: Default::default(),
226             yield_active_thread: false,
227             timeout_callbacks: FxHashMap::default(),
228         }
229     }
230 }
231
232 impl<'mir, 'tcx: 'mir> ThreadManager<'mir, 'tcx> {
233     /// Check if we have an allocation for the given thread local static for the
234     /// active thread.
235     fn get_thread_local_alloc_id(&self, def_id: DefId) -> Option<AllocId> {
236         self.thread_local_alloc_ids.borrow().get(&(def_id, self.active_thread)).cloned()
237     }
238
239     /// Set the allocation id as the allocation id of the given thread local
240     /// static for the active thread.
241     ///
242     /// Panics if a thread local is initialized twice for the same thread.
243     fn set_thread_local_alloc_id(&self, def_id: DefId, new_alloc_id: AllocId) {
244         self.thread_local_alloc_ids
245             .borrow_mut()
246             .insert((def_id, self.active_thread), new_alloc_id)
247             .unwrap_none();
248     }
249
250     /// Borrow the stack of the active thread.
251     fn active_thread_stack(&self) -> &[Frame<'mir, 'tcx, Tag, FrameData<'tcx>>] {
252         &self.threads[self.active_thread].stack
253     }
254
255     /// Mutably borrow the stack of the active thread.
256     fn active_thread_stack_mut(&mut self) -> &mut Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
257         &mut self.threads[self.active_thread].stack
258     }
259
260     /// Create a new thread and returns its id.
261     fn create_thread(&mut self) -> ThreadId {
262         let new_thread_id = ThreadId::new(self.threads.len());
263         self.threads.push(Default::default());
264         new_thread_id
265     }
266
267     /// Set an active thread and return the id of the thread that was active before.
268     fn set_active_thread_id(&mut self, id: ThreadId) -> ThreadId {
269         let active_thread_id = self.active_thread;
270         self.active_thread = id;
271         assert!(self.active_thread.index() < self.threads.len());
272         active_thread_id
273     }
274
275     /// Get the id of the currently active thread.
276     fn get_active_thread_id(&self) -> ThreadId {
277         self.active_thread
278     }
279
280     /// Get the total number of threads that were ever spawn by this program.
281     fn get_total_thread_count(&self) -> usize {
282         self.threads.len()
283     }
284
285     /// Has the given thread terminated?
286     fn has_terminated(&self, thread_id: ThreadId) -> bool {
287         self.threads[thread_id].state == ThreadState::Terminated
288     }
289
290     /// Enable the thread for execution. The thread must be terminated.
291     fn enable_thread(&mut self, thread_id: ThreadId) {
292         assert!(self.has_terminated(thread_id));
293         self.threads[thread_id].state = ThreadState::Enabled;
294     }
295
296     /// Get a mutable borrow of the currently active thread.
297     fn active_thread_mut(&mut self) -> &mut Thread<'mir, 'tcx> {
298         &mut self.threads[self.active_thread]
299     }
300
301     /// Get a shared borrow of the currently active thread.
302     fn active_thread_ref(&self) -> &Thread<'mir, 'tcx> {
303         &self.threads[self.active_thread]
304     }
305
306     /// Mark the thread as detached, which means that no other thread will try
307     /// to join it and the thread is responsible for cleaning up.
308     fn detach_thread(&mut self, id: ThreadId) -> InterpResult<'tcx> {
309         if self.threads[id].join_status != ThreadJoinStatus::Joinable {
310             throw_ub_format!("trying to detach thread that was already detached or joined");
311         }
312         self.threads[id].join_status = ThreadJoinStatus::Detached;
313         Ok(())
314     }
315
316     /// Mark that the active thread tries to join the thread with `joined_thread_id`.
317     fn join_thread(&mut self, joined_thread_id: ThreadId) -> InterpResult<'tcx> {
318         if self.threads[joined_thread_id].join_status != ThreadJoinStatus::Joinable {
319             throw_ub_format!("trying to join a detached or already joined thread");
320         }
321         if joined_thread_id == self.active_thread {
322             throw_ub_format!("trying to join itself");
323         }
324         assert!(
325             self.threads
326                 .iter()
327                 .all(|thread| thread.state != ThreadState::BlockedOnJoin(joined_thread_id)),
328             "a joinable thread already has threads waiting for its termination"
329         );
330         // Mark the joined thread as being joined so that we detect if other
331         // threads try to join it.
332         self.threads[joined_thread_id].join_status = ThreadJoinStatus::Joined;
333         if self.threads[joined_thread_id].state != ThreadState::Terminated {
334             // The joined thread is still running, we need to wait for it.
335             self.active_thread_mut().state = ThreadState::BlockedOnJoin(joined_thread_id);
336             trace!(
337                 "{:?} blocked on {:?} when trying to join",
338                 self.active_thread,
339                 joined_thread_id
340             );
341         }
342         Ok(())
343     }
344
345     /// Set the name of the active thread.
346     fn set_thread_name(&mut self, new_thread_name: Vec<u8>) {
347         self.active_thread_mut().thread_name = Some(new_thread_name);
348     }
349
350     /// Get the name of the active thread.
351     fn get_thread_name(&self) -> &[u8] {
352         self.active_thread_ref().thread_name()
353     }
354
355     /// Put the thread into the blocked state.
356     fn block_thread(&mut self, thread: ThreadId) {
357         let state = &mut self.threads[thread].state;
358         assert_eq!(*state, ThreadState::Enabled);
359         *state = ThreadState::BlockedOnSync;
360     }
361
362     /// Put the blocked thread into the enabled state.
363     fn unblock_thread(&mut self, thread: ThreadId) {
364         let state = &mut self.threads[thread].state;
365         assert_eq!(*state, ThreadState::BlockedOnSync);
366         *state = ThreadState::Enabled;
367     }
368
369     /// Change the active thread to some enabled thread.
370     fn yield_active_thread(&mut self) {
371         // We do not yield immediately, as swapping out the current stack while executing a MIR statement
372         // could lead to all sorts of confusion.
373         // We should only switch stacks between steps.
374         self.yield_active_thread = true;
375     }
376
377     /// Register the given `callback` to be called once the `call_time` passes.
378     ///
379     /// The callback will be called with `thread` being the active thread, and
380     /// the callback may not change the active thread.
381     fn register_timeout_callback(
382         &mut self,
383         thread: ThreadId,
384         call_time: Time,
385         callback: TimeoutCallback<'mir, 'tcx>,
386     ) {
387         self.timeout_callbacks
388             .insert(thread, TimeoutCallbackInfo { call_time, callback })
389             .unwrap_none();
390     }
391
392     /// Unregister the callback for the `thread`.
393     fn unregister_timeout_callback_if_exists(&mut self, thread: ThreadId) {
394         self.timeout_callbacks.remove(&thread);
395     }
396
397     /// Get a callback that is ready to be called.
398     fn get_ready_callback(&mut self) -> Option<(ThreadId, TimeoutCallback<'mir, 'tcx>)> {
399         // We iterate over all threads in the order of their indices because
400         // this allows us to have a deterministic scheduler.
401         for thread in self.threads.indices() {
402             match self.timeout_callbacks.entry(thread) {
403                 Entry::Occupied(entry) =>
404                     if entry.get().call_time.get_wait_time() == Duration::new(0, 0) {
405                         return Some((thread, entry.remove().callback));
406                     },
407                 Entry::Vacant(_) => {}
408             }
409         }
410         None
411     }
412
413     /// Decide which action to take next and on which thread.
414     ///
415     /// The currently implemented scheduling policy is the one that is commonly
416     /// used in stateless model checkers such as Loom: run the active thread as
417     /// long as we can and switch only when we have to (the active thread was
418     /// blocked, terminated, or has explicitly asked to be preempted).
419     fn schedule(&mut self) -> InterpResult<'tcx, SchedulingAction> {
420         // Check whether the thread has **just** terminated (`check_terminated`
421         // checks whether the thread has popped all its stack and if yes, sets
422         // the thread state to terminated).
423         if self.threads[self.active_thread].check_terminated() {
424             // Check if we need to unblock any threads.
425             for (i, thread) in self.threads.iter_enumerated_mut() {
426                 if thread.state == ThreadState::BlockedOnJoin(self.active_thread) {
427                     trace!("unblocking {:?} because {:?} terminated", i, self.active_thread);
428                     thread.state = ThreadState::Enabled;
429                 }
430             }
431             return Ok(SchedulingAction::ExecuteDtors);
432         }
433         if self.threads[MAIN_THREAD].state == ThreadState::Terminated {
434             // The main thread terminated; stop the program.
435             if self.threads.iter().any(|thread| thread.state != ThreadState::Terminated) {
436                 // FIXME: This check should be either configurable or just emit
437                 // a warning. For example, it seems normal for a program to
438                 // terminate without waiting for its detached threads to
439                 // terminate. However, this case is not trivial to support
440                 // because we also probably do not want to consider the memory
441                 // owned by these threads as leaked.
442                 throw_unsup_format!("the main thread terminated without waiting for other threads");
443             }
444             return Ok(SchedulingAction::Stop);
445         }
446         // At least for `pthread_cond_timedwait` we need to report timeout when
447         // the function is called already after the specified time even if a
448         // signal is received before the thread gets scheduled. Therefore, we
449         // need to schedule all timeout callbacks before we continue regular
450         // execution.
451         //
452         // Documentation:
453         // https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html#
454         let potential_sleep_time =
455             self.timeout_callbacks.values().map(|info| info.call_time.get_wait_time()).min();
456         if potential_sleep_time == Some(Duration::new(0, 0)) {
457             return Ok(SchedulingAction::ExecuteTimeoutCallback);
458         }
459         // No callbacks scheduled, pick a regular thread to execute.
460         if self.threads[self.active_thread].state == ThreadState::Enabled
461             && !self.yield_active_thread
462         {
463             // The currently active thread is still enabled, just continue with it.
464             return Ok(SchedulingAction::ExecuteStep);
465         }
466         // We need to pick a new thread for execution.
467         for (id, thread) in self.threads.iter_enumerated() {
468             if thread.state == ThreadState::Enabled {
469                 if !self.yield_active_thread || id != self.active_thread {
470                     self.active_thread = id;
471                     break;
472                 }
473             }
474         }
475         self.yield_active_thread = false;
476         if self.threads[self.active_thread].state == ThreadState::Enabled {
477             return Ok(SchedulingAction::ExecuteStep);
478         }
479         // We have not found a thread to execute.
480         if self.threads.iter().all(|thread| thread.state == ThreadState::Terminated) {
481             unreachable!("all threads terminated without the main thread terminating?!");
482         } else if let Some(sleep_time) = potential_sleep_time {
483             // All threads are currently blocked, but we have unexecuted
484             // timeout_callbacks, which may unblock some of the threads. Hence,
485             // sleep until the first callback.
486             std::thread::sleep(sleep_time);
487             Ok(SchedulingAction::ExecuteTimeoutCallback)
488         } else {
489             throw_machine_stop!(TerminationInfo::Deadlock);
490         }
491     }
492 }
493
494 // Public interface to thread management.
495 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
496 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
497     /// Get a thread-specific allocation id for the given thread-local static.
498     /// If needed, allocate a new one.
499     fn get_or_create_thread_local_alloc_id(&self, def_id: DefId) -> InterpResult<'tcx, AllocId> {
500         let this = self.eval_context_ref();
501         let tcx = this.tcx;
502         if let Some(new_alloc_id) = this.machine.threads.get_thread_local_alloc_id(def_id) {
503             // We already have a thread-specific allocation id for this
504             // thread-local static.
505             Ok(new_alloc_id)
506         } else {
507             // We need to allocate a thread-specific allocation id for this
508             // thread-local static.
509             //
510             // At first, we compute the initial value for this static.
511             // Then we store the retrieved allocation back into the `alloc_map`
512             // to get a fresh allocation id, which we can use as a
513             // thread-specific allocation id for the thread-local static.
514             // On first access to that allocation, it will be copied over to the machine memory.
515             if tcx.is_foreign_item(def_id) {
516                 throw_unsup_format!("foreign thread-local statics are not supported");
517             }
518             let allocation = interpret::get_static(*tcx, def_id)?;
519             // Create a new allocation id for the same allocation in this hacky
520             // way. Internally, `alloc_map` deduplicates allocations, but this
521             // is fine because Miri will make a copy before a first mutable
522             // access.
523             let new_alloc_id = tcx.create_memory_alloc(allocation);
524             this.machine.threads.set_thread_local_alloc_id(def_id, new_alloc_id);
525             Ok(new_alloc_id)
526         }
527     }
528
529     #[inline]
530     fn create_thread(&mut self) -> ThreadId {
531         let this = self.eval_context_mut();
532         this.machine.threads.create_thread()
533     }
534
535     #[inline]
536     fn detach_thread(&mut self, thread_id: ThreadId) -> InterpResult<'tcx> {
537         let this = self.eval_context_mut();
538         this.machine.threads.detach_thread(thread_id)
539     }
540
541     #[inline]
542     fn join_thread(&mut self, joined_thread_id: ThreadId) -> InterpResult<'tcx> {
543         let this = self.eval_context_mut();
544         this.machine.threads.join_thread(joined_thread_id)
545     }
546
547     #[inline]
548     fn set_active_thread(&mut self, thread_id: ThreadId) -> ThreadId {
549         let this = self.eval_context_mut();
550         this.machine.threads.set_active_thread_id(thread_id)
551     }
552
553     #[inline]
554     fn get_active_thread(&self) -> ThreadId {
555         let this = self.eval_context_ref();
556         this.machine.threads.get_active_thread_id()
557     }
558
559     #[inline]
560     fn get_total_thread_count(&self) -> usize {
561         let this = self.eval_context_ref();
562         this.machine.threads.get_total_thread_count()
563     }
564
565     #[inline]
566     fn has_terminated(&self, thread_id: ThreadId) -> bool {
567         let this = self.eval_context_ref();
568         this.machine.threads.has_terminated(thread_id)
569     }
570
571     #[inline]
572     fn enable_thread(&mut self, thread_id: ThreadId) {
573         let this = self.eval_context_mut();
574         this.machine.threads.enable_thread(thread_id);
575     }
576
577     #[inline]
578     fn active_thread_stack(&self) -> &[Frame<'mir, 'tcx, Tag, FrameData<'tcx>>] {
579         let this = self.eval_context_ref();
580         this.machine.threads.active_thread_stack()
581     }
582
583     #[inline]
584     fn active_thread_stack_mut(&mut self) -> &mut Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
585         let this = self.eval_context_mut();
586         this.machine.threads.active_thread_stack_mut()
587     }
588
589     #[inline]
590     fn set_active_thread_name(&mut self, new_thread_name: Vec<u8>) {
591         let this = self.eval_context_mut();
592         this.machine.threads.set_thread_name(new_thread_name);
593     }
594
595     #[inline]
596     fn get_active_thread_name<'c>(&'c self) -> &'c [u8]
597     where
598         'mir: 'c,
599     {
600         let this = self.eval_context_ref();
601         this.machine.threads.get_thread_name()
602     }
603
604     #[inline]
605     fn block_thread(&mut self, thread: ThreadId) {
606         let this = self.eval_context_mut();
607         this.machine.threads.block_thread(thread);
608     }
609
610     #[inline]
611     fn unblock_thread(&mut self, thread: ThreadId) {
612         let this = self.eval_context_mut();
613         this.machine.threads.unblock_thread(thread);
614     }
615
616     #[inline]
617     fn yield_active_thread(&mut self) {
618         let this = self.eval_context_mut();
619         this.machine.threads.yield_active_thread();
620     }
621
622     #[inline]
623     fn register_timeout_callback(
624         &mut self,
625         thread: ThreadId,
626         call_time: Time,
627         callback: TimeoutCallback<'mir, 'tcx>,
628     ) {
629         let this = self.eval_context_mut();
630         this.machine.threads.register_timeout_callback(thread, call_time, callback);
631     }
632
633     #[inline]
634     fn unregister_timeout_callback_if_exists(&mut self, thread: ThreadId) {
635         let this = self.eval_context_mut();
636         this.machine.threads.unregister_timeout_callback_if_exists(thread);
637     }
638
639     /// Execute a timeout callback on the callback's thread.
640     #[inline]
641     fn run_timeout_callback(&mut self) -> InterpResult<'tcx> {
642         let this = self.eval_context_mut();
643         let (thread, callback) =
644             this.machine.threads.get_ready_callback().expect("no callback found");
645         // This back-and-forth with `set_active_thread` is here because of two
646         // design decisions:
647         // 1. Make the caller and not the callback responsible for changing
648         //    thread.
649         // 2. Make the scheduler the only place that can change the active
650         //    thread.
651         let old_thread = this.set_active_thread(thread);
652         callback(this)?;
653         this.set_active_thread(old_thread);
654         Ok(())
655     }
656
657     /// Decide which action to take next and on which thread.
658     #[inline]
659     fn schedule(&mut self) -> InterpResult<'tcx, SchedulingAction> {
660         let this = self.eval_context_mut();
661         this.machine.threads.schedule()
662     }
663 }