1use std::sync::atomic::Ordering::Relaxed;
4use std::task::Poll;
5use std::time::{Duration, SystemTime};
6use std::{io, mem};
7
8use rand::seq::IteratorRandom;
9use rustc_abi::ExternAbi;
10use rustc_const_eval::CTRL_C_RECEIVED;
11use rustc_data_structures::either::Either;
12use rustc_data_structures::fx::FxHashMap;
13use rustc_hir::def_id::DefId;
14use rustc_index::{Idx, IndexVec};
15use rustc_middle::mir::Mutability;
16use rustc_middle::ty::layout::TyAndLayout;
17use rustc_span::{DUMMY_SP, Span};
18use rustc_target::spec::Os;
19
20use crate::concurrency::GlobalDataRaceHandler;
21use crate::concurrency::blocking_io::InterestReceiver;
22use crate::shims::tls;
23use crate::*;
24
25#[derive(Clone, Copy, Debug, PartialEq)]
26enum SchedulingAction {
27 ExecuteStep,
29 SleepAndWaitForIo(Option<Duration>),
34}
35
36#[derive(Clone, Copy, Debug, PartialEq)]
38pub enum TlsAllocAction {
39 Deallocate,
41 Leak,
44}
45
46#[derive(Clone, Copy, Debug, PartialEq)]
48pub enum UnblockKind {
49 Ready,
51 TimedOut,
53}
54
55pub type DynUnblockCallback<'tcx> = DynMachineCallback<'tcx, UnblockKind>;
58
59#[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
61pub struct ThreadId(u32);
62
63impl ThreadId {
64 pub fn to_u32(self) -> u32 {
65 self.0
66 }
67
68 pub fn new_unchecked(id: u32) -> Self {
70 Self(id)
71 }
72
73 pub const MAIN_THREAD: ThreadId = ThreadId(0);
74}
75
76impl Idx for ThreadId {
77 fn new(idx: usize) -> Self {
78 ThreadId(u32::try_from(idx).unwrap())
79 }
80
81 fn index(self) -> usize {
82 usize::try_from(self.0).unwrap()
83 }
84}
85
86impl From<ThreadId> for u64 {
87 fn from(t: ThreadId) -> Self {
88 t.0.into()
89 }
90}
91
92#[derive(Debug, Copy, Clone, PartialEq, Eq)]
94pub enum BlockReason {
95 Join(ThreadId),
98 Sleep,
100 Mutex,
102 Condvar,
104 RwLock,
106 Futex,
108 InitOnce,
110 Epoll,
112 Eventfd,
114 VirtualSocket,
116 IO,
118 Genmc,
121}
122
123enum ThreadState<'tcx> {
125 Enabled,
127 Blocked { reason: BlockReason, timeout: Option<Timeout>, callback: DynUnblockCallback<'tcx> },
129 Terminated,
132}
133
134impl<'tcx> std::fmt::Debug for ThreadState<'tcx> {
135 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136 match self {
137 Self::Enabled => write!(f, "Enabled"),
138 Self::Blocked { reason, timeout, .. } =>
139 f.debug_struct("Blocked").field("reason", reason).field("timeout", timeout).finish(),
140 Self::Terminated => write!(f, "Terminated"),
141 }
142 }
143}
144
145impl<'tcx> ThreadState<'tcx> {
146 fn is_enabled(&self) -> bool {
147 matches!(self, ThreadState::Enabled)
148 }
149
150 fn is_terminated(&self) -> bool {
151 matches!(self, ThreadState::Terminated)
152 }
153
154 fn is_blocked_on(&self, reason: BlockReason) -> bool {
155 matches!(*self, ThreadState::Blocked { reason: actual_reason, .. } if actual_reason == reason)
156 }
157}
158
159#[derive(Debug, Copy, Clone, PartialEq, Eq)]
161enum ThreadJoinStatus {
162 Joinable,
164 Detached,
167 Joined,
169}
170
171pub struct Thread<'tcx> {
173 state: ThreadState<'tcx>,
174
175 thread_name: Option<Vec<u8>>,
177
178 stack: Vec<Frame<'tcx, Provenance, FrameExtra<'tcx>>>,
180
181 pub(crate) origin_span: Span,
184
185 pub(crate) on_stack_empty: Option<StackEmptyCallback<'tcx>>,
190
191 top_user_relevant_frame: Option<usize>,
196
197 join_status: ThreadJoinStatus,
199
200 pub(crate) unwind_payloads: Vec<ImmTy<'tcx>>,
209
210 pub(crate) last_error: Option<MPlaceTy<'tcx>>,
212}
213
214pub type StackEmptyCallback<'tcx> =
215 Box<dyn FnMut(&mut MiriInterpCx<'tcx>) -> InterpResult<'tcx, Poll<()>> + 'tcx>;
216
217impl<'tcx> Thread<'tcx> {
218 fn thread_name(&self) -> Option<&[u8]> {
220 self.thread_name.as_deref()
221 }
222
223 pub fn is_enabled(&self) -> bool {
225 self.state.is_enabled()
226 }
227
228 fn thread_display_name(&self, id: ThreadId) -> String {
230 if let Some(ref thread_name) = self.thread_name {
231 String::from_utf8_lossy(thread_name).into_owned()
232 } else {
233 format!("unnamed-{}", id.index())
234 }
235 }
236
237 fn compute_top_user_relevant_frame(&self, skip: usize) -> Option<usize> {
243 let mut best = None;
245 for (idx, frame) in self.stack.iter().enumerate().rev().skip(skip) {
246 let relevance = frame.extra.user_relevance;
247 if relevance == u8::MAX {
248 return Some(idx);
250 }
251 if best.is_none_or(|(_best_idx, best_relevance)| best_relevance < relevance) {
252 best = Some((idx, relevance));
255 }
256 }
257 best.map(|(idx, _relevance)| idx)
258 }
259
260 pub fn recompute_top_user_relevant_frame(&mut self, skip: usize) {
263 self.top_user_relevant_frame = self.compute_top_user_relevant_frame(skip);
264 }
265
266 pub fn set_top_user_relevant_frame(&mut self, frame_idx: usize) {
269 debug_assert_eq!(Some(frame_idx), self.compute_top_user_relevant_frame(0));
270 self.top_user_relevant_frame = Some(frame_idx);
271 }
272
273 pub fn top_user_relevant_frame(&self) -> Option<usize> {
276 self.top_user_relevant_frame.or_else(|| self.stack.len().checked_sub(1))
280 }
281
282 pub fn current_user_relevance(&self) -> u8 {
283 self.top_user_relevant_frame()
284 .map(|frame_idx| self.stack[frame_idx].extra.user_relevance)
285 .unwrap_or(0)
286 }
287
288 pub fn current_user_relevant_span(&self) -> Span {
289 debug_assert_eq!(self.top_user_relevant_frame, self.compute_top_user_relevant_frame(0));
290 self.top_user_relevant_frame()
291 .map(|frame_idx| self.stack[frame_idx].current_span())
292 .unwrap_or(rustc_span::DUMMY_SP)
293 }
294}
295
296impl<'tcx> std::fmt::Debug for Thread<'tcx> {
297 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
298 write!(
299 f,
300 "{}({:?}, {:?})",
301 String::from_utf8_lossy(self.thread_name().unwrap_or(b"<unnamed>")),
302 self.state,
303 self.join_status
304 )
305 }
306}
307
308impl<'tcx> Thread<'tcx> {
309 fn new(name: Option<&str>, on_stack_empty: Option<StackEmptyCallback<'tcx>>) -> Self {
310 Self {
311 state: ThreadState::Enabled,
312 thread_name: name.map(|name| Vec::from(name.as_bytes())),
313 stack: Vec::new(),
314 origin_span: DUMMY_SP,
315 top_user_relevant_frame: None,
316 join_status: ThreadJoinStatus::Joinable,
317 unwind_payloads: Vec::new(),
318 last_error: None,
319 on_stack_empty,
320 }
321 }
322}
323
324impl VisitProvenance for Thread<'_> {
325 fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
326 let Thread {
327 unwind_payloads: panic_payload,
328 last_error,
329 stack,
330 origin_span: _,
331 top_user_relevant_frame: _,
332 state: _,
333 thread_name: _,
334 join_status: _,
335 on_stack_empty: _, } = self;
337
338 for payload in panic_payload {
339 payload.visit_provenance(visit);
340 }
341 last_error.visit_provenance(visit);
342 for frame in stack {
343 frame.visit_provenance(visit)
344 }
345 }
346}
347
348impl VisitProvenance for Frame<'_, Provenance, FrameExtra<'_>> {
349 fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
350 let return_place = self.return_place();
351 let Frame {
352 locals,
353 extra,
354 ..
356 } = self;
357
358 return_place.visit_provenance(visit);
360 for local in locals.iter() {
362 match local.as_mplace_or_imm() {
363 None => {}
364 Some(Either::Left((ptr, meta))) => {
365 ptr.visit_provenance(visit);
366 meta.visit_provenance(visit);
367 }
368 Some(Either::Right(imm)) => {
369 imm.visit_provenance(visit);
370 }
371 }
372 }
373
374 extra.visit_provenance(visit);
375 }
376}
377
378#[derive(Debug)]
380enum Timeout {
381 Monotonic(Instant),
382 RealTime(SystemTime),
383}
384
385impl Timeout {
386 fn get_wait_time(&self, clock: &MonotonicClock) -> Duration {
388 match self {
389 Timeout::Monotonic(instant) => instant.duration_since(clock.now()),
390 Timeout::RealTime(time) =>
391 time.duration_since(SystemTime::now()).unwrap_or(Duration::ZERO),
392 }
393 }
394
395 fn add_lossy(&self, duration: Duration) -> Self {
397 match self {
398 Timeout::Monotonic(i) => Timeout::Monotonic(i.add_lossy(duration)),
399 Timeout::RealTime(s) => {
400 Timeout::RealTime(
402 s.checked_add(duration)
403 .unwrap_or_else(|| s.checked_add(Duration::from_secs(3600)).unwrap()),
404 )
405 }
406 }
407 }
408}
409
410#[derive(Debug, Copy, Clone, PartialEq)]
412pub enum TimeoutClock {
413 Monotonic,
414 RealTime,
415}
416
417#[derive(Debug, Copy, Clone)]
419pub enum TimeoutAnchor {
420 Relative,
421 Absolute,
422}
423
424#[derive(Debug, Copy, Clone)]
426pub struct ThreadNotFound;
427
428#[derive(Debug)]
430pub struct ThreadManager<'tcx> {
431 active_thread: ThreadId,
433 threads: IndexVec<ThreadId, Thread<'tcx>>,
437 thread_local_allocs: FxHashMap<(DefId, ThreadId), StrictPointer>,
439 yield_active_thread: bool,
442 fixed_scheduling: bool,
444}
445
446impl VisitProvenance for ThreadManager<'_> {
447 fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
448 let ThreadManager {
449 threads,
450 thread_local_allocs,
451 active_thread: _,
452 yield_active_thread: _,
453 fixed_scheduling: _,
454 } = self;
455
456 for thread in threads {
457 thread.visit_provenance(visit);
458 }
459 for ptr in thread_local_allocs.values() {
460 ptr.visit_provenance(visit);
461 }
462 }
463}
464
465impl<'tcx> ThreadManager<'tcx> {
466 pub(crate) fn new(config: &MiriConfig) -> Self {
467 let mut threads = IndexVec::new();
468 threads.push(Thread::new(Some("main"), None));
470 Self {
471 active_thread: ThreadId::MAIN_THREAD,
472 threads,
473 thread_local_allocs: Default::default(),
474 yield_active_thread: false,
475 fixed_scheduling: config.fixed_scheduling,
476 }
477 }
478
479 pub(crate) fn init(
480 ecx: &mut MiriInterpCx<'tcx>,
481 on_main_stack_empty: StackEmptyCallback<'tcx>,
482 ) {
483 ecx.machine.threads.threads[ThreadId::MAIN_THREAD].on_stack_empty =
484 Some(on_main_stack_empty);
485 if ecx.tcx.sess.target.os != Os::Windows {
486 ecx.machine.threads.threads[ThreadId::MAIN_THREAD].join_status =
488 ThreadJoinStatus::Detached;
489 }
490 }
491
492 pub fn thread_id_try_from(&self, id: impl TryInto<u32>) -> Result<ThreadId, ThreadNotFound> {
493 if let Ok(id) = id.try_into()
494 && usize::try_from(id).is_ok_and(|id| id < self.threads.len())
495 {
496 Ok(ThreadId(id))
497 } else {
498 Err(ThreadNotFound)
499 }
500 }
501
502 fn get_thread_local_alloc_id(&self, def_id: DefId) -> Option<StrictPointer> {
505 self.thread_local_allocs.get(&(def_id, self.active_thread)).cloned()
506 }
507
508 fn set_thread_local_alloc(&mut self, def_id: DefId, ptr: StrictPointer) {
513 self.thread_local_allocs.try_insert((def_id, self.active_thread), ptr).unwrap();
514 }
515
516 pub fn active_thread_stack(&self) -> &[Frame<'tcx, Provenance, FrameExtra<'tcx>>] {
518 &self.threads[self.active_thread].stack
519 }
520
521 pub fn active_thread_stack_mut(
523 &mut self,
524 ) -> &mut Vec<Frame<'tcx, Provenance, FrameExtra<'tcx>>> {
525 &mut self.threads[self.active_thread].stack
526 }
527
528 pub fn all_blocked_stacks(
529 &self,
530 ) -> impl Iterator<Item = (ThreadId, &[Frame<'tcx, Provenance, FrameExtra<'tcx>>])> {
531 self.threads
532 .iter_enumerated()
533 .filter(|(_id, t)| matches!(t.state, ThreadState::Blocked { .. }))
534 .map(|(id, t)| (id, &t.stack[..]))
535 }
536
537 fn create_thread(&mut self, on_stack_empty: StackEmptyCallback<'tcx>) -> ThreadId {
539 let new_thread_id = ThreadId::new(self.threads.len());
540 self.threads.push(Thread::new(None, Some(on_stack_empty)));
541 new_thread_id
542 }
543
544 fn set_active_thread_id(&mut self, id: ThreadId) -> ThreadId {
546 assert!(id.index() < self.threads.len());
547 info!(
548 "---------- Now executing on thread `{}` (previous: `{}`) ----------------------------------------",
549 self.get_thread_display_name(id),
550 self.get_thread_display_name(self.active_thread)
551 );
552 std::mem::replace(&mut self.active_thread, id)
553 }
554
555 pub fn active_thread(&self) -> ThreadId {
557 self.active_thread
558 }
559
560 pub fn get_total_thread_count(&self) -> usize {
562 self.threads.len()
563 }
564
565 pub fn get_live_thread_count(&self) -> usize {
568 self.threads.iter().filter(|t| !t.state.is_terminated()).count()
569 }
570
571 fn has_terminated(&self, thread_id: ThreadId) -> bool {
573 self.threads[thread_id].state.is_terminated()
574 }
575
576 fn have_all_terminated(&self) -> bool {
578 self.threads.iter().all(|thread| thread.state.is_terminated())
579 }
580
581 fn enable_thread(&mut self, thread_id: ThreadId) {
583 assert!(self.has_terminated(thread_id));
584 self.threads[thread_id].state = ThreadState::Enabled;
585 }
586
587 pub fn active_thread_mut(&mut self) -> &mut Thread<'tcx> {
589 &mut self.threads[self.active_thread]
590 }
591
592 pub fn active_thread_ref(&self) -> &Thread<'tcx> {
594 &self.threads[self.active_thread]
595 }
596
597 pub fn thread_ref(&self, thread_id: ThreadId) -> &Thread<'tcx> {
598 &self.threads[thread_id]
599 }
600
601 fn detach_thread(&mut self, id: ThreadId, allow_terminated_joined: bool) -> InterpResult<'tcx> {
610 trace!("detaching {:?}", id);
612
613 let is_ub = if allow_terminated_joined && self.threads[id].state.is_terminated() {
614 self.threads[id].join_status == ThreadJoinStatus::Detached
616 } else {
617 self.threads[id].join_status != ThreadJoinStatus::Joinable
618 };
619 if is_ub {
620 throw_ub_format!("trying to detach thread that was already detached or joined");
621 }
622
623 self.threads[id].join_status = ThreadJoinStatus::Detached;
624 interp_ok(())
625 }
626
627 pub fn set_thread_name(&mut self, thread: ThreadId, new_thread_name: Vec<u8>) {
629 self.threads[thread].thread_name = Some(new_thread_name);
630 }
631
632 pub fn get_thread_name(&self, thread: ThreadId) -> Option<&[u8]> {
634 self.threads[thread].thread_name()
635 }
636
637 pub fn get_thread_display_name(&self, thread: ThreadId) -> String {
638 self.threads[thread].thread_display_name(thread)
639 }
640
641 fn block_thread(
643 &mut self,
644 reason: BlockReason,
645 timeout: Option<Timeout>,
646 callback: DynUnblockCallback<'tcx>,
647 ) {
648 let state = &mut self.threads[self.active_thread].state;
649 assert!(state.is_enabled());
650 *state = ThreadState::Blocked { reason, timeout, callback }
651 }
652
653 fn yield_active_thread(&mut self) {
655 self.yield_active_thread = true;
659 }
660}
661
662impl<'tcx> EvalContextPrivExt<'tcx> for MiriInterpCx<'tcx> {}
663trait EvalContextPrivExt<'tcx>: MiriInterpCxExt<'tcx> {
664 #[inline]
665 fn run_on_stack_empty(&mut self) -> InterpResult<'tcx, Poll<()>> {
666 let this = self.eval_context_mut();
667 let active_thread = this.active_thread_mut();
668 active_thread.origin_span = DUMMY_SP; let mut callback = active_thread
670 .on_stack_empty
671 .take()
672 .expect("`on_stack_empty` not set up, or already running");
673 let res = callback(this)?;
674 this.active_thread_mut().on_stack_empty = Some(callback);
675 interp_ok(res)
676 }
677
678 fn schedule(&mut self) -> InterpResult<'tcx, SchedulingAction> {
687 let this = self.eval_context_mut();
688
689 if this.machine.data_race.as_genmc_ref().is_some() {
691 loop {
692 let genmc_ctx = this.machine.data_race.as_genmc_ref().unwrap();
693 let Some(next_thread_id) = genmc_ctx.schedule_thread(this)? else {
694 return interp_ok(SchedulingAction::ExecuteStep);
695 };
696 if this.machine.threads.threads[next_thread_id]
698 .state
699 .is_blocked_on(BlockReason::Genmc)
700 {
701 info!(
702 "GenMC: scheduling blocked thread {next_thread_id:?}, so we unblock it now."
703 );
704 this.unblock_thread(next_thread_id, BlockReason::Genmc)?;
705 }
706 let thread_manager = &mut this.machine.threads;
709 if thread_manager.threads[next_thread_id].state.is_enabled() {
710 thread_manager.active_thread = next_thread_id;
712 return interp_ok(SchedulingAction::ExecuteStep);
713 }
714 }
715 }
716
717 let thread_manager = &this.machine.threads;
719 if thread_manager.threads[thread_manager.active_thread].state.is_enabled()
721 && !thread_manager.yield_active_thread
722 {
723 return interp_ok(SchedulingAction::ExecuteStep);
725 }
726
727 if this.machine.communicate() {
731 this.poll_and_unblock(Some(Duration::ZERO))?;
738 }
739
740 let potential_sleep_time = this.unblock_expired_timeouts()?;
746
747 let thread_manager = &mut this.machine.threads;
748 let rng = this.machine.rng.get_mut();
749
750 let mut threads_iter = thread_manager
757 .threads
758 .iter_enumerated()
759 .skip(thread_manager.active_thread.index() + 1)
760 .chain(
761 thread_manager
762 .threads
763 .iter_enumerated()
764 .take(thread_manager.active_thread.index() + 1),
765 )
766 .filter(|(_id, thread)| thread.state.is_enabled());
767 let new_thread = if thread_manager.fixed_scheduling {
769 threads_iter.next()
770 } else {
771 threads_iter.choose(rng)
772 };
773
774 if let Some((id, _thread)) = new_thread {
775 if thread_manager.active_thread != id {
776 info!(
777 "---------- Now executing on thread `{}` (previous: `{}`) ----------------------------------------",
778 thread_manager.get_thread_display_name(id),
779 thread_manager.get_thread_display_name(thread_manager.active_thread)
780 );
781 thread_manager.active_thread = id;
782 }
783 }
784 thread_manager.yield_active_thread = false;
786
787 if thread_manager.threads[thread_manager.active_thread].state.is_enabled() {
788 return interp_ok(SchedulingAction::ExecuteStep);
789 }
790 if thread_manager.threads.iter().all(|thread| thread.state.is_terminated()) {
792 unreachable!("all threads terminated without the main thread terminating?!");
793 } else if let Some(sleep_time) = potential_sleep_time {
794 interp_ok(SchedulingAction::SleepAndWaitForIo(Some(sleep_time)))
798 } else if thread_manager
799 .threads
800 .iter()
801 .any(|thread| thread.state.is_blocked_on(BlockReason::IO))
802 {
803 interp_ok(SchedulingAction::SleepAndWaitForIo(None))
807 } else {
808 throw_machine_stop!(TerminationInfo::GlobalDeadlock);
809 }
810 }
811
812 fn poll_and_unblock(&mut self, timeout: Option<Duration>) -> InterpResult<'tcx> {
815 let this = self.eval_context_mut();
816
817 let ready = match this.machine.blocking_io.poll(timeout) {
818 Ok(ready) => ready,
819 Err(e) if e.kind() == io::ErrorKind::Interrupted => return interp_ok(()),
821 Err(e) => panic!("unexpected error while polling: {e}"),
824 };
825
826 ready.into_iter().try_for_each(|(receiver, _source)| {
827 match receiver {
828 InterestReceiver::UnblockThread(thread_id) =>
829 this.unblock_thread(thread_id, BlockReason::IO),
830 }
831 })
832 }
833
834 fn unblock_expired_timeouts(&mut self) -> InterpResult<'tcx, Option<Duration>> {
839 let this = self.eval_context_mut();
840 let clock = &this.machine.monotonic_clock;
841
842 let mut min_wait_time = Option::<Duration>::None;
843 let mut callbacks = Vec::new();
844
845 for (id, thread) in this.machine.threads.threads.iter_enumerated_mut() {
846 match &thread.state {
847 ThreadState::Blocked { timeout: Some(timeout), .. } => {
848 let wait_time = timeout.get_wait_time(clock);
849 if wait_time.is_zero() {
850 let old_state = mem::replace(&mut thread.state, ThreadState::Enabled);
852 let ThreadState::Blocked { callback, .. } = old_state else {
853 unreachable!()
854 };
855 callbacks.push((id, callback));
857 } else {
858 min_wait_time = Some(wait_time.min(min_wait_time.unwrap_or(Duration::MAX)));
861 }
862 }
863 _ => {}
864 }
865 }
866
867 for (thread, callback) in callbacks {
868 let old_thread = this.machine.threads.set_active_thread_id(thread);
875 callback.call(this, UnblockKind::TimedOut)?;
876 this.machine.threads.set_active_thread_id(old_thread);
877 }
878
879 interp_ok(min_wait_time)
880 }
881}
882
883impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
885pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
886 #[inline]
887 fn thread_id_try_from(&self, id: impl TryInto<u32>) -> Result<ThreadId, ThreadNotFound> {
888 self.eval_context_ref().machine.threads.thread_id_try_from(id)
889 }
890
891 fn get_or_create_thread_local_alloc(
894 &mut self,
895 def_id: DefId,
896 ) -> InterpResult<'tcx, StrictPointer> {
897 let this = self.eval_context_mut();
898 let tcx = this.tcx;
899 if let Some(old_alloc) = this.machine.threads.get_thread_local_alloc_id(def_id) {
900 interp_ok(old_alloc)
903 } else {
904 if tcx.is_foreign_item(def_id) {
908 throw_unsup_format!("foreign thread-local statics are not supported");
909 }
910 let params = this.machine.get_default_alloc_params();
911 let alloc = this.ctfe_query(|tcx| tcx.eval_static_initializer(def_id))?;
912 let mut alloc = alloc.inner().adjust_from_tcx(
914 &this.tcx,
915 |bytes, align| {
916 interp_ok(MiriAllocBytes::from_bytes(
917 std::borrow::Cow::Borrowed(bytes),
918 align,
919 params,
920 ))
921 },
922 |ptr| this.global_root_pointer(ptr),
923 )?;
924 alloc.mutability = Mutability::Mut;
926 let ptr = this.insert_allocation(alloc, MiriMemoryKind::Tls.into())?;
928 this.machine.threads.set_thread_local_alloc(def_id, ptr);
929 interp_ok(ptr)
930 }
931 }
932
933 #[inline]
935 fn start_regular_thread(
936 &mut self,
937 thread: Option<MPlaceTy<'tcx>>,
938 start_routine: Pointer,
939 start_abi: ExternAbi,
940 func_arg: ImmTy<'tcx>,
941 ret_layout: TyAndLayout<'tcx>,
942 ) -> InterpResult<'tcx, ThreadId> {
943 let this = self.eval_context_mut();
944
945 let current_span = this.machine.current_user_relevant_span();
947 let new_thread_id = this.machine.threads.create_thread({
948 let mut state = tls::TlsDtorsState::default();
949 Box::new(move |m| state.on_stack_empty(m))
950 });
951 match &mut this.machine.data_race {
952 GlobalDataRaceHandler::None => {}
953 GlobalDataRaceHandler::Vclocks(data_race) =>
954 data_race.thread_created(&this.machine.threads, new_thread_id, current_span),
955 GlobalDataRaceHandler::Genmc(genmc_ctx) =>
956 genmc_ctx.handle_thread_create(
957 &this.machine.threads,
958 start_routine,
959 &func_arg,
960 new_thread_id,
961 )?,
962 }
963 if let Some(thread_info_place) = thread {
966 this.write_scalar(
967 Scalar::from_uint(new_thread_id.to_u32(), thread_info_place.layout.size),
968 &thread_info_place,
969 )?;
970 }
971
972 let old_thread_id = this.machine.threads.set_active_thread_id(new_thread_id);
975
976 if let Some(cpuset) = this.machine.thread_cpu_affinity.get(&old_thread_id).cloned() {
978 this.machine.thread_cpu_affinity.insert(new_thread_id, cpuset);
979 }
980
981 let instance = this.get_ptr_fn(start_routine)?.as_instance()?;
983
984 let ret_place = this.allocate(ret_layout, MiriMemoryKind::Machine.into())?;
988
989 this.call_thread_root_function(
990 instance,
991 start_abi,
992 &[func_arg],
993 Some(&ret_place),
994 current_span,
995 )?;
996
997 this.machine.threads.set_active_thread_id(old_thread_id);
999
1000 interp_ok(new_thread_id)
1001 }
1002
1003 fn terminate_active_thread(&mut self, tls_alloc_action: TlsAllocAction) -> InterpResult<'tcx> {
1008 let this = self.eval_context_mut();
1009
1010 let thread = this.active_thread_mut();
1012 assert!(thread.stack.is_empty(), "only threads with an empty stack can be terminated");
1013 thread.state = ThreadState::Terminated;
1014
1015 let gone_thread = this.active_thread();
1017 {
1018 let mut free_tls_statics = Vec::new();
1019 this.machine.threads.thread_local_allocs.retain(|&(_def_id, thread), &mut alloc_id| {
1020 if thread != gone_thread {
1021 return true;
1023 }
1024 free_tls_statics.push(alloc_id);
1027 false
1028 });
1029 for ptr in free_tls_statics {
1031 match tls_alloc_action {
1032 TlsAllocAction::Deallocate =>
1033 this.deallocate_ptr(ptr.into(), None, MiriMemoryKind::Tls.into())?,
1034 TlsAllocAction::Leak =>
1035 if let Some(alloc) = ptr.provenance.get_alloc_id() {
1036 trace!(
1037 "Thread-local static leaked and stored as static root: {:?}",
1038 alloc
1039 );
1040 this.machine.static_roots.push(alloc);
1041 },
1042 }
1043 }
1044 }
1045
1046 match &mut this.machine.data_race {
1047 GlobalDataRaceHandler::None => {}
1048 GlobalDataRaceHandler::Vclocks(data_race) =>
1049 data_race.thread_terminated(&this.machine.threads),
1050 GlobalDataRaceHandler::Genmc(genmc_ctx) => {
1051 genmc_ctx.handle_thread_finish(&this.machine.threads)
1054 }
1055 }
1056
1057 let unblock_reason = BlockReason::Join(gone_thread);
1059 let threads = &this.machine.threads.threads;
1060 let joining_threads = threads
1061 .iter_enumerated()
1062 .filter(|(_, thread)| thread.state.is_blocked_on(unblock_reason))
1063 .map(|(id, _)| id)
1064 .collect::<Vec<_>>();
1065 for thread in joining_threads {
1066 this.unblock_thread(thread, unblock_reason)?;
1067 }
1068
1069 interp_ok(())
1070 }
1071
1072 #[inline]
1075 fn block_thread(
1076 &mut self,
1077 reason: BlockReason,
1078 timeout: Option<(TimeoutClock, TimeoutAnchor, Duration)>,
1079 callback: DynUnblockCallback<'tcx>,
1080 ) {
1081 let this = self.eval_context_mut();
1082 if timeout.is_some() && this.machine.data_race.as_genmc_ref().is_some() {
1083 panic!("Unimplemented: Timeouts not yet supported in GenMC mode.");
1084 }
1085 let timeout = timeout.map(|(clock, anchor, duration)| {
1086 let anchor = match clock {
1087 TimeoutClock::RealTime => {
1088 assert!(
1089 this.machine.communicate(),
1090 "cannot have `RealTime` timeout with isolation enabled!"
1091 );
1092 Timeout::RealTime(match anchor {
1093 TimeoutAnchor::Absolute => SystemTime::UNIX_EPOCH,
1094 TimeoutAnchor::Relative => SystemTime::now(),
1095 })
1096 }
1097 TimeoutClock::Monotonic =>
1098 Timeout::Monotonic(match anchor {
1099 TimeoutAnchor::Absolute => this.machine.monotonic_clock.epoch(),
1100 TimeoutAnchor::Relative => this.machine.monotonic_clock.now(),
1101 }),
1102 };
1103 anchor.add_lossy(duration)
1104 });
1105 this.machine.threads.block_thread(reason, timeout, callback);
1106 }
1107
1108 fn unblock_thread(&mut self, thread: ThreadId, reason: BlockReason) -> InterpResult<'tcx> {
1111 let this = self.eval_context_mut();
1112 let old_state =
1113 mem::replace(&mut this.machine.threads.threads[thread].state, ThreadState::Enabled);
1114 let callback = match old_state {
1115 ThreadState::Blocked { reason: actual_reason, callback, .. } => {
1116 assert_eq!(
1117 reason, actual_reason,
1118 "unblock_thread: thread was blocked for the wrong reason"
1119 );
1120 callback
1121 }
1122 _ => panic!("unblock_thread: thread was not blocked"),
1123 };
1124 let old_thread = this.machine.threads.set_active_thread_id(thread);
1126 callback.call(this, UnblockKind::Ready)?;
1127 this.machine.threads.set_active_thread_id(old_thread);
1128 interp_ok(())
1129 }
1130
1131 #[inline]
1132 fn detach_thread(
1133 &mut self,
1134 thread_id: ThreadId,
1135 allow_terminated_joined: bool,
1136 ) -> InterpResult<'tcx> {
1137 let this = self.eval_context_mut();
1138 this.machine.threads.detach_thread(thread_id, allow_terminated_joined)
1139 }
1140
1141 fn join_thread(
1145 &mut self,
1146 joined_thread_id: ThreadId,
1147 success_retval: Scalar,
1148 return_dest: &MPlaceTy<'tcx>,
1149 ) -> InterpResult<'tcx> {
1150 let this = self.eval_context_mut();
1151 let thread_mgr = &mut this.machine.threads;
1152 if thread_mgr.threads[joined_thread_id].join_status == ThreadJoinStatus::Detached {
1153 throw_ub_format!("trying to join a detached thread");
1155 }
1156
1157 fn after_join<'tcx>(
1158 this: &mut InterpCx<'tcx, MiriMachine<'tcx>>,
1159 joined_thread_id: ThreadId,
1160 success_retval: Scalar,
1161 return_dest: &MPlaceTy<'tcx>,
1162 ) -> InterpResult<'tcx> {
1163 let threads = &this.machine.threads;
1164 match &mut this.machine.data_race {
1165 GlobalDataRaceHandler::None => {}
1166 GlobalDataRaceHandler::Vclocks(data_race) =>
1167 data_race.thread_joined(threads, joined_thread_id),
1168 GlobalDataRaceHandler::Genmc(genmc_ctx) =>
1169 genmc_ctx.handle_thread_join(threads.active_thread, joined_thread_id)?,
1170 }
1171 this.write_scalar(success_retval, return_dest)?;
1172 interp_ok(())
1173 }
1174
1175 thread_mgr.threads[joined_thread_id].join_status = ThreadJoinStatus::Joined;
1178 if !thread_mgr.threads[joined_thread_id].state.is_terminated() {
1179 trace!(
1180 "{:?} blocked on {:?} when trying to join",
1181 thread_mgr.active_thread, joined_thread_id
1182 );
1183 if let Some(genmc_ctx) = this.machine.data_race.as_genmc_ref() {
1184 genmc_ctx.handle_thread_join(thread_mgr.active_thread, joined_thread_id)?;
1185 }
1186
1187 let dest = return_dest.clone();
1190 thread_mgr.block_thread(
1191 BlockReason::Join(joined_thread_id),
1192 None,
1193 callback!(
1194 @capture<'tcx> {
1195 joined_thread_id: ThreadId,
1196 dest: MPlaceTy<'tcx>,
1197 success_retval: Scalar,
1198 }
1199 |this, unblock: UnblockKind| {
1200 assert_eq!(unblock, UnblockKind::Ready);
1201 after_join(this, joined_thread_id, success_retval, &dest)
1202 }
1203 ),
1204 );
1205 } else {
1206 after_join(this, joined_thread_id, success_retval, return_dest)?;
1208 }
1209 interp_ok(())
1210 }
1211
1212 fn join_thread_exclusive(
1217 &mut self,
1218 joined_thread_id: ThreadId,
1219 success_retval: Scalar,
1220 return_dest: &MPlaceTy<'tcx>,
1221 ) -> InterpResult<'tcx> {
1222 let this = self.eval_context_mut();
1223 let threads = &this.machine.threads.threads;
1224 if threads[joined_thread_id].join_status == ThreadJoinStatus::Joined {
1225 throw_ub_format!("trying to join an already joined thread");
1226 }
1227
1228 if joined_thread_id == this.machine.threads.active_thread {
1229 throw_ub_format!("trying to join itself");
1230 }
1231
1232 assert!(
1234 threads
1235 .iter()
1236 .all(|thread| { !thread.state.is_blocked_on(BlockReason::Join(joined_thread_id)) }),
1237 "this thread already has threads waiting for its termination"
1238 );
1239
1240 this.join_thread(joined_thread_id, success_retval, return_dest)
1241 }
1242
1243 #[inline]
1244 fn active_thread(&self) -> ThreadId {
1245 let this = self.eval_context_ref();
1246 this.machine.threads.active_thread()
1247 }
1248
1249 #[inline]
1250 fn active_thread_mut(&mut self) -> &mut Thread<'tcx> {
1251 let this = self.eval_context_mut();
1252 this.machine.threads.active_thread_mut()
1253 }
1254
1255 #[inline]
1256 fn active_thread_ref(&self) -> &Thread<'tcx> {
1257 let this = self.eval_context_ref();
1258 this.machine.threads.active_thread_ref()
1259 }
1260
1261 #[inline]
1262 fn get_total_thread_count(&self) -> usize {
1263 let this = self.eval_context_ref();
1264 this.machine.threads.get_total_thread_count()
1265 }
1266
1267 #[inline]
1268 fn have_all_terminated(&self) -> bool {
1269 let this = self.eval_context_ref();
1270 this.machine.threads.have_all_terminated()
1271 }
1272
1273 #[inline]
1274 fn enable_thread(&mut self, thread_id: ThreadId) {
1275 let this = self.eval_context_mut();
1276 this.machine.threads.enable_thread(thread_id);
1277 }
1278
1279 #[inline]
1280 fn active_thread_stack<'a>(&'a self) -> &'a [Frame<'tcx, Provenance, FrameExtra<'tcx>>] {
1281 let this = self.eval_context_ref();
1282 this.machine.threads.active_thread_stack()
1283 }
1284
1285 #[inline]
1286 fn active_thread_stack_mut<'a>(
1287 &'a mut self,
1288 ) -> &'a mut Vec<Frame<'tcx, Provenance, FrameExtra<'tcx>>> {
1289 let this = self.eval_context_mut();
1290 this.machine.threads.active_thread_stack_mut()
1291 }
1292
1293 #[inline]
1295 fn set_thread_name(&mut self, thread: ThreadId, new_thread_name: Vec<u8>) {
1296 self.eval_context_mut().machine.threads.set_thread_name(thread, new_thread_name);
1297 }
1298
1299 #[inline]
1300 fn get_thread_name<'c>(&'c self, thread: ThreadId) -> Option<&'c [u8]>
1301 where
1302 'tcx: 'c,
1303 {
1304 self.eval_context_ref().machine.threads.get_thread_name(thread)
1305 }
1306
1307 #[inline]
1308 fn yield_active_thread(&mut self) {
1309 self.eval_context_mut().machine.threads.yield_active_thread();
1310 }
1311
1312 #[inline]
1313 fn maybe_preempt_active_thread(&mut self) {
1314 use rand::Rng as _;
1315
1316 let this = self.eval_context_mut();
1317 if !this.machine.threads.fixed_scheduling
1318 && this.machine.rng.get_mut().random_bool(this.machine.preemption_rate)
1319 {
1320 this.yield_active_thread();
1321 }
1322 }
1323
1324 fn run_threads(&mut self) -> InterpResult<'tcx, !> {
1327 let this = self.eval_context_mut();
1328 loop {
1329 if CTRL_C_RECEIVED.load(Relaxed) {
1330 this.machine.handle_abnormal_termination();
1331 throw_machine_stop!(TerminationInfo::Interrupted);
1332 }
1333 match this.schedule()? {
1334 SchedulingAction::ExecuteStep => {
1335 if !this.step()? {
1336 match this.run_on_stack_empty()? {
1338 Poll::Pending => {} Poll::Ready(()) =>
1340 this.terminate_active_thread(TlsAllocAction::Deallocate)?,
1341 }
1342 }
1343 }
1344 SchedulingAction::SleepAndWaitForIo(duration) => {
1345 if this.machine.communicate() {
1346 this.poll_and_unblock(duration)?;
1351 } else {
1352 let duration = duration.expect(
1353 "Infinite sleep should not be triggered when isolation is enabled",
1354 );
1355 this.machine.monotonic_clock.sleep(duration);
1356 }
1357 }
1358 }
1359 }
1360 }
1361}