1use std::cell::{Cell, Ref, RefCell, RefMut};
44use std::fmt::Debug;
45use std::mem;
46
47use rustc_abi::{Align, HasDataLayout, Size};
48use rustc_ast::Mutability;
49use rustc_data_structures::fx::{FxHashMap, FxHashSet};
50use rustc_index::{Idx, IndexVec};
51use rustc_middle::mir;
52use rustc_middle::ty::Ty;
53use rustc_span::Span;
54
55use super::vector_clock::{VClock, VTimestamp, VectorIdx};
56use super::weak_memory::EvalContextExt as _;
57use crate::concurrency::GlobalDataRaceHandler;
58use crate::diagnostics::RacingOp;
59use crate::*;
60
61pub type AllocState = VClockAlloc;
62
63#[derive(Copy, Clone, PartialEq, Eq, Debug)]
65pub enum AtomicRwOrd {
66 Relaxed,
67 Acquire,
68 Release,
69 AcqRel,
70 SeqCst,
71}
72
73#[derive(Copy, Clone, PartialEq, Eq, Debug)]
75pub enum AtomicReadOrd {
76 Relaxed,
77 Acquire,
78 SeqCst,
79}
80
81#[derive(Copy, Clone, PartialEq, Eq, Debug)]
83pub enum AtomicWriteOrd {
84 Relaxed,
85 Release,
86 SeqCst,
87}
88
89#[derive(Copy, Clone, PartialEq, Eq, Debug)]
91pub enum AtomicFenceOrd {
92 Acquire,
93 Release,
94 AcqRel,
95 SeqCst,
96}
97
98#[derive(Clone, Default, Debug)]
102pub(super) struct ThreadClockSet {
103 pub(super) clock: VClock,
106
107 fence_acquire: VClock,
110
111 fence_release: VClock,
114
115 pub(super) write_seqcst: VClock,
120
121 pub(super) read_seqcst: VClock,
126}
127
128impl ThreadClockSet {
129 #[inline]
132 fn apply_release_fence(&mut self) {
133 self.fence_release.clone_from(&self.clock);
134 }
135
136 #[inline]
139 fn apply_acquire_fence(&mut self) {
140 self.clock.join(&self.fence_acquire);
141 }
142
143 #[inline]
146 fn increment_clock(&mut self, index: VectorIdx, current_span: Span) {
147 self.clock.increment_index(index, current_span);
148 }
149
150 fn join_with(&mut self, other: &ThreadClockSet) {
154 self.clock.join(&other.clock);
155 }
156}
157
158#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
161pub struct DataRace;
162
163#[derive(Clone, PartialEq, Eq, Debug)]
168struct AtomicMemoryCellClocks {
169 read_vector: VClock,
174
175 write_vector: VClock,
180
181 sync_vector: VClock,
186
187 size: Option<Size>,
192}
193
194#[derive(Copy, Clone, PartialEq, Eq, Debug)]
195enum AtomicAccessType {
196 Load(AtomicReadOrd),
197 Store,
198 Rmw,
199}
200
201#[derive(Copy, Clone, PartialEq, Eq, Debug)]
203pub enum NaReadType {
204 Read,
206
207 Retag,
209}
210
211impl NaReadType {
212 fn description(self) -> &'static str {
213 match self {
214 NaReadType::Read => "non-atomic read",
215 NaReadType::Retag => "retag read",
216 }
217 }
218}
219
220#[derive(Copy, Clone, PartialEq, Eq, Debug)]
223pub enum NaWriteType {
224 Allocate,
226
227 Write,
229
230 Retag,
232
233 Deallocate,
238}
239
240impl NaWriteType {
241 fn description(self) -> &'static str {
242 match self {
243 NaWriteType::Allocate => "creating a new allocation",
244 NaWriteType::Write => "non-atomic write",
245 NaWriteType::Retag => "retag write",
246 NaWriteType::Deallocate => "deallocation",
247 }
248 }
249}
250
251#[derive(Copy, Clone, PartialEq, Eq, Debug)]
252enum AccessType {
253 NaRead(NaReadType),
254 NaWrite(NaWriteType),
255 AtomicLoad,
256 AtomicStore,
257 AtomicRmw,
258}
259
260#[derive(Clone, PartialEq, Eq, Debug)]
262struct MemoryCellClocks {
263 write: (VectorIdx, VTimestamp),
267
268 write_type: NaWriteType,
272
273 read: VClock,
277
278 atomic_ops: Option<Box<AtomicMemoryCellClocks>>,
282}
283
284#[derive(Debug, Clone, Default)]
286struct ThreadExtraState {
287 vector_index: Option<VectorIdx>,
293
294 termination_vector_clock: Option<VClock>,
299}
300
301#[derive(Debug, Clone)]
306pub struct GlobalState {
307 multi_threaded: Cell<bool>,
314
315 ongoing_action_data_race_free: Cell<bool>,
319
320 vector_clocks: RefCell<IndexVec<VectorIdx, ThreadClockSet>>,
324
325 vector_info: RefCell<IndexVec<VectorIdx, ThreadId>>,
329
330 thread_info: RefCell<IndexVec<ThreadId, ThreadExtraState>>,
332
333 reuse_candidates: RefCell<FxHashSet<VectorIdx>>,
341
342 last_sc_fence: RefCell<VClock>,
345
346 last_sc_write_per_thread: RefCell<VClock>,
349
350 pub track_outdated_loads: bool,
352
353 pub weak_memory: bool,
355}
356
357impl VisitProvenance for GlobalState {
358 fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
359 }
361}
362
363impl AccessType {
364 fn description(self, ty: Option<Ty<'_>>, size: Option<Size>) -> String {
365 let mut msg = String::new();
366
367 if let Some(size) = size {
368 if size == Size::ZERO {
369 assert!(self == AccessType::AtomicLoad);
373 assert!(ty.is_none());
374 return format!("multiple differently-sized atomic loads, including one load");
375 }
376 msg.push_str(&format!("{}-byte {}", size.bytes(), msg))
377 }
378
379 msg.push_str(match self {
380 AccessType::NaRead(w) => w.description(),
381 AccessType::NaWrite(w) => w.description(),
382 AccessType::AtomicLoad => "atomic load",
383 AccessType::AtomicStore => "atomic store",
384 AccessType::AtomicRmw => "atomic read-modify-write",
385 });
386
387 if let Some(ty) = ty {
388 msg.push_str(&format!(" of type `{ty}`"));
389 }
390
391 msg
392 }
393
394 fn is_atomic(self) -> bool {
395 match self {
396 AccessType::AtomicLoad | AccessType::AtomicStore | AccessType::AtomicRmw => true,
397 AccessType::NaRead(_) | AccessType::NaWrite(_) => false,
398 }
399 }
400
401 fn is_read(self) -> bool {
402 match self {
403 AccessType::AtomicLoad | AccessType::NaRead(_) => true,
404 AccessType::NaWrite(_) | AccessType::AtomicStore | AccessType::AtomicRmw => false,
405 }
406 }
407
408 fn is_retag(self) -> bool {
409 matches!(
410 self,
411 AccessType::NaRead(NaReadType::Retag) | AccessType::NaWrite(NaWriteType::Retag)
412 )
413 }
414}
415
416impl AtomicMemoryCellClocks {
417 fn new(size: Size) -> Self {
418 AtomicMemoryCellClocks {
419 read_vector: Default::default(),
420 write_vector: Default::default(),
421 sync_vector: Default::default(),
422 size: Some(size),
423 }
424 }
425}
426
427impl MemoryCellClocks {
428 fn new(alloc: VTimestamp, alloc_index: VectorIdx) -> Self {
431 MemoryCellClocks {
432 read: VClock::default(),
433 write: (alloc_index, alloc),
434 write_type: NaWriteType::Allocate,
435 atomic_ops: None,
436 }
437 }
438
439 #[inline]
440 fn write_was_before(&self, other: &VClock) -> bool {
441 self.write.1 <= other[self.write.0]
444 }
445
446 #[inline]
447 fn write(&self) -> VClock {
448 VClock::new_with_index(self.write.0, self.write.1)
449 }
450
451 #[inline]
453 fn atomic(&self) -> Option<&AtomicMemoryCellClocks> {
454 self.atomic_ops.as_deref()
455 }
456
457 #[inline]
459 fn atomic_mut_unwrap(&mut self) -> &mut AtomicMemoryCellClocks {
460 self.atomic_ops.as_deref_mut().unwrap()
461 }
462
463 fn atomic_access(
466 &mut self,
467 thread_clocks: &ThreadClockSet,
468 size: Size,
469 write: bool,
470 ) -> Result<&mut AtomicMemoryCellClocks, DataRace> {
471 match self.atomic_ops {
472 Some(ref mut atomic) => {
473 if atomic.size == Some(size) {
475 Ok(atomic)
476 } else if atomic.read_vector <= thread_clocks.clock
477 && atomic.write_vector <= thread_clocks.clock
478 {
479 atomic.size = Some(size);
481 Ok(atomic)
482 } else if !write && atomic.write_vector <= thread_clocks.clock {
483 atomic.size = None;
486 Ok(atomic)
487 } else {
488 Err(DataRace)
489 }
490 }
491 None => {
492 self.atomic_ops = Some(Box::new(AtomicMemoryCellClocks::new(size)));
493 Ok(self.atomic_ops.as_mut().unwrap())
494 }
495 }
496 }
497
498 fn load_acquire(
502 &mut self,
503 thread_clocks: &mut ThreadClockSet,
504 index: VectorIdx,
505 access_size: Size,
506 ) -> Result<(), DataRace> {
507 self.atomic_read_detect(thread_clocks, index, access_size)?;
508 if let Some(atomic) = self.atomic() {
509 thread_clocks.clock.join(&atomic.sync_vector);
510 }
511 Ok(())
512 }
513
514 fn load_relaxed(
518 &mut self,
519 thread_clocks: &mut ThreadClockSet,
520 index: VectorIdx,
521 access_size: Size,
522 ) -> Result<(), DataRace> {
523 self.atomic_read_detect(thread_clocks, index, access_size)?;
524 if let Some(atomic) = self.atomic() {
525 thread_clocks.fence_acquire.join(&atomic.sync_vector);
526 }
527 Ok(())
528 }
529
530 fn store_release(
533 &mut self,
534 thread_clocks: &ThreadClockSet,
535 index: VectorIdx,
536 access_size: Size,
537 ) -> Result<(), DataRace> {
538 self.atomic_write_detect(thread_clocks, index, access_size)?;
539 let atomic = self.atomic_mut_unwrap(); atomic.sync_vector.clone_from(&thread_clocks.clock);
541 Ok(())
542 }
543
544 fn store_relaxed(
547 &mut self,
548 thread_clocks: &ThreadClockSet,
549 index: VectorIdx,
550 access_size: Size,
551 ) -> Result<(), DataRace> {
552 self.atomic_write_detect(thread_clocks, index, access_size)?;
553
554 let atomic = self.atomic_mut_unwrap();
559 atomic.sync_vector.clone_from(&thread_clocks.fence_release);
560 Ok(())
561 }
562
563 fn rmw_release(
566 &mut self,
567 thread_clocks: &ThreadClockSet,
568 index: VectorIdx,
569 access_size: Size,
570 ) -> Result<(), DataRace> {
571 self.atomic_write_detect(thread_clocks, index, access_size)?;
572 let atomic = self.atomic_mut_unwrap();
573 atomic.sync_vector.join(&thread_clocks.clock);
574 Ok(())
575 }
576
577 fn rmw_relaxed(
580 &mut self,
581 thread_clocks: &ThreadClockSet,
582 index: VectorIdx,
583 access_size: Size,
584 ) -> Result<(), DataRace> {
585 self.atomic_write_detect(thread_clocks, index, access_size)?;
586 let atomic = self.atomic_mut_unwrap();
587 atomic.sync_vector.join(&thread_clocks.fence_release);
588 Ok(())
589 }
590
591 fn atomic_read_detect(
594 &mut self,
595 thread_clocks: &ThreadClockSet,
596 index: VectorIdx,
597 access_size: Size,
598 ) -> Result<(), DataRace> {
599 trace!("Atomic read with vectors: {:#?} :: {:#?}", self, thread_clocks);
600 let atomic = self.atomic_access(thread_clocks, access_size, false)?;
601 atomic.read_vector.set_at_index(&thread_clocks.clock, index);
602 if self.write_was_before(&thread_clocks.clock) { Ok(()) } else { Err(DataRace) }
604 }
605
606 fn atomic_write_detect(
609 &mut self,
610 thread_clocks: &ThreadClockSet,
611 index: VectorIdx,
612 access_size: Size,
613 ) -> Result<(), DataRace> {
614 trace!("Atomic write with vectors: {:#?} :: {:#?}", self, thread_clocks);
615 let atomic = self.atomic_access(thread_clocks, access_size, true)?;
616 atomic.write_vector.set_at_index(&thread_clocks.clock, index);
617 if self.write_was_before(&thread_clocks.clock) && self.read <= thread_clocks.clock {
619 Ok(())
620 } else {
621 Err(DataRace)
622 }
623 }
624
625 fn read_race_detect(
628 &mut self,
629 thread_clocks: &mut ThreadClockSet,
630 index: VectorIdx,
631 read_type: NaReadType,
632 current_span: Span,
633 ) -> Result<(), DataRace> {
634 trace!("Unsynchronized read with vectors: {:#?} :: {:#?}", self, thread_clocks);
635 if !current_span.is_dummy() {
636 thread_clocks.clock.index_mut(index).span = current_span;
637 }
638 thread_clocks.clock.index_mut(index).set_read_type(read_type);
639 if self.write_was_before(&thread_clocks.clock) {
640 let race_free = if let Some(atomic) = self.atomic() {
642 atomic.write_vector <= thread_clocks.clock
643 } else {
644 true
645 };
646 self.read.set_at_index(&thread_clocks.clock, index);
647 if race_free { Ok(()) } else { Err(DataRace) }
648 } else {
649 Err(DataRace)
650 }
651 }
652
653 fn write_race_detect(
656 &mut self,
657 thread_clocks: &mut ThreadClockSet,
658 index: VectorIdx,
659 write_type: NaWriteType,
660 current_span: Span,
661 ) -> Result<(), DataRace> {
662 trace!("Unsynchronized write with vectors: {:#?} :: {:#?}", self, thread_clocks);
663 if !current_span.is_dummy() {
664 thread_clocks.clock.index_mut(index).span = current_span;
665 }
666 if self.write_was_before(&thread_clocks.clock) && self.read <= thread_clocks.clock {
667 let race_free = if let Some(atomic) = self.atomic() {
668 atomic.write_vector <= thread_clocks.clock
669 && atomic.read_vector <= thread_clocks.clock
670 } else {
671 true
672 };
673 self.write = (index, thread_clocks.clock[index]);
674 self.write_type = write_type;
675 if race_free {
676 self.read.set_zero_vector();
677 Ok(())
678 } else {
679 Err(DataRace)
680 }
681 } else {
682 Err(DataRace)
683 }
684 }
685}
686
687impl GlobalDataRaceHandler {
688 fn set_ongoing_action_data_race_free(&self, enable: bool) {
691 match self {
692 GlobalDataRaceHandler::None => {}
693 GlobalDataRaceHandler::Vclocks(data_race) => {
694 let old = data_race.ongoing_action_data_race_free.replace(enable);
695 assert_ne!(old, enable, "cannot nest allow_data_races");
696 }
697 GlobalDataRaceHandler::Genmc(genmc_ctx) => {
698 genmc_ctx.set_ongoing_action_data_race_free(enable);
699 }
700 }
701 }
702}
703
704impl<'tcx> EvalContextExt<'tcx> for MiriInterpCx<'tcx> {}
706pub trait EvalContextExt<'tcx>: MiriInterpCxExt<'tcx> {
707 fn read_scalar_atomic(
709 &self,
710 place: &MPlaceTy<'tcx>,
711 atomic: AtomicReadOrd,
712 ) -> InterpResult<'tcx, Scalar> {
713 let this = self.eval_context_ref();
714 this.atomic_access_check(place, AtomicAccessType::Load(atomic))?;
715 if let Some(genmc_ctx) = this.machine.data_race.as_genmc_ref() {
722 let old_val = None;
724 return genmc_ctx.atomic_load(
725 this,
726 place.ptr().addr(),
727 place.layout.size,
728 atomic,
729 old_val,
730 );
731 }
732
733 let scalar = this.allow_data_races_ref(move |this| this.read_scalar(place))?;
734 let buffered_scalar = this.buffered_atomic_read(place, atomic, scalar, || {
735 this.validate_atomic_load(place, atomic)
736 })?;
737 interp_ok(buffered_scalar.ok_or_else(|| err_ub!(InvalidUninitBytes(None)))?)
738 }
739
740 fn write_scalar_atomic(
742 &mut self,
743 val: Scalar,
744 dest: &MPlaceTy<'tcx>,
745 atomic: AtomicWriteOrd,
746 ) -> InterpResult<'tcx> {
747 let this = self.eval_context_mut();
748 this.atomic_access_check(dest, AtomicAccessType::Store)?;
749
750 let old_val = this.run_for_validation_mut(|this| this.read_scalar(dest)).discard_err();
755 if let Some(genmc_ctx) = this.machine.data_race.as_genmc_ref() {
757 genmc_ctx.atomic_store(this, dest.ptr().addr(), dest.layout.size, val, atomic)?;
759 return interp_ok(());
760 }
761 this.allow_data_races_mut(move |this| this.write_scalar(val, dest))?;
762 this.validate_atomic_store(dest, atomic)?;
763 this.buffered_atomic_write(val, dest, atomic, old_val)
764 }
765
766 fn atomic_rmw_op_immediate(
768 &mut self,
769 place: &MPlaceTy<'tcx>,
770 rhs: &ImmTy<'tcx>,
771 op: mir::BinOp,
772 not: bool,
773 atomic: AtomicRwOrd,
774 ) -> InterpResult<'tcx, ImmTy<'tcx>> {
775 let this = self.eval_context_mut();
776 this.atomic_access_check(place, AtomicAccessType::Rmw)?;
777
778 let old = this.allow_data_races_mut(|this| this.read_immediate(place))?;
779
780 if let Some(genmc_ctx) = this.machine.data_race.as_genmc_ref() {
782 let (old_val, new_val) = genmc_ctx.atomic_rmw_op(
784 this,
785 place.ptr().addr(),
786 place.layout.size,
787 atomic,
788 (op, not),
789 rhs.to_scalar(),
790 )?;
791 this.allow_data_races_mut(|this| this.write_scalar(new_val, place))?;
792 return interp_ok(ImmTy::from_scalar(old_val, old.layout));
793 }
794
795 let val = this.binary_op(op, &old, rhs)?;
796 let val = if not { this.unary_op(mir::UnOp::Not, &val)? } else { val };
797 this.allow_data_races_mut(|this| this.write_immediate(*val, place))?;
798
799 this.validate_atomic_rmw(place, atomic)?;
800
801 this.buffered_atomic_rmw(val.to_scalar(), place, atomic, old.to_scalar())?;
802 interp_ok(old)
803 }
804
805 fn atomic_exchange_scalar(
808 &mut self,
809 place: &MPlaceTy<'tcx>,
810 new: Scalar,
811 atomic: AtomicRwOrd,
812 ) -> InterpResult<'tcx, Scalar> {
813 let this = self.eval_context_mut();
814 this.atomic_access_check(place, AtomicAccessType::Rmw)?;
815
816 let old = this.allow_data_races_mut(|this| this.read_scalar(place))?;
817 this.allow_data_races_mut(|this| this.write_scalar(new, place))?;
818
819 if let Some(genmc_ctx) = this.machine.data_race.as_genmc_ref() {
821 let (old_val, _is_success) = genmc_ctx.atomic_exchange(
823 this,
824 place.ptr().addr(),
825 place.layout.size,
826 new,
827 atomic,
828 )?;
829 return interp_ok(old_val);
830 }
831
832 this.validate_atomic_rmw(place, atomic)?;
833
834 this.buffered_atomic_rmw(new, place, atomic, old)?;
835 interp_ok(old)
836 }
837
838 fn atomic_min_max_scalar(
841 &mut self,
842 place: &MPlaceTy<'tcx>,
843 rhs: ImmTy<'tcx>,
844 min: bool,
845 atomic: AtomicRwOrd,
846 ) -> InterpResult<'tcx, ImmTy<'tcx>> {
847 let this = self.eval_context_mut();
848 this.atomic_access_check(place, AtomicAccessType::Rmw)?;
849
850 let old = this.allow_data_races_mut(|this| this.read_immediate(place))?;
851
852 if let Some(genmc_ctx) = this.machine.data_race.as_genmc_ref() {
854 let (old_val, new_val) = genmc_ctx.atomic_min_max_op(
856 this,
857 place.ptr().addr(),
858 place.layout.size,
859 atomic,
860 min,
861 old.layout.backend_repr.is_signed(),
862 rhs.to_scalar(),
863 )?;
864 this.allow_data_races_mut(|this| this.write_scalar(new_val, place))?;
865 return interp_ok(ImmTy::from_scalar(old_val, old.layout));
866 }
867
868 let lt = this.binary_op(mir::BinOp::Lt, &old, &rhs)?.to_scalar().to_bool()?;
869
870 #[rustfmt::skip] let new_val = if min {
872 if lt { &old } else { &rhs }
873 } else {
874 if lt { &rhs } else { &old }
875 };
876
877 this.allow_data_races_mut(|this| this.write_immediate(**new_val, place))?;
878
879 this.validate_atomic_rmw(place, atomic)?;
880
881 this.buffered_atomic_rmw(new_val.to_scalar(), place, atomic, old.to_scalar())?;
882
883 interp_ok(old)
885 }
886
887 fn atomic_compare_exchange_scalar(
894 &mut self,
895 place: &MPlaceTy<'tcx>,
896 expect_old: &ImmTy<'tcx>,
897 new: Scalar,
898 success: AtomicRwOrd,
899 fail: AtomicReadOrd,
900 can_fail_spuriously: bool,
901 ) -> InterpResult<'tcx, Immediate<Provenance>> {
902 use rand::Rng as _;
903 let this = self.eval_context_mut();
904 this.atomic_access_check(place, AtomicAccessType::Rmw)?;
905
906 let old = this.allow_data_races_mut(|this| this.read_immediate(place))?;
911
912 if let Some(genmc_ctx) = this.machine.data_race.as_genmc_ref() {
914 let (old, cmpxchg_success) = genmc_ctx.atomic_compare_exchange(
915 this,
916 place.ptr().addr(),
917 place.layout.size,
918 this.read_scalar(expect_old)?,
919 new,
920 success,
921 fail,
922 can_fail_spuriously,
923 )?;
924 if cmpxchg_success {
925 this.allow_data_races_mut(|this| this.write_scalar(new, place))?;
926 }
927 return interp_ok(Immediate::ScalarPair(old, Scalar::from_bool(cmpxchg_success)));
928 }
929
930 let eq = this.binary_op(mir::BinOp::Eq, &old, expect_old)?;
932 let success_rate = 1.0 - this.machine.cmpxchg_weak_failure_rate;
935 let cmpxchg_success = eq.to_scalar().to_bool()?
936 && if can_fail_spuriously {
937 this.machine.rng.get_mut().random_bool(success_rate)
938 } else {
939 true
940 };
941 let res = Immediate::ScalarPair(old.to_scalar(), Scalar::from_bool(cmpxchg_success));
942
943 if cmpxchg_success {
947 this.allow_data_races_mut(|this| this.write_scalar(new, place))?;
948 this.validate_atomic_rmw(place, success)?;
949 this.buffered_atomic_rmw(new, place, success, old.to_scalar())?;
950 } else {
951 this.validate_atomic_load(place, fail)?;
952 this.perform_read_on_buffered_latest(place, fail)?;
957 }
958
959 interp_ok(res)
961 }
962
963 fn atomic_fence(&mut self, atomic: AtomicFenceOrd) -> InterpResult<'tcx> {
965 let this = self.eval_context_mut();
966 let machine = &this.machine;
967 match &this.machine.data_race {
968 GlobalDataRaceHandler::None => interp_ok(()),
969 GlobalDataRaceHandler::Vclocks(data_race) => data_race.atomic_fence(machine, atomic),
970 GlobalDataRaceHandler::Genmc(genmc_ctx) => genmc_ctx.atomic_fence(machine, atomic),
971 }
972 }
973
974 fn release_clock<R>(&self, callback: impl FnOnce(&VClock) -> R) -> Option<R> {
980 let this = self.eval_context_ref();
981 Some(
982 this.machine.data_race.as_vclocks_ref()?.release_clock(&this.machine.threads, callback),
983 )
984 }
985
986 fn acquire_clock(&self, clock: &VClock) {
989 let this = self.eval_context_ref();
990 if let Some(data_race) = this.machine.data_race.as_vclocks_ref() {
991 data_race.acquire_clock(clock, &this.machine.threads);
992 }
993 }
994}
995
996#[derive(Debug, Clone)]
998pub struct VClockAlloc {
999 alloc_ranges: RefCell<RangeMap<MemoryCellClocks>>,
1001}
1002
1003impl VisitProvenance for VClockAlloc {
1004 fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
1005 }
1007}
1008
1009impl VClockAlloc {
1010 pub fn new_allocation(
1012 global: &GlobalState,
1013 thread_mgr: &ThreadManager<'_>,
1014 len: Size,
1015 kind: MemoryKind,
1016 current_span: Span,
1017 ) -> VClockAlloc {
1018 let (alloc_timestamp, alloc_index) = match kind {
1020 MemoryKind::Machine(
1022 MiriMemoryKind::Rust
1023 | MiriMemoryKind::Miri
1024 | MiriMemoryKind::C
1025 | MiriMemoryKind::WinHeap
1026 | MiriMemoryKind::WinLocal
1027 | MiriMemoryKind::Mmap,
1028 )
1029 | MemoryKind::Stack => {
1030 let (alloc_index, clocks) = global.active_thread_state(thread_mgr);
1031 let mut alloc_timestamp = clocks.clock[alloc_index];
1032 alloc_timestamp.span = current_span;
1033 (alloc_timestamp, alloc_index)
1034 }
1035 MemoryKind::Machine(
1038 MiriMemoryKind::Global
1039 | MiriMemoryKind::Machine
1040 | MiriMemoryKind::Runtime
1041 | MiriMemoryKind::ExternStatic
1042 | MiriMemoryKind::Tls,
1043 )
1044 | MemoryKind::CallerLocation =>
1045 (VTimestamp::ZERO, global.thread_index(ThreadId::MAIN_THREAD)),
1046 };
1047 VClockAlloc {
1048 alloc_ranges: RefCell::new(RangeMap::new(
1049 len,
1050 MemoryCellClocks::new(alloc_timestamp, alloc_index),
1051 )),
1052 }
1053 }
1054
1055 fn find_gt_index(l: &VClock, r: &VClock) -> Option<VectorIdx> {
1058 trace!("Find index where not {:?} <= {:?}", l, r);
1059 let l_slice = l.as_slice();
1060 let r_slice = r.as_slice();
1061 l_slice
1062 .iter()
1063 .zip(r_slice.iter())
1064 .enumerate()
1065 .find_map(|(idx, (&l, &r))| if l > r { Some(idx) } else { None })
1066 .or_else(|| {
1067 if l_slice.len() > r_slice.len() {
1068 let l_remainder_slice = &l_slice[r_slice.len()..];
1073 let idx = l_remainder_slice
1074 .iter()
1075 .enumerate()
1076 .find_map(|(idx, &r)| if r == VTimestamp::ZERO { None } else { Some(idx) })
1077 .expect("Invalid VClock Invariant");
1078 Some(idx + r_slice.len())
1079 } else {
1080 None
1081 }
1082 })
1083 .map(VectorIdx::new)
1084 }
1085
1086 #[cold]
1093 #[inline(never)]
1094 fn report_data_race<'tcx>(
1095 global: &GlobalState,
1096 thread_mgr: &ThreadManager<'_>,
1097 mem_clocks: &MemoryCellClocks,
1098 access: AccessType,
1099 access_size: Size,
1100 ptr_dbg: interpret::Pointer<AllocId>,
1101 ty: Option<Ty<'_>>,
1102 ) -> InterpResult<'tcx> {
1103 let (active_index, active_clocks) = global.active_thread_state(thread_mgr);
1104 let mut other_size = None; let write_clock;
1106 let (other_access, other_thread, other_clock) =
1107 if !access.is_atomic() &&
1109 let Some(atomic) = mem_clocks.atomic() &&
1110 let Some(idx) = Self::find_gt_index(&atomic.write_vector, &active_clocks.clock)
1111 {
1112 (AccessType::AtomicStore, idx, &atomic.write_vector)
1113 } else if !access.is_atomic() &&
1114 let Some(atomic) = mem_clocks.atomic() &&
1115 let Some(idx) = Self::find_gt_index(&atomic.read_vector, &active_clocks.clock)
1116 {
1117 (AccessType::AtomicLoad, idx, &atomic.read_vector)
1118 } else if mem_clocks.write.1 > active_clocks.clock[mem_clocks.write.0] {
1120 write_clock = mem_clocks.write();
1121 (AccessType::NaWrite(mem_clocks.write_type), mem_clocks.write.0, &write_clock)
1122 } else if let Some(idx) = Self::find_gt_index(&mem_clocks.read, &active_clocks.clock) {
1123 (AccessType::NaRead(mem_clocks.read[idx].read_type()), idx, &mem_clocks.read)
1124 } else if access.is_atomic() && let Some(atomic) = mem_clocks.atomic() && atomic.size != Some(access_size) {
1126 other_size = Some(atomic.size.unwrap_or(Size::ZERO));
1129 if let Some(idx) = Self::find_gt_index(&atomic.write_vector, &active_clocks.clock)
1130 {
1131 (AccessType::AtomicStore, idx, &atomic.write_vector)
1132 } else if let Some(idx) =
1133 Self::find_gt_index(&atomic.read_vector, &active_clocks.clock)
1134 {
1135 (AccessType::AtomicLoad, idx, &atomic.read_vector)
1136 } else {
1137 unreachable!(
1138 "Failed to report data-race for mixed-size access: no race found"
1139 )
1140 }
1141 } else {
1142 unreachable!("Failed to report data-race")
1143 };
1144
1145 let active_thread_info = global.print_thread_metadata(thread_mgr, active_index);
1147 let other_thread_info = global.print_thread_metadata(thread_mgr, other_thread);
1148 let involves_non_atomic = !access.is_atomic() || !other_access.is_atomic();
1149
1150 let extra = if other_size.is_some() {
1152 assert!(!involves_non_atomic);
1153 Some("overlapping unsynchronized atomic accesses must use the same access size")
1154 } else if access.is_read() && other_access.is_read() {
1155 panic!("there should be no same-size read-read races")
1156 } else {
1157 None
1158 };
1159 Err(err_machine_stop!(TerminationInfo::DataRace {
1160 involves_non_atomic,
1161 extra,
1162 retag_explain: access.is_retag() || other_access.is_retag(),
1163 ptr: ptr_dbg,
1164 op1: RacingOp {
1165 action: other_access.description(None, other_size),
1166 thread_info: other_thread_info,
1167 span: other_clock.as_slice()[other_thread.index()].span_data(),
1168 },
1169 op2: RacingOp {
1170 action: access.description(ty, other_size.map(|_| access_size)),
1171 thread_info: active_thread_info,
1172 span: active_clocks.clock.as_slice()[active_index.index()].span_data(),
1173 },
1174 }))?
1175 }
1176
1177 pub fn read<'tcx>(
1184 &self,
1185 alloc_id: AllocId,
1186 access_range: AllocRange,
1187 read_type: NaReadType,
1188 ty: Option<Ty<'_>>,
1189 machine: &MiriMachine<'_>,
1190 ) -> InterpResult<'tcx> {
1191 let current_span = machine.current_span();
1192 let global = machine.data_race.as_vclocks_ref().unwrap();
1193 if !global.race_detecting() {
1194 return interp_ok(());
1195 }
1196 let (index, mut thread_clocks) = global.active_thread_state_mut(&machine.threads);
1197 let mut alloc_ranges = self.alloc_ranges.borrow_mut();
1198 for (mem_clocks_range, mem_clocks) in
1199 alloc_ranges.iter_mut(access_range.start, access_range.size)
1200 {
1201 if let Err(DataRace) =
1202 mem_clocks.read_race_detect(&mut thread_clocks, index, read_type, current_span)
1203 {
1204 drop(thread_clocks);
1205 return Self::report_data_race(
1207 global,
1208 &machine.threads,
1209 mem_clocks,
1210 AccessType::NaRead(read_type),
1211 access_range.size,
1212 interpret::Pointer::new(alloc_id, Size::from_bytes(mem_clocks_range.start)),
1213 ty,
1214 );
1215 }
1216 }
1217 interp_ok(())
1218 }
1219
1220 pub fn write<'tcx>(
1226 &mut self,
1227 alloc_id: AllocId,
1228 access_range: AllocRange,
1229 write_type: NaWriteType,
1230 ty: Option<Ty<'_>>,
1231 machine: &mut MiriMachine<'_>,
1232 ) -> InterpResult<'tcx> {
1233 let current_span = machine.current_span();
1234 let global = machine.data_race.as_vclocks_mut().unwrap();
1235 if !global.race_detecting() {
1236 return interp_ok(());
1237 }
1238 let (index, mut thread_clocks) = global.active_thread_state_mut(&machine.threads);
1239 for (mem_clocks_range, mem_clocks) in
1240 self.alloc_ranges.get_mut().iter_mut(access_range.start, access_range.size)
1241 {
1242 if let Err(DataRace) =
1243 mem_clocks.write_race_detect(&mut thread_clocks, index, write_type, current_span)
1244 {
1245 drop(thread_clocks);
1246 return Self::report_data_race(
1248 global,
1249 &machine.threads,
1250 mem_clocks,
1251 AccessType::NaWrite(write_type),
1252 access_range.size,
1253 interpret::Pointer::new(alloc_id, Size::from_bytes(mem_clocks_range.start)),
1254 ty,
1255 );
1256 }
1257 }
1258 interp_ok(())
1259 }
1260}
1261
1262#[derive(Debug, Default)]
1265pub struct FrameState {
1266 local_clocks: RefCell<FxHashMap<mir::Local, LocalClocks>>,
1267}
1268
1269#[derive(Debug)]
1273struct LocalClocks {
1274 write: VTimestamp,
1275 write_type: NaWriteType,
1276 read: VTimestamp,
1277}
1278
1279impl Default for LocalClocks {
1280 fn default() -> Self {
1281 Self { write: VTimestamp::ZERO, write_type: NaWriteType::Allocate, read: VTimestamp::ZERO }
1282 }
1283}
1284
1285impl FrameState {
1286 pub fn local_write(&self, local: mir::Local, storage_live: bool, machine: &MiriMachine<'_>) {
1287 let current_span = machine.current_span();
1288 let global = machine.data_race.as_vclocks_ref().unwrap();
1289 if !global.race_detecting() {
1290 return;
1291 }
1292 let (index, mut thread_clocks) = global.active_thread_state_mut(&machine.threads);
1293 if !current_span.is_dummy() {
1295 thread_clocks.clock.index_mut(index).span = current_span;
1296 }
1297 let mut clocks = self.local_clocks.borrow_mut();
1298 if storage_live {
1299 let new_clocks = LocalClocks {
1300 write: thread_clocks.clock[index],
1301 write_type: NaWriteType::Allocate,
1302 read: VTimestamp::ZERO,
1303 };
1304 clocks.insert(local, new_clocks);
1307 } else {
1308 let clocks = clocks.entry(local).or_default();
1311 clocks.write = thread_clocks.clock[index];
1312 clocks.write_type = NaWriteType::Write;
1313 }
1314 }
1315
1316 pub fn local_read(&self, local: mir::Local, machine: &MiriMachine<'_>) {
1317 let current_span = machine.current_span();
1318 let global = machine.data_race.as_vclocks_ref().unwrap();
1319 if !global.race_detecting() {
1320 return;
1321 }
1322 let (index, mut thread_clocks) = global.active_thread_state_mut(&machine.threads);
1323 if !current_span.is_dummy() {
1325 thread_clocks.clock.index_mut(index).span = current_span;
1326 }
1327 thread_clocks.clock.index_mut(index).set_read_type(NaReadType::Read);
1328 let mut clocks = self.local_clocks.borrow_mut();
1331 let clocks = clocks.entry(local).or_default();
1332 clocks.read = thread_clocks.clock[index];
1333 }
1334
1335 pub fn local_moved_to_memory(
1336 &self,
1337 local: mir::Local,
1338 alloc: &mut VClockAlloc,
1339 machine: &MiriMachine<'_>,
1340 ) {
1341 let global = machine.data_race.as_vclocks_ref().unwrap();
1342 if !global.race_detecting() {
1343 return;
1344 }
1345 let (index, _thread_clocks) = global.active_thread_state_mut(&machine.threads);
1346 let local_clocks = self.local_clocks.borrow_mut().remove(&local).unwrap_or_default();
1350 for (_mem_clocks_range, mem_clocks) in alloc.alloc_ranges.get_mut().iter_mut_all() {
1351 assert_eq!(mem_clocks.write.0, index);
1354 mem_clocks.write = (index, local_clocks.write);
1356 mem_clocks.write_type = local_clocks.write_type;
1357 mem_clocks.read = VClock::new_with_index(index, local_clocks.read);
1358 }
1359 }
1360}
1361
1362impl<'tcx> EvalContextPrivExt<'tcx> for MiriInterpCx<'tcx> {}
1363trait EvalContextPrivExt<'tcx>: MiriInterpCxExt<'tcx> {
1364 #[inline]
1372 fn allow_data_races_ref<R>(&self, op: impl FnOnce(&MiriInterpCx<'tcx>) -> R) -> R {
1373 let this = self.eval_context_ref();
1374 this.machine.data_race.set_ongoing_action_data_race_free(true);
1375 let result = op(this);
1376 this.machine.data_race.set_ongoing_action_data_race_free(false);
1377 result
1378 }
1379
1380 #[inline]
1384 fn allow_data_races_mut<R>(&mut self, op: impl FnOnce(&mut MiriInterpCx<'tcx>) -> R) -> R {
1385 let this = self.eval_context_mut();
1386 this.machine.data_race.set_ongoing_action_data_race_free(true);
1387 let result = op(this);
1388 this.machine.data_race.set_ongoing_action_data_race_free(false);
1389 result
1390 }
1391
1392 fn atomic_access_check(
1394 &self,
1395 place: &MPlaceTy<'tcx>,
1396 access_type: AtomicAccessType,
1397 ) -> InterpResult<'tcx> {
1398 let this = self.eval_context_ref();
1399 let align = Align::from_bytes(place.layout.size.bytes()).unwrap();
1403 this.check_ptr_align(place.ptr(), align)?;
1404 let (alloc_id, _offset, _prov) = this
1412 .ptr_try_get_alloc_id(place.ptr(), 0)
1413 .expect("there are no zero-sized atomic accesses");
1414 if this.get_alloc_mutability(alloc_id)? == Mutability::Not {
1415 match access_type {
1417 AtomicAccessType::Rmw | AtomicAccessType::Store => {
1418 throw_ub_format!(
1419 "atomic store and read-modify-write operations cannot be performed on read-only memory\n\
1420 see <https://doc.rust-lang.org/nightly/std/sync/atomic/index.html#atomic-accesses-to-read-only-memory> for more information"
1421 );
1422 }
1423 AtomicAccessType::Load(_)
1424 if place.layout.size > this.tcx.data_layout().pointer_size() =>
1425 {
1426 throw_ub_format!(
1427 "large atomic load operations cannot be performed on read-only memory\n\
1428 these operations often have to be implemented using read-modify-write operations, which require writeable memory\n\
1429 see <https://doc.rust-lang.org/nightly/std/sync/atomic/index.html#atomic-accesses-to-read-only-memory> for more information"
1430 );
1431 }
1432 AtomicAccessType::Load(o) if o != AtomicReadOrd::Relaxed => {
1433 throw_ub_format!(
1434 "non-relaxed atomic load operations cannot be performed on read-only memory\n\
1435 these operations sometimes have to be implemented using read-modify-write operations, which require writeable memory\n\
1436 see <https://doc.rust-lang.org/nightly/std/sync/atomic/index.html#atomic-accesses-to-read-only-memory> for more information"
1437 );
1438 }
1439 _ => {
1440 }
1442 }
1443 }
1444 interp_ok(())
1445 }
1446
1447 fn validate_atomic_load(
1450 &self,
1451 place: &MPlaceTy<'tcx>,
1452 atomic: AtomicReadOrd,
1453 ) -> InterpResult<'tcx> {
1454 let this = self.eval_context_ref();
1455 this.validate_atomic_op(
1456 place,
1457 atomic,
1458 AccessType::AtomicLoad,
1459 move |memory, clocks, index, atomic| {
1460 if atomic == AtomicReadOrd::Relaxed {
1461 memory.load_relaxed(&mut *clocks, index, place.layout.size)
1462 } else {
1463 memory.load_acquire(&mut *clocks, index, place.layout.size)
1464 }
1465 },
1466 )
1467 }
1468
1469 fn validate_atomic_store(
1472 &mut self,
1473 place: &MPlaceTy<'tcx>,
1474 atomic: AtomicWriteOrd,
1475 ) -> InterpResult<'tcx> {
1476 let this = self.eval_context_mut();
1477 this.validate_atomic_op(
1478 place,
1479 atomic,
1480 AccessType::AtomicStore,
1481 move |memory, clocks, index, atomic| {
1482 if atomic == AtomicWriteOrd::Relaxed {
1483 memory.store_relaxed(clocks, index, place.layout.size)
1484 } else {
1485 memory.store_release(clocks, index, place.layout.size)
1486 }
1487 },
1488 )
1489 }
1490
1491 fn validate_atomic_rmw(
1494 &mut self,
1495 place: &MPlaceTy<'tcx>,
1496 atomic: AtomicRwOrd,
1497 ) -> InterpResult<'tcx> {
1498 use AtomicRwOrd::*;
1499 let acquire = matches!(atomic, Acquire | AcqRel | SeqCst);
1500 let release = matches!(atomic, Release | AcqRel | SeqCst);
1501 let this = self.eval_context_mut();
1502 this.validate_atomic_op(
1503 place,
1504 atomic,
1505 AccessType::AtomicRmw,
1506 move |memory, clocks, index, _| {
1507 if acquire {
1508 memory.load_acquire(clocks, index, place.layout.size)?;
1509 } else {
1510 memory.load_relaxed(clocks, index, place.layout.size)?;
1511 }
1512 if release {
1513 memory.rmw_release(clocks, index, place.layout.size)
1514 } else {
1515 memory.rmw_relaxed(clocks, index, place.layout.size)
1516 }
1517 },
1518 )
1519 }
1520
1521 fn validate_atomic_op<A: Debug + Copy>(
1523 &self,
1524 place: &MPlaceTy<'tcx>,
1525 atomic: A,
1526 access: AccessType,
1527 mut op: impl FnMut(
1528 &mut MemoryCellClocks,
1529 &mut ThreadClockSet,
1530 VectorIdx,
1531 A,
1532 ) -> Result<(), DataRace>,
1533 ) -> InterpResult<'tcx> {
1534 let this = self.eval_context_ref();
1535 assert!(access.is_atomic());
1536 let Some(data_race) = this.machine.data_race.as_vclocks_ref() else {
1537 return interp_ok(());
1538 };
1539 if !data_race.race_detecting() {
1540 return interp_ok(());
1541 }
1542 let size = place.layout.size;
1543 let (alloc_id, base_offset, _prov) = this.ptr_get_alloc_id(place.ptr(), 0)?;
1544 let alloc_meta = this.get_alloc_extra(alloc_id)?.data_race.as_vclocks_ref().unwrap();
1547 trace!(
1548 "Atomic op({}) with ordering {:?} on {:?} (size={})",
1549 access.description(None, None),
1550 &atomic,
1551 place.ptr(),
1552 size.bytes()
1553 );
1554
1555 let current_span = this.machine.current_span();
1556 data_race.maybe_perform_sync_operation(
1558 &this.machine.threads,
1559 current_span,
1560 |index, mut thread_clocks| {
1561 for (mem_clocks_range, mem_clocks) in
1562 alloc_meta.alloc_ranges.borrow_mut().iter_mut(base_offset, size)
1563 {
1564 if let Err(DataRace) = op(mem_clocks, &mut thread_clocks, index, atomic) {
1565 mem::drop(thread_clocks);
1566 return VClockAlloc::report_data_race(
1567 data_race,
1568 &this.machine.threads,
1569 mem_clocks,
1570 access,
1571 place.layout.size,
1572 interpret::Pointer::new(
1573 alloc_id,
1574 Size::from_bytes(mem_clocks_range.start),
1575 ),
1576 None,
1577 )
1578 .map(|_| true);
1579 }
1580 }
1581
1582 interp_ok(true)
1584 },
1585 )?;
1586
1587 if tracing::enabled!(tracing::Level::TRACE) {
1589 for (_offset, mem_clocks) in alloc_meta.alloc_ranges.borrow().iter(base_offset, size) {
1590 trace!(
1591 "Updated atomic memory({:?}, size={}) to {:#?}",
1592 place.ptr(),
1593 size.bytes(),
1594 mem_clocks.atomic_ops
1595 );
1596 }
1597 }
1598
1599 interp_ok(())
1600 }
1601}
1602
1603impl GlobalState {
1604 pub fn new(config: &MiriConfig) -> Self {
1607 let mut global_state = GlobalState {
1608 multi_threaded: Cell::new(false),
1609 ongoing_action_data_race_free: Cell::new(false),
1610 vector_clocks: RefCell::new(IndexVec::new()),
1611 vector_info: RefCell::new(IndexVec::new()),
1612 thread_info: RefCell::new(IndexVec::new()),
1613 reuse_candidates: RefCell::new(FxHashSet::default()),
1614 last_sc_fence: RefCell::new(VClock::default()),
1615 last_sc_write_per_thread: RefCell::new(VClock::default()),
1616 track_outdated_loads: config.track_outdated_loads,
1617 weak_memory: config.weak_memory_emulation,
1618 };
1619
1620 let index = global_state.vector_clocks.get_mut().push(ThreadClockSet::default());
1623 global_state.vector_info.get_mut().push(ThreadId::MAIN_THREAD);
1624 global_state
1625 .thread_info
1626 .get_mut()
1627 .push(ThreadExtraState { vector_index: Some(index), termination_vector_clock: None });
1628
1629 global_state
1630 }
1631
1632 fn race_detecting(&self) -> bool {
1636 self.multi_threaded.get() && !self.ongoing_action_data_race_free.get()
1637 }
1638
1639 pub fn ongoing_action_data_race_free(&self) -> bool {
1640 self.ongoing_action_data_race_free.get()
1641 }
1642
1643 fn find_vector_index_reuse_candidate(&self) -> Option<VectorIdx> {
1646 let mut reuse = self.reuse_candidates.borrow_mut();
1647 let vector_clocks = self.vector_clocks.borrow();
1648 for &candidate in reuse.iter() {
1649 let target_timestamp = vector_clocks[candidate].clock[candidate];
1650 if vector_clocks.iter_enumerated().all(|(clock_idx, clock)| {
1651 let no_data_race = clock.clock[candidate] >= target_timestamp;
1654
1655 let vector_terminated = reuse.contains(&clock_idx);
1658
1659 no_data_race || vector_terminated
1662 }) {
1663 assert!(reuse.remove(&candidate));
1668 return Some(candidate);
1669 }
1670 }
1671 None
1672 }
1673
1674 #[inline]
1677 pub fn thread_created(
1678 &mut self,
1679 thread_mgr: &ThreadManager<'_>,
1680 thread: ThreadId,
1681 current_span: Span,
1682 ) {
1683 let current_index = self.active_thread_index(thread_mgr);
1684
1685 self.multi_threaded.set(true);
1688
1689 let mut thread_info = self.thread_info.borrow_mut();
1691 thread_info.ensure_contains_elem(thread, Default::default);
1692
1693 let created_index = if let Some(reuse_index) = self.find_vector_index_reuse_candidate() {
1696 let vector_clocks = self.vector_clocks.get_mut();
1699 vector_clocks[reuse_index].increment_clock(reuse_index, current_span);
1700
1701 let vector_info = self.vector_info.get_mut();
1704 let old_thread = vector_info[reuse_index];
1705 vector_info[reuse_index] = thread;
1706
1707 thread_info[old_thread].vector_index = None;
1710
1711 reuse_index
1712 } else {
1713 let vector_info = self.vector_info.get_mut();
1716 vector_info.push(thread)
1717 };
1718
1719 trace!("Creating thread = {:?} with vector index = {:?}", thread, created_index);
1720
1721 thread_info[thread].vector_index = Some(created_index);
1723
1724 let vector_clocks = self.vector_clocks.get_mut();
1726 if created_index == vector_clocks.next_index() {
1727 vector_clocks.push(ThreadClockSet::default());
1728 }
1729
1730 let (current, created) = vector_clocks.pick2_mut(current_index, created_index);
1732
1733 created.join_with(current);
1736
1737 current.increment_clock(current_index, current_span);
1740 created.increment_clock(created_index, current_span);
1741 }
1742
1743 #[inline]
1747 pub fn thread_joined(&mut self, threads: &ThreadManager<'_>, joinee: ThreadId) {
1748 let thread_info = self.thread_info.borrow();
1749 let thread_info = &thread_info[joinee];
1750
1751 let join_clock = thread_info
1753 .termination_vector_clock
1754 .as_ref()
1755 .expect("joined with thread but thread has not terminated");
1756 self.acquire_clock(join_clock, threads);
1758
1759 if let Some(current_index) = thread_info.vector_index {
1764 if threads.get_live_thread_count() == 1 {
1765 let vector_clocks = self.vector_clocks.get_mut();
1766 let current_clock = &vector_clocks[current_index];
1768 if vector_clocks
1769 .iter_enumerated()
1770 .all(|(idx, clocks)| clocks.clock[idx] <= current_clock.clock[idx])
1771 {
1772 self.multi_threaded.set(false);
1776 }
1777 }
1778 }
1779 }
1780
1781 #[inline]
1789 pub fn thread_terminated(&mut self, thread_mgr: &ThreadManager<'_>) {
1790 let current_thread = thread_mgr.active_thread();
1791 let current_index = self.active_thread_index(thread_mgr);
1792
1793 let terminaion_clock = self.release_clock(thread_mgr, |clock| clock.clone());
1795 self.thread_info.get_mut()[current_thread].termination_vector_clock =
1796 Some(terminaion_clock);
1797
1798 let reuse = self.reuse_candidates.get_mut();
1800 reuse.insert(current_index);
1801 }
1802
1803 fn atomic_fence<'tcx>(
1805 &self,
1806 machine: &MiriMachine<'tcx>,
1807 atomic: AtomicFenceOrd,
1808 ) -> InterpResult<'tcx> {
1809 let current_span = machine.current_span();
1810 self.maybe_perform_sync_operation(&machine.threads, current_span, |index, mut clocks| {
1811 trace!("Atomic fence on {:?} with ordering {:?}", index, atomic);
1812
1813 if atomic != AtomicFenceOrd::Release {
1817 clocks.apply_acquire_fence();
1819 }
1820 if atomic == AtomicFenceOrd::SeqCst {
1821 let mut sc_fence_clock = self.last_sc_fence.borrow_mut();
1829 sc_fence_clock.join(&clocks.clock);
1830 clocks.clock.join(&sc_fence_clock);
1831 clocks.write_seqcst.join(&self.last_sc_write_per_thread.borrow());
1834 }
1835 if atomic != AtomicFenceOrd::Acquire {
1838 clocks.apply_release_fence();
1840 }
1841
1842 interp_ok(atomic != AtomicFenceOrd::Acquire)
1844 })
1845 }
1846
1847 fn maybe_perform_sync_operation<'tcx>(
1855 &self,
1856 thread_mgr: &ThreadManager<'_>,
1857 current_span: Span,
1858 op: impl FnOnce(VectorIdx, RefMut<'_, ThreadClockSet>) -> InterpResult<'tcx, bool>,
1859 ) -> InterpResult<'tcx> {
1860 if self.multi_threaded.get() {
1861 let (index, clocks) = self.active_thread_state_mut(thread_mgr);
1862 if op(index, clocks)? {
1863 let (_, mut clocks) = self.active_thread_state_mut(thread_mgr);
1864 clocks.increment_clock(index, current_span);
1865 }
1866 }
1867 interp_ok(())
1868 }
1869
1870 fn print_thread_metadata(&self, thread_mgr: &ThreadManager<'_>, vector: VectorIdx) -> String {
1873 let thread = self.vector_info.borrow()[vector];
1874 let thread_name = thread_mgr.get_thread_display_name(thread);
1875 format!("thread `{thread_name}`")
1876 }
1877
1878 pub fn acquire_clock<'tcx>(&self, clock: &VClock, threads: &ThreadManager<'tcx>) {
1883 let thread = threads.active_thread();
1884 let (_, mut clocks) = self.thread_state_mut(thread);
1885 clocks.clock.join(clock);
1886 }
1887
1888 pub fn release_clock<'tcx, R>(
1892 &self,
1893 threads: &ThreadManager<'tcx>,
1894 callback: impl FnOnce(&VClock) -> R,
1895 ) -> R {
1896 let thread = threads.active_thread();
1897 let span = threads.active_thread_ref().current_span();
1898 let (index, mut clocks) = self.thread_state_mut(thread);
1899 let r = callback(&clocks.clock);
1900 clocks.increment_clock(index, span);
1903
1904 r
1905 }
1906
1907 fn thread_index(&self, thread: ThreadId) -> VectorIdx {
1908 self.thread_info.borrow()[thread].vector_index.expect("thread has no assigned vector")
1909 }
1910
1911 #[inline]
1914 fn thread_state_mut(&self, thread: ThreadId) -> (VectorIdx, RefMut<'_, ThreadClockSet>) {
1915 let index = self.thread_index(thread);
1916 let ref_vector = self.vector_clocks.borrow_mut();
1917 let clocks = RefMut::map(ref_vector, |vec| &mut vec[index]);
1918 (index, clocks)
1919 }
1920
1921 #[inline]
1924 fn thread_state(&self, thread: ThreadId) -> (VectorIdx, Ref<'_, ThreadClockSet>) {
1925 let index = self.thread_index(thread);
1926 let ref_vector = self.vector_clocks.borrow();
1927 let clocks = Ref::map(ref_vector, |vec| &vec[index]);
1928 (index, clocks)
1929 }
1930
1931 #[inline]
1934 pub(super) fn active_thread_state(
1935 &self,
1936 thread_mgr: &ThreadManager<'_>,
1937 ) -> (VectorIdx, Ref<'_, ThreadClockSet>) {
1938 self.thread_state(thread_mgr.active_thread())
1939 }
1940
1941 #[inline]
1944 pub(super) fn active_thread_state_mut(
1945 &self,
1946 thread_mgr: &ThreadManager<'_>,
1947 ) -> (VectorIdx, RefMut<'_, ThreadClockSet>) {
1948 self.thread_state_mut(thread_mgr.active_thread())
1949 }
1950
1951 #[inline]
1954 fn active_thread_index(&self, thread_mgr: &ThreadManager<'_>) -> VectorIdx {
1955 let active_thread_id = thread_mgr.active_thread();
1956 self.thread_index(active_thread_id)
1957 }
1958
1959 pub(super) fn sc_write(&self, thread_mgr: &ThreadManager<'_>) {
1961 let (index, clocks) = self.active_thread_state(thread_mgr);
1962 self.last_sc_write_per_thread.borrow_mut().set_at_index(&clocks.clock, index);
1963 }
1964
1965 pub(super) fn sc_read(&self, thread_mgr: &ThreadManager<'_>) {
1967 let (.., mut clocks) = self.active_thread_state_mut(thread_mgr);
1968 clocks.read_seqcst.join(&self.last_sc_fence.borrow());
1969 }
1970}