1 //! Implementation of a data-race detector using Lamport Timestamps / Vector-clocks
2 //! based on the Dyamic Race Detection for C++:
3 //! https://www.doc.ic.ac.uk/~afd/homepages/papers/pdfs/2017/POPL.pdf
4 //! which does not report false-positives when fences are used, and gives better
5 //! accuracy in presence of read-modify-write operations.
7 //! This does not explore weak memory orders and so can still miss data-races
8 //! but should not report false-positives
10 //! Data-race definiton from(https://en.cppreference.com/w/cpp/language/memory_model#Threads_and_data_races):
11 //! a data race occurs between two memory accesses if they are on different threads, at least one operation
12 //! is non-atomic, at least one operation is a write and neither access happens-before the other. Read the link
13 //! for full definition.
15 //! This re-uses vector indexes for threads that are known to be unable to report data-races, this is valid
16 //! because it only re-uses vector indexes once all currently-active (not-terminated) threads have an internal
17 //! vector clock that happens-after the join operation of the candidate thread. Threads that have not been joined
18 //! on are not considered. Since the thread's vector clock will only increase and a data-race implies that
19 //! there is some index x where clock[x] > thread_clock, when this is true clock[candidate-idx] > thread_clock
20 //! can never hold and hence a data-race can never be reported in that vector index again.
21 //! This means that the thread-index can be safely re-used, starting on the next timestamp for the newly created
24 //! The sequentially consistant ordering corresponds to the ordering that the threads
25 //! are currently scheduled, this means that the data-race detector has no additional
26 //! logic for sequentially consistent accesses at the moment since they are indistinguishable
27 //! from acquire/release operations. If weak memory orderings are explored then this
28 //! may need to change or be updated accordingly.
30 //! Per the C++ spec for the memory model a sequentially consistent operation:
31 //! "A load operation with this memory order performs an acquire operation,
32 //! a store performs a release operation, and read-modify-write performs
33 //! both an acquire operation and a release operation, plus a single total
34 //! order exists in which all threads observe all modifications in the same
35 //! order (see Sequentially-consistent ordering below) "
36 //! So in the absence of weak memory effects a seq-cst load & a seq-cst store is identical
37 //! to a acquire load and a release store given the global sequentially consistent order
40 //! The timestamps used in the data-race detector assign each sequence of non-atomic operations
41 //! followed by a single atomic or concurrent operation a single timestamp.
42 //! Write, Read, Write, ThreadJoin will be represented by a single timestamp value on a thread.
43 //! This is because extra increment operations between the operations in the sequence are not
44 //! required for accurate reporting of data-race values.
46 //! As per the paper a threads timestamp is only incremented after a release operation is performed
47 //! so some atomic operations that only perform acquires do not increment the timestamp. Due to shared
48 //! code some atomic operations may increment the timestamp when not necessary but this has no effect
49 //! on the data-race detection code.
52 //! currently we have our own local copy of the currently active thread index and names, this is due
53 //! in part to the inability to access the current location of threads.active_thread inside the AllocExtra
54 //! read, write and deallocate functions and should be cleaned up in the future.
57 cell::{Cell, Ref, RefCell, RefMut},
63 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
64 use rustc_index::vec::{Idx, IndexVec};
65 use rustc_middle::{mir, ty::layout::TyAndLayout};
66 use rustc_target::abi::Size;
69 ImmTy, Immediate, InterpResult, MPlaceTy, MemPlaceMeta, MiriEvalContext, MiriEvalContextExt,
70 OpTy, Pointer, RangeMap, ScalarMaybeUninit, Tag, ThreadId, VClock, VSmallClockMap, VTimestamp,
74 pub type AllocExtra = VClockAlloc;
75 pub type MemoryExtra = Rc<GlobalState>;
77 /// Valid atomic read-write operations, alias of atomic::Ordering (not non-exhaustive).
78 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
87 /// Valid atomic read operations, subset of atomic::Ordering.
88 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
89 pub enum AtomicReadOp {
95 /// Valid atomic write operations, subset of atomic::Ordering.
96 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
97 pub enum AtomicWriteOp {
103 /// Valid atomic fence operations, subset of atomic::Ordering.
104 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
105 pub enum AtomicFenceOp {
112 /// The current set of vector clocks describing the state
113 /// of a thread, contains the happens-before clock and
114 /// additional metadata to model atomic fence operations.
115 #[derive(Clone, Default, Debug)]
116 struct ThreadClockSet {
117 /// The increasing clock representing timestamps
118 /// that happen-before this thread.
121 /// The set of timestamps that will happen-before this
122 /// thread once it performs an acquire fence.
123 fence_acquire: VClock,
125 /// The last timesamp of happens-before relations that
126 /// have been released by this thread by a fence.
127 fence_release: VClock,
130 impl ThreadClockSet {
131 /// Apply the effects of a release fence to this
132 /// set of thread vector clocks.
134 fn apply_release_fence(&mut self) {
135 self.fence_release.clone_from(&self.clock);
138 /// Apply the effects of a acquire fence to this
139 /// set of thread vector clocks.
141 fn apply_acquire_fence(&mut self) {
142 self.clock.join(&self.fence_acquire);
145 /// Increment the happens-before clock at a
148 fn increment_clock(&mut self, index: VectorIdx) {
149 self.clock.increment_index(index);
152 /// Join the happens-before clock with that of
153 /// another thread, used to model thread join
155 fn join_with(&mut self, other: &ThreadClockSet) {
156 self.clock.join(&other.clock);
160 /// Error returned by finding a data race
161 /// should be elaborated upon.
162 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
165 /// Externally stored memory cell clocks
166 /// explicitly to reduce memory usage for the
167 /// common case where no atomic operations
168 /// exists on the memory cell.
169 #[derive(Clone, PartialEq, Eq, Default, Debug)]
170 struct AtomicMemoryCellClocks {
171 /// The clock-vector of the timestamp of the last atomic
172 /// read operation performed by each thread.
173 /// This detects potential data-races between atomic read
174 /// and non-atomic write operations.
177 /// The clock-vector of the timestamp of the last atomic
178 /// write operation performed by each thread.
179 /// This detects potential data-races between atomic write
180 /// and non-atomic read or write operations.
181 write_vector: VClock,
183 /// Synchronization vector for acquire-release semantics
184 /// contains the vector of timestamps that will
185 /// happen-before a thread if an acquire-load is
186 /// performed on the data.
189 /// The Hash-Map of all threads for which a release
190 /// sequence exists in the memory cell, required
191 /// since read-modify-write operations do not
192 /// invalidate existing release sequences.
193 /// See page 6 of linked paper.
194 release_sequences: VSmallClockMap,
197 /// Memory Cell vector clock metadata
198 /// for data-race detection.
199 #[derive(Clone, PartialEq, Eq, Debug)]
200 struct MemoryCellClocks {
201 /// The vector-clock timestamp of the last write
202 /// corresponding to the writing threads timestamp.
205 /// The identifier of the vector index, corresponding to a thread
206 /// that performed the last write operation.
207 write_index: VectorIdx,
209 /// The vector-clock of the timestamp of the last read operation
210 /// performed by a thread since the last write operation occured.
211 /// It is reset to zero on each write operation.
214 /// Atomic acquire & release sequence tracking clocks.
215 /// For non-atomic memory in the common case this
216 /// value is set to None.
217 atomic_ops: Option<Box<AtomicMemoryCellClocks>>,
220 /// Create a default memory cell clocks instance
221 /// for uninitialized memory.
222 impl Default for MemoryCellClocks {
223 fn default() -> Self {
225 read: VClock::default(),
227 write_index: VectorIdx::MAX_INDEX,
233 impl MemoryCellClocks {
234 /// Load the internal atomic memory cells if they exist.
236 fn atomic(&self) -> Option<&AtomicMemoryCellClocks> {
237 match &self.atomic_ops {
238 Some(op) => Some(&*op),
243 /// Load or create the internal atomic memory metadata
244 /// if it does not exist.
246 fn atomic_mut(&mut self) -> &mut AtomicMemoryCellClocks {
247 self.atomic_ops.get_or_insert_with(Default::default)
250 /// Update memory cell data-race tracking for atomic
251 /// load acquire semantics, is a no-op if this memory was
252 /// not used previously as atomic memory.
255 clocks: &mut ThreadClockSet,
257 ) -> Result<(), DataRace> {
258 self.atomic_read_detect(clocks, index)?;
259 if let Some(atomic) = self.atomic() {
260 clocks.clock.join(&atomic.sync_vector);
265 /// Update memory cell data-race tracking for atomic
266 /// load relaxed semantics, is a no-op if this memory was
267 /// not used previously as atomic memory.
270 clocks: &mut ThreadClockSet,
272 ) -> Result<(), DataRace> {
273 self.atomic_read_detect(clocks, index)?;
274 if let Some(atomic) = self.atomic() {
275 clocks.fence_acquire.join(&atomic.sync_vector);
280 /// Update the memory cell data-race tracking for atomic
281 /// store release semantics.
282 fn store_release(&mut self, clocks: &ThreadClockSet, index: VectorIdx) -> Result<(), DataRace> {
283 self.atomic_write_detect(clocks, index)?;
284 let atomic = self.atomic_mut();
285 atomic.sync_vector.clone_from(&clocks.clock);
286 atomic.release_sequences.clear();
287 atomic.release_sequences.insert(index, &clocks.clock);
291 /// Update the memory cell data-race tracking for atomic
292 /// store relaxed semantics.
293 fn store_relaxed(&mut self, clocks: &ThreadClockSet, index: VectorIdx) -> Result<(), DataRace> {
294 self.atomic_write_detect(clocks, index)?;
295 let atomic = self.atomic_mut();
296 atomic.sync_vector.clone_from(&clocks.fence_release);
297 if let Some(release) = atomic.release_sequences.get(index) {
298 atomic.sync_vector.join(release);
300 atomic.release_sequences.retain_index(index);
304 /// Update the memory cell data-race tracking for atomic
305 /// store release semantics for RMW operations.
306 fn rmw_release(&mut self, clocks: &ThreadClockSet, index: VectorIdx) -> Result<(), DataRace> {
307 self.atomic_write_detect(clocks, index)?;
308 let atomic = self.atomic_mut();
309 atomic.sync_vector.join(&clocks.clock);
310 atomic.release_sequences.insert(index, &clocks.clock);
314 /// Update the memory cell data-race tracking for atomic
315 /// store relaxed semantics for RMW operations.
316 fn rmw_relaxed(&mut self, clocks: &ThreadClockSet, index: VectorIdx) -> Result<(), DataRace> {
317 self.atomic_write_detect(clocks, index)?;
318 let atomic = self.atomic_mut();
319 atomic.sync_vector.join(&clocks.fence_release);
323 /// Detect data-races with an atomic read, caused by a non-atomic write that does
324 /// not happen-before the atomic-read.
325 fn atomic_read_detect(
327 clocks: &ThreadClockSet,
329 ) -> Result<(), DataRace> {
330 log::trace!("Atomic read with vectors: {:#?} :: {:#?}", self, clocks);
331 if self.write <= clocks.clock[self.write_index] {
332 let atomic = self.atomic_mut();
333 atomic.read_vector.set_at_index(&clocks.clock, index);
340 /// Detect data-races with an atomic write, either with a non-atomic read or with
341 /// a non-atomic write.
342 fn atomic_write_detect(
344 clocks: &ThreadClockSet,
346 ) -> Result<(), DataRace> {
347 log::trace!("Atomic write with vectors: {:#?} :: {:#?}", self, clocks);
348 if self.write <= clocks.clock[self.write_index] && self.read <= clocks.clock {
349 let atomic = self.atomic_mut();
350 atomic.write_vector.set_at_index(&clocks.clock, index);
357 /// Detect races for non-atomic read operations at the current memory cell
358 /// returns true if a data-race is detected.
361 clocks: &ThreadClockSet,
363 ) -> Result<(), DataRace> {
364 log::trace!("Unsynchronized read with vectors: {:#?} :: {:#?}", self, clocks);
365 if self.write <= clocks.clock[self.write_index] {
366 let race_free = if let Some(atomic) = self.atomic() {
367 atomic.write_vector <= clocks.clock
372 self.read.set_at_index(&clocks.clock, index);
382 /// Detect races for non-atomic write operations at the current memory cell
383 /// returns true if a data-race is detected.
384 fn write_race_detect(
386 clocks: &ThreadClockSet,
388 ) -> Result<(), DataRace> {
389 log::trace!("Unsynchronized write with vectors: {:#?} :: {:#?}", self, clocks);
390 if self.write <= clocks.clock[self.write_index] && self.read <= clocks.clock {
391 let race_free = if let Some(atomic) = self.atomic() {
392 atomic.write_vector <= clocks.clock && atomic.read_vector <= clocks.clock
397 self.write = clocks.clock[index];
398 self.write_index = index;
399 self.read.set_zero_vector();
410 /// Evaluation context extensions.
411 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {}
412 pub trait EvalContextExt<'mir, 'tcx: 'mir>: MiriEvalContextExt<'mir, 'tcx> {
413 /// Atomic variant of read_scalar_at_offset.
414 fn read_scalar_at_offset_atomic(
418 layout: TyAndLayout<'tcx>,
419 atomic: AtomicReadOp,
420 ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
421 let this = self.eval_context_ref();
422 let op_place = this.deref_operand(op)?;
423 let offset = Size::from_bytes(offset);
425 // Ensure that the following read at an offset is within bounds.
426 assert!(op_place.layout.size >= offset + layout.size);
427 let value_place = op_place.offset(offset, MemPlaceMeta::None, layout, this)?;
428 this.read_scalar_atomic(value_place, atomic)
431 /// Atomic variant of write_scalar_at_offset.
432 fn write_scalar_at_offset_atomic(
436 value: impl Into<ScalarMaybeUninit<Tag>>,
437 layout: TyAndLayout<'tcx>,
438 atomic: AtomicWriteOp,
439 ) -> InterpResult<'tcx> {
440 let this = self.eval_context_mut();
441 let op_place = this.deref_operand(op)?;
442 let offset = Size::from_bytes(offset);
444 // Ensure that the following read at an offset is within bounds.
445 assert!(op_place.layout.size >= offset + layout.size);
446 let value_place = op_place.offset(offset, MemPlaceMeta::None, layout, this)?;
447 this.write_scalar_atomic(value.into(), value_place, atomic)
450 /// Perform an atomic read operation at the memory location.
451 fn read_scalar_atomic(
453 place: MPlaceTy<'tcx, Tag>,
454 atomic: AtomicReadOp,
455 ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
456 let this = self.eval_context_ref();
457 let scalar = this.allow_data_races_ref(move |this| this.read_scalar(place.into()))?;
458 self.validate_atomic_load(place, atomic)?;
462 /// Perform an atomic write operation at the memory location.
463 fn write_scalar_atomic(
465 val: ScalarMaybeUninit<Tag>,
466 dest: MPlaceTy<'tcx, Tag>,
467 atomic: AtomicWriteOp,
468 ) -> InterpResult<'tcx> {
469 let this = self.eval_context_mut();
470 this.allow_data_races_mut(move |this| this.write_scalar(val, dest.into()))?;
471 self.validate_atomic_store(dest, atomic)
474 /// Perform a atomic operation on a memory location.
475 fn atomic_op_immediate(
477 place: MPlaceTy<'tcx, Tag>,
478 rhs: ImmTy<'tcx, Tag>,
482 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
483 let this = self.eval_context_mut();
485 let old = this.allow_data_races_mut(|this| this.read_immediate(place.into()))?;
487 // Atomics wrap around on overflow.
488 let val = this.binary_op(op, old, rhs)?;
489 let val = if neg { this.unary_op(mir::UnOp::Not, val)? } else { val };
490 this.allow_data_races_mut(|this| this.write_immediate(*val, place.into()))?;
492 this.validate_atomic_rmw(place, atomic)?;
496 /// Perform an atomic exchange with a memory place and a new
497 /// scalar value, the old value is returned.
498 fn atomic_exchange_scalar(
500 place: MPlaceTy<'tcx, Tag>,
501 new: ScalarMaybeUninit<Tag>,
503 ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
504 let this = self.eval_context_mut();
506 let old = this.allow_data_races_mut(|this| this.read_scalar(place.into()))?;
507 this.allow_data_races_mut(|this| this.write_scalar(new, place.into()))?;
508 this.validate_atomic_rmw(place, atomic)?;
512 /// Perform an atomic compare and exchange at a given memory location.
513 /// On success an atomic RMW operation is performed and on failure
514 /// only an atomic read occurs.
515 fn atomic_compare_exchange_scalar(
517 place: MPlaceTy<'tcx, Tag>,
518 expect_old: ImmTy<'tcx, Tag>,
519 new: ScalarMaybeUninit<Tag>,
522 ) -> InterpResult<'tcx, Immediate<Tag>> {
523 let this = self.eval_context_mut();
525 // Failure ordering cannot be stronger than success ordering, therefore first attempt
526 // to read with the failure ordering and if successfull then try again with the success
527 // read ordering and write in the success case.
528 // Read as immediate for the sake of `binary_op()`
529 let old = this.allow_data_races_mut(|this| this.read_immediate(place.into()))?;
531 // `binary_op` will bail if either of them is not a scalar.
532 let eq = this.overflowing_binary_op(mir::BinOp::Eq, old, expect_old)?.0;
533 let res = Immediate::ScalarPair(old.to_scalar_or_uninit(), eq.into());
535 // Update ptr depending on comparison.
536 // if successful, perform a full rw-atomic validation
537 // otherwise treat this as an atomic load with the fail ordering.
539 this.allow_data_races_mut(|this| this.write_scalar(new, place.into()))?;
540 this.validate_atomic_rmw(place, success)?;
542 this.validate_atomic_load(place, fail)?;
545 // Return the old value.
549 /// Update the data-race detector for an atomic read occuring at the
550 /// associated memory-place and on the current thread.
551 fn validate_atomic_load(
553 place: MPlaceTy<'tcx, Tag>,
554 atomic: AtomicReadOp,
555 ) -> InterpResult<'tcx> {
556 let this = self.eval_context_ref();
557 this.validate_atomic_op(
561 move |memory, clocks, index, atomic| {
562 if atomic == AtomicReadOp::Relaxed {
563 memory.load_relaxed(&mut *clocks, index)
565 memory.load_acquire(&mut *clocks, index)
571 /// Update the data-race detector for an atomic write occuring at the
572 /// associated memory-place and on the current thread.
573 fn validate_atomic_store(
575 place: MPlaceTy<'tcx, Tag>,
576 atomic: AtomicWriteOp,
577 ) -> InterpResult<'tcx> {
578 let this = self.eval_context_ref();
579 this.validate_atomic_op(
583 move |memory, clocks, index, atomic| {
584 if atomic == AtomicWriteOp::Relaxed {
585 memory.store_relaxed(clocks, index)
587 memory.store_release(clocks, index)
593 /// Update the data-race detector for an atomic read-modify-write occuring
594 /// at the associated memory place and on the current thread.
595 fn validate_atomic_rmw(
597 place: MPlaceTy<'tcx, Tag>,
599 ) -> InterpResult<'tcx> {
601 let acquire = matches!(atomic, Acquire | AcqRel | SeqCst);
602 let release = matches!(atomic, Release | AcqRel | SeqCst);
603 let this = self.eval_context_ref();
604 this.validate_atomic_op(place, atomic, "Atomic RMW", move |memory, clocks, index, _| {
606 memory.load_acquire(clocks, index)?;
608 memory.load_relaxed(clocks, index)?;
611 memory.rmw_release(clocks, index)
613 memory.rmw_relaxed(clocks, index)
618 /// Update the data-race detector for an atomic fence on the current thread.
619 fn validate_atomic_fence(&mut self, atomic: AtomicFenceOp) -> InterpResult<'tcx> {
620 let this = self.eval_context_mut();
621 if let Some(data_race) = &this.memory.extra.data_race {
622 data_race.maybe_perform_sync_operation(move |index, mut clocks| {
623 log::trace!("Atomic fence on {:?} with ordering {:?}", index, atomic);
625 // Apply data-race detection for the current fences
626 // this treats AcqRel and SeqCst as the same as a acquire
627 // and release fence applied in the same timestamp.
628 if atomic != AtomicFenceOp::Release {
629 // Either Acquire | AcqRel | SeqCst
630 clocks.apply_acquire_fence();
632 if atomic != AtomicFenceOp::Acquire {
633 // Either Release | AcqRel | SeqCst
634 clocks.apply_release_fence();
637 // Increment timestamp in case of release semantics.
638 Ok(atomic != AtomicFenceOp::Acquire)
646 /// Vector clock metadata for a logical memory allocation.
647 #[derive(Debug, Clone)]
648 pub struct VClockAlloc {
649 /// Assigning each byte a MemoryCellClocks.
650 alloc_ranges: RefCell<RangeMap<MemoryCellClocks>>,
652 // Pointer to global state.
657 /// Create a new data-race allocation detector.
658 pub fn new_allocation(global: &MemoryExtra, len: Size) -> VClockAlloc {
660 global: Rc::clone(global),
661 alloc_ranges: RefCell::new(RangeMap::new(len, MemoryCellClocks::default())),
665 // Find an index, if one exists where the value
666 // in `l` is greater than the value in `r`.
667 fn find_gt_index(l: &VClock, r: &VClock) -> Option<VectorIdx> {
668 let l_slice = l.as_slice();
669 let r_slice = r.as_slice();
674 .find_map(|(idx, (&l, &r))| if l > r { Some(idx) } else { None })
676 if l_slice.len() > r_slice.len() {
677 // By invariant, if l_slice is longer
678 // then one element must be larger.
679 // This just validates that this is true
680 // and reports earlier elements first.
681 let l_remainder_slice = &l_slice[r_slice.len()..];
682 let idx = l_remainder_slice
685 .find_map(|(idx, &r)| if r == 0 { None } else { Some(idx) })
686 .expect("Invalid VClock Invariant");
692 .map(|idx| VectorIdx::new(idx))
695 /// Report a data-race found in the program.
696 /// This finds the two racing threads and the type
697 /// of data-race that occured. This will also
698 /// return info about the memory location the data-race
702 fn report_data_race<'tcx>(
703 global: &MemoryExtra,
704 range: &MemoryCellClocks,
707 pointer: Pointer<Tag>,
709 ) -> InterpResult<'tcx> {
710 let (current_index, current_clocks) = global.current_thread_state();
712 let (other_action, other_thread, other_clock) = if range.write
713 > current_clocks.clock[range.write_index]
715 // Convert the write action into the vector clock it
716 // represents for diagnostic purposes.
717 write_clock = VClock::new_with_index(range.write_index, range.write);
718 ("WRITE", range.write_index, &write_clock)
719 } else if let Some(idx) = Self::find_gt_index(&range.read, ¤t_clocks.clock) {
720 ("READ", idx, &range.read)
721 } else if !is_atomic {
722 if let Some(atomic) = range.atomic() {
723 if let Some(idx) = Self::find_gt_index(&atomic.write_vector, ¤t_clocks.clock)
725 ("ATOMIC_STORE", idx, &atomic.write_vector)
726 } else if let Some(idx) =
727 Self::find_gt_index(&atomic.read_vector, ¤t_clocks.clock)
729 ("ATOMIC_LOAD", idx, &atomic.read_vector)
732 "Failed to report data-race for non-atomic operation: no race found"
737 "Failed to report data-race for non-atomic operation: no atomic component"
741 unreachable!("Failed to report data-race for atomic operation")
744 // Load elaborated thread information about the racing thread actions.
745 let current_thread_info = global.print_thread_metadata(current_index);
746 let other_thread_info = global.print_thread_metadata(other_thread);
748 // Throw the data-race detection.
750 "Data race detected between {} on {} and {} on {}, memory({:?},offset={},size={})\
751 \n\t\t -current vector clock = {:?}\
752 \n\t\t -conflicting timestamp = {:?}",
758 pointer.offset.bytes(),
760 current_clocks.clock,
765 /// Detect data-races for an unsychronized read operation, will not perform
766 /// data-race detection if `multi-threaded` is false, either due to no threads
767 /// being created or if it is temporarily disabled during a racy read or write
768 /// operation for which data-race detection is handled separately, for example
769 /// atomic read operations.
770 pub fn read<'tcx>(&self, pointer: Pointer<Tag>, len: Size) -> InterpResult<'tcx> {
771 if self.global.multi_threaded.get() {
772 let (index, clocks) = self.global.current_thread_state();
773 let mut alloc_ranges = self.alloc_ranges.borrow_mut();
774 for (_, range) in alloc_ranges.iter_mut(pointer.offset, len) {
775 if let Err(DataRace) = range.read_race_detect(&*clocks, index) {
777 return Self::report_data_race(
793 // Shared code for detecting data-races on unique access to a section of memory
794 fn unique_access<'tcx>(
796 pointer: Pointer<Tag>,
799 ) -> InterpResult<'tcx> {
800 if self.global.multi_threaded.get() {
801 let (index, clocks) = self.global.current_thread_state();
802 for (_, range) in self.alloc_ranges.get_mut().iter_mut(pointer.offset, len) {
803 if let Err(DataRace) = range.write_race_detect(&*clocks, index) {
805 return Self::report_data_race(
821 /// Detect data-races for an unsychronized write operation, will not perform
822 /// data-race threads if `multi-threaded` is false, either due to no threads
823 /// being created or if it is temporarily disabled during a racy read or write
825 pub fn write<'tcx>(&mut self, pointer: Pointer<Tag>, len: Size) -> InterpResult<'tcx> {
826 self.unique_access(pointer, len, "Write")
829 /// Detect data-races for an unsychronized deallocate operation, will not perform
830 /// data-race threads if `multi-threaded` is false, either due to no threads
831 /// being created or if it is temporarily disabled during a racy read or write
833 pub fn deallocate<'tcx>(&mut self, pointer: Pointer<Tag>, len: Size) -> InterpResult<'tcx> {
834 self.unique_access(pointer, len, "Deallocate")
838 impl<'mir, 'tcx: 'mir> EvalContextPrivExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {}
839 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: MiriEvalContextExt<'mir, 'tcx> {
840 // Temporarily allow data-races to occur, this should only be
841 // used if either one of the appropiate `validate_atomic` functions
842 // will be called to treat a memory access as atomic or if the memory
843 // being accessed should be treated as internal state, that cannot be
844 // accessed by the interpreted program.
846 fn allow_data_races_ref<R>(&self, op: impl FnOnce(&MiriEvalContext<'mir, 'tcx>) -> R) -> R {
847 let this = self.eval_context_ref();
848 let old = if let Some(data_race) = &this.memory.extra.data_race {
849 data_race.multi_threaded.replace(false)
853 let result = op(this);
854 if let Some(data_race) = &this.memory.extra.data_race {
855 data_race.multi_threaded.set(old);
860 /// Same as `allow_data_races_ref`, this temporarily disables any data-race detection and
861 /// so should only be used for atomic operations or internal state that the program cannot
864 fn allow_data_races_mut<R>(
866 op: impl FnOnce(&mut MiriEvalContext<'mir, 'tcx>) -> R,
868 let this = self.eval_context_mut();
869 let old = if let Some(data_race) = &this.memory.extra.data_race {
870 data_race.multi_threaded.replace(false)
874 let result = op(this);
875 if let Some(data_race) = &this.memory.extra.data_race {
876 data_race.multi_threaded.set(old);
881 /// Generic atomic operation implementation,
882 /// this accesses memory via get_raw instead of
883 /// get_raw_mut, due to issues calling get_raw_mut
884 /// for atomic loads from read-only memory.
885 /// FIXME: is this valid, or should get_raw_mut be used for
886 /// atomic-stores/atomic-rmw?
887 fn validate_atomic_op<A: Debug + Copy>(
889 place: MPlaceTy<'tcx, Tag>,
893 &mut MemoryCellClocks,
897 ) -> Result<(), DataRace>,
898 ) -> InterpResult<'tcx> {
899 let this = self.eval_context_ref();
900 if let Some(data_race) = &this.memory.extra.data_race {
901 if data_race.multi_threaded.get() {
902 // Load and log the atomic operation.
903 let place_ptr = place.ptr.assert_ptr();
904 let size = place.layout.size;
906 &this.memory.get_raw(place_ptr.alloc_id)?.extra.data_race.as_ref().unwrap();
908 "Atomic op({}) with ordering {:?} on memory({:?}, offset={}, size={})",
912 place_ptr.offset.bytes(),
916 // Perform the atomic operation.
917 let data_race = &alloc_meta.global;
918 data_race.maybe_perform_sync_operation(|index, mut clocks| {
920 alloc_meta.alloc_ranges.borrow_mut().iter_mut(place_ptr.offset, size)
922 if let Err(DataRace) = op(range, &mut *clocks, index, atomic) {
924 return VClockAlloc::report_data_race(
935 // This conservatively assumes all operations have release semantics
939 // Log changes to atomic memory.
940 if log::log_enabled!(log::Level::Trace) {
941 for (_, range) in alloc_meta.alloc_ranges.borrow().iter(place_ptr.offset, size)
944 "Updated atomic memory({:?}, offset={}, size={}) to {:#?}",
945 place.ptr.assert_ptr().alloc_id,
946 place_ptr.offset.bytes(),
958 /// Extra metadata associated with a thread.
959 #[derive(Debug, Clone, Default)]
960 struct ThreadExtraState {
961 /// The current vector index in use by the
962 /// thread currently, this is set to None
963 /// after the vector index has been re-used
964 /// and hence the value will never need to be
965 /// read during data-race reporting.
966 vector_index: Option<VectorIdx>,
968 /// The name of the thread, updated for better
969 /// diagnostics when reporting detected data
971 thread_name: Option<Box<str>>,
973 /// Thread termination vector clock, this
974 /// is set on thread termination and is used
975 /// for joining on threads since the vector_index
976 /// may be re-used when the join operation occurs.
977 termination_vector_clock: Option<VClock>,
980 /// Global data-race detection state, contains the currently
981 /// executing thread as well as the vector-clocks associated
982 /// with each of the threads.
983 #[derive(Debug, Clone)]
984 pub struct GlobalState {
985 /// Set to true once the first additional
986 /// thread has launched, due to the dependency
987 /// between before and after a thread launch.
988 /// Any data-races must be recorded after this
989 /// so concurrent execution can ignore recording
991 multi_threaded: Cell<bool>,
993 /// Mapping of a vector index to a known set of thread
994 /// clocks, this is not directly mapping from a thread id
995 /// since it may refer to multiple threads.
996 vector_clocks: RefCell<IndexVec<VectorIdx, ThreadClockSet>>,
998 /// Mapping of a given vector index to the current thread
999 /// that the execution is representing, this may change
1000 /// if a vector index is re-assigned to a new thread.
1001 vector_info: RefCell<IndexVec<VectorIdx, ThreadId>>,
1003 /// The mapping of a given thread to assocaited thread metadata.
1004 thread_info: RefCell<IndexVec<ThreadId, ThreadExtraState>>,
1006 /// The current vector index being executed.
1007 current_index: Cell<VectorIdx>,
1009 /// Potential vector indices that could be re-used on thread creation
1010 /// values are inserted here on after the thread has terminated and
1011 /// been joined with, and hence may potentially become free
1012 /// for use as the index for a new thread.
1013 /// Elements in this set may still require the vector index to
1014 /// report data-races, and can only be re-used after all
1015 /// active vector-clocks catch up with the threads timestamp.
1016 reuse_candidates: RefCell<FxHashSet<VectorIdx>>,
1018 /// Counts the number of threads that are currently active
1019 /// if the number of active threads reduces to 1 and then
1020 /// a join operation occures with the remaining main thread
1021 /// then multi-threaded execution may be disabled.
1022 active_thread_count: Cell<usize>,
1024 /// This contains threads that have terminated, but not yet joined
1025 /// and so cannot become re-use candidates until a join operation
1027 /// The associated vector index will be moved into re-use candidates
1028 /// after the join operation occurs.
1029 terminated_threads: RefCell<FxHashMap<ThreadId, VectorIdx>>,
1033 /// Create a new global state, setup with just thread-id=0
1034 /// advanced to timestamp = 1.
1035 pub fn new() -> Self {
1036 let global_state = GlobalState {
1037 multi_threaded: Cell::new(false),
1038 vector_clocks: RefCell::new(IndexVec::new()),
1039 vector_info: RefCell::new(IndexVec::new()),
1040 thread_info: RefCell::new(IndexVec::new()),
1041 current_index: Cell::new(VectorIdx::new(0)),
1042 active_thread_count: Cell::new(1),
1043 reuse_candidates: RefCell::new(FxHashSet::default()),
1044 terminated_threads: RefCell::new(FxHashMap::default()),
1047 // Setup the main-thread since it is not explicitly created:
1048 // uses vector index and thread-id 0, also the rust runtime gives
1049 // the main-thread a name of "main".
1050 let index = global_state.vector_clocks.borrow_mut().push(ThreadClockSet::default());
1051 global_state.vector_info.borrow_mut().push(ThreadId::new(0));
1052 global_state.thread_info.borrow_mut().push(ThreadExtraState {
1053 vector_index: Some(index),
1054 thread_name: Some("main".to_string().into_boxed_str()),
1055 termination_vector_clock: None,
1061 // Try to find vector index values that can potentially be re-used
1062 // by a new thread instead of a new vector index being created.
1063 fn find_vector_index_reuse_candidate(&self) -> Option<VectorIdx> {
1064 let mut reuse = self.reuse_candidates.borrow_mut();
1065 let vector_clocks = self.vector_clocks.borrow();
1066 let vector_info = self.vector_info.borrow();
1067 let terminated_threads = self.terminated_threads.borrow();
1068 for &candidate in reuse.iter() {
1069 let target_timestamp = vector_clocks[candidate].clock[candidate];
1070 if vector_clocks.iter_enumerated().all(|(clock_idx, clock)| {
1071 // The thread happens before the clock, and hence cannot report
1072 // a data-race with this the candidate index.
1073 let no_data_race = clock.clock[candidate] >= target_timestamp;
1075 // The vector represents a thread that has terminated and hence cannot
1076 // report a data-race with the candidate index.
1077 let thread_id = vector_info[clock_idx];
1078 let vector_terminated =
1079 reuse.contains(&clock_idx) || terminated_threads.contains_key(&thread_id);
1081 // The vector index cannot report a race with the candidate index
1082 // and hence allows the candidate index to be re-used.
1083 no_data_race || vector_terminated
1085 // All vector clocks for each vector index are equal to
1086 // the target timestamp, and the thread is known to have
1087 // terminated, therefore this vector clock index cannot
1088 // report any more data-races.
1089 assert!(reuse.remove(&candidate));
1090 return Some(candidate);
1096 // Hook for thread creation, enabled multi-threaded execution and marks
1097 // the current thread timestamp as happening-before the current thread.
1099 pub fn thread_created(&self, thread: ThreadId) {
1100 let current_index = self.current_index();
1102 // Increment the number of active threads.
1103 let active_threads = self.active_thread_count.get();
1104 self.active_thread_count.set(active_threads + 1);
1106 // Enable multi-threaded execution, there are now two threads
1107 // so data-races are now possible.
1108 self.multi_threaded.set(true);
1110 // Load and setup the associated thread metadata
1111 let mut thread_info = self.thread_info.borrow_mut();
1112 thread_info.ensure_contains_elem(thread, Default::default);
1114 // Assign a vector index for the thread, attempting to re-use an old
1115 // vector index that can no longer report any data-races if possible.
1116 let created_index = if let Some(reuse_index) = self.find_vector_index_reuse_candidate() {
1117 // Now re-configure the re-use candidate, increment the clock
1118 // for the new sync use of the vector.
1119 let mut vector_clocks = self.vector_clocks.borrow_mut();
1120 vector_clocks[reuse_index].increment_clock(reuse_index);
1122 // Locate the old thread the vector was associated with and update
1123 // it to represent the new thread instead.
1124 let mut vector_info = self.vector_info.borrow_mut();
1125 let old_thread = vector_info[reuse_index];
1126 vector_info[reuse_index] = thread;
1128 // Mark the thread the vector index was associated with as no longer
1129 // representing a thread index.
1130 thread_info[old_thread].vector_index = None;
1134 // No vector re-use candidates available, instead create
1135 // a new vector index.
1136 let mut vector_info = self.vector_info.borrow_mut();
1137 vector_info.push(thread)
1140 // Mark the chosen vector index as in use by the thread.
1141 thread_info[thread].vector_index = Some(created_index);
1143 // Create a thread clock set if applicable.
1144 let mut vector_clocks = self.vector_clocks.borrow_mut();
1145 if created_index == vector_clocks.next_index() {
1146 vector_clocks.push(ThreadClockSet::default());
1149 // Now load the two clocks and configure the initial state.
1150 let (current, created) = vector_clocks.pick2_mut(current_index, created_index);
1152 // Join the created with current, since the current threads
1153 // previous actions happen-before the created thread.
1154 created.join_with(current);
1156 // Advance both threads after the synchronized operation.
1157 // Both operations are considered to have release semantics.
1158 current.increment_clock(current_index);
1159 created.increment_clock(created_index);
1162 /// Hook on a thread join to update the implicit happens-before relation
1163 /// between the joined thead and the current thread.
1165 pub fn thread_joined(&self, current_thread: ThreadId, join_thread: ThreadId) {
1166 let mut clocks_vec = self.vector_clocks.borrow_mut();
1167 let thread_info = self.thread_info.borrow();
1169 // Load the vector clock of the current thread.
1170 let current_index = thread_info[current_thread]
1172 .expect("Performed thread join on thread with no assigned vector");
1173 let current = &mut clocks_vec[current_index];
1175 // Load the associated vector clock for the terminated thread.
1176 let join_clock = thread_info[join_thread]
1177 .termination_vector_clock
1179 .expect("Joined with thread but thread has not terminated");
1182 // The join thread happens-before the current thread
1183 // so update the current vector clock.
1184 // Is not a release operation so the clock is not incremented.
1185 current.clock.join(join_clock);
1187 // Check the number of active threads, if the value is 1
1188 // then test for potentially disabling multi-threaded execution.
1189 let active_threads = self.active_thread_count.get();
1190 if active_threads == 1 {
1191 // May potentially be able to disable multi-threaded execution.
1192 let current_clock = &clocks_vec[current_index];
1195 .all(|(idx, clocks)| clocks.clock[idx] <= current_clock.clock[idx])
1197 // The all thread termations happen-before the current clock
1198 // therefore no data-races can be reported until a new thread
1199 // is created, so disable multi-threaded execution.
1200 self.multi_threaded.set(false);
1204 // If the thread is marked as terminated but not joined
1205 // then move the thread to the re-use set.
1206 let mut termination = self.terminated_threads.borrow_mut();
1207 if let Some(index) = termination.remove(&join_thread) {
1208 let mut reuse = self.reuse_candidates.borrow_mut();
1209 reuse.insert(index);
1213 /// On thread termination, the vector-clock may re-used
1214 /// in the future once all remaining thread-clocks catch
1215 /// up with the time index of the terminated thread.
1216 /// This assiges thread termination with a unique index
1217 /// which will be used to join the thread
1218 /// This should be called strictly before any calls to
1219 /// `thread_joined`.
1221 pub fn thread_terminated(&self) {
1222 let current_index = self.current_index();
1224 // Increment the clock to a unique termination timestamp.
1225 let mut vector_clocks = self.vector_clocks.borrow_mut();
1226 let current_clocks = &mut vector_clocks[current_index];
1227 current_clocks.increment_clock(current_index);
1229 // Load the current thread id for the executing vector.
1230 let vector_info = self.vector_info.borrow();
1231 let current_thread = vector_info[current_index];
1233 // Load the current thread metadata, and move to a terminated
1234 // vector state. Setting up the vector clock all join operations
1236 let mut thread_info = self.thread_info.borrow_mut();
1237 let current = &mut thread_info[current_thread];
1238 current.termination_vector_clock = Some(current_clocks.clock.clone());
1240 // Add this thread as a candidate for re-use after a thread join
1242 let mut termination = self.terminated_threads.borrow_mut();
1243 termination.insert(current_thread, current_index);
1245 // Reduce the number of active threads, now that a thread has
1247 let mut active_threads = self.active_thread_count.get();
1248 active_threads -= 1;
1249 self.active_thread_count.set(active_threads);
1252 /// Hook for updating the local tracker of the currently
1253 /// enabled thread, should always be updated whenever
1254 /// `active_thread` in thread.rs is updated.
1256 pub fn thread_set_active(&self, thread: ThreadId) {
1257 let thread_info = self.thread_info.borrow();
1258 let vector_idx = thread_info[thread]
1260 .expect("Setting thread active with no assigned vector");
1261 self.current_index.set(vector_idx);
1264 /// Hook for updating the local tracker of the threads name
1265 /// this should always mirror the local value in thread.rs
1266 /// the thread name is used for improved diagnostics
1267 /// during a data-race.
1269 pub fn thread_set_name(&self, thread: ThreadId, name: String) {
1270 let name = name.into_boxed_str();
1271 let mut thread_info = self.thread_info.borrow_mut();
1272 thread_info[thread].thread_name = Some(name);
1275 /// Attempt to perform a synchronized operation, this
1276 /// will perform no operation if multi-threading is
1277 /// not currently enabled.
1278 /// Otherwise it will increment the clock for the current
1279 /// vector before and after the operation for data-race
1280 /// detection between any happens-before edges the
1281 /// operation may create.
1282 fn maybe_perform_sync_operation<'tcx>(
1284 op: impl FnOnce(VectorIdx, RefMut<'_, ThreadClockSet>) -> InterpResult<'tcx, bool>,
1285 ) -> InterpResult<'tcx> {
1286 if self.multi_threaded.get() {
1287 let (index, clocks) = self.current_thread_state_mut();
1288 if op(index, clocks)? {
1289 let (_, mut clocks) = self.current_thread_state_mut();
1290 clocks.increment_clock(index);
1296 /// Internal utility to identify a thread stored internally
1297 /// returns the id and the name for better diagnostics.
1298 fn print_thread_metadata(&self, vector: VectorIdx) -> String {
1299 let thread = self.vector_info.borrow()[vector];
1300 let thread_name = &self.thread_info.borrow()[thread].thread_name;
1301 if let Some(name) = thread_name {
1302 let name: &str = name;
1303 format!("Thread(id = {:?}, name = {:?})", thread.to_u32(), &*name)
1305 format!("Thread(id = {:?})", thread.to_u32())
1309 /// Acquire a lock, express that the previous call of
1310 /// `validate_lock_release` must happen before this.
1311 /// As this is an acquire operation, the thread timestamp is not
1313 pub fn validate_lock_acquire(&self, lock: &VClock, thread: ThreadId) {
1314 let (_, mut clocks) = self.load_thread_state_mut(thread);
1315 clocks.clock.join(&lock);
1318 /// Release a lock handle, express that this happens-before
1319 /// any subsequent calls to `validate_lock_acquire`.
1320 /// For normal locks this should be equivalent to `validate_lock_release_shared`
1321 /// since an acquire operation should have occured before, however
1322 /// for futex & cond-var operations this is not the case and this
1323 /// operation must be used.
1324 pub fn validate_lock_release(&self, lock: &mut VClock, thread: ThreadId) {
1325 let (index, mut clocks) = self.load_thread_state_mut(thread);
1326 lock.clone_from(&clocks.clock);
1327 clocks.increment_clock(index);
1330 /// Release a lock handle, express that this happens-before
1331 /// any subsequent calls to `validate_lock_acquire` as well
1332 /// as any previous calls to this function after any
1333 /// `validate_lock_release` calls.
1334 /// For normal locks this should be equivalent to `validate_lock_release`.
1335 /// This function only exists for joining over the set of concurrent readers
1336 /// in a read-write lock and should not be used for anything else.
1337 pub fn validate_lock_release_shared(&self, lock: &mut VClock, thread: ThreadId) {
1338 let (index, mut clocks) = self.load_thread_state_mut(thread);
1339 lock.join(&clocks.clock);
1340 clocks.increment_clock(index);
1343 /// Load the vector index used by the given thread as well as the set of vector clocks
1344 /// used by the thread.
1346 fn load_thread_state_mut(&self, thread: ThreadId) -> (VectorIdx, RefMut<'_, ThreadClockSet>) {
1347 let index = self.thread_info.borrow()[thread]
1349 .expect("Loading thread state for thread with no assigned vector");
1350 let ref_vector = self.vector_clocks.borrow_mut();
1351 let clocks = RefMut::map(ref_vector, |vec| &mut vec[index]);
1355 /// Load the current vector clock in use and the current set of thread clocks
1356 /// in use for the vector.
1358 fn current_thread_state(&self) -> (VectorIdx, Ref<'_, ThreadClockSet>) {
1359 let index = self.current_index();
1360 let ref_vector = self.vector_clocks.borrow();
1361 let clocks = Ref::map(ref_vector, |vec| &vec[index]);
1365 /// Load the current vector clock in use and the current set of thread clocks
1366 /// in use for the vector mutably for modification.
1368 fn current_thread_state_mut(&self) -> (VectorIdx, RefMut<'_, ThreadClockSet>) {
1369 let index = self.current_index();
1370 let ref_vector = self.vector_clocks.borrow_mut();
1371 let clocks = RefMut::map(ref_vector, |vec| &mut vec[index]);
1375 /// Return the current thread, should be the same
1376 /// as the data-race active thread.
1378 fn current_index(&self) -> VectorIdx {
1379 self.current_index.get()