]> git.lizzy.rs Git - rust.git/blob - src/concurrency/data_race.rs
Move buffered functions into their own ext trait
[rust.git] / src / concurrency / data_race.rs
1 //! Implementation of a data-race detector using Lamport Timestamps / Vector-clocks
2 //! based on the Dynamic 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.
6 //!
7 //! The implementation contains modifications to correctly model the changes to the memory model in C++20
8 //! regarding the weakening of release sequences: <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0982r1.html>.
9 //! Relaxed stores now unconditionally block all currently active release sequences and so per-thread tracking of release
10 //! sequences is not needed.
11 //!
12 //! The implementation also models races with memory allocation and deallocation via treating allocation and
13 //! deallocation as a type of write internally for detecting data-races.
14 //!
15 //! Weak memory orders are explored but not all weak behaviours are exhibited, so it can still miss data-races
16 //! but should not report false-positives
17 //!
18 //! Data-race definition from(<https://en.cppreference.com/w/cpp/language/memory_model#Threads_and_data_races>):
19 //! a data race occurs between two memory accesses if they are on different threads, at least one operation
20 //! is non-atomic, at least one operation is a write and neither access happens-before the other. Read the link
21 //! for full definition.
22 //!
23 //! This re-uses vector indexes for threads that are known to be unable to report data-races, this is valid
24 //! because it only re-uses vector indexes once all currently-active (not-terminated) threads have an internal
25 //! vector clock that happens-after the join operation of the candidate thread. Threads that have not been joined
26 //! on are not considered. Since the thread's vector clock will only increase and a data-race implies that
27 //! there is some index x where clock\[x\] > thread_clock, when this is true clock\[candidate-idx\] > thread_clock
28 //! can never hold and hence a data-race can never be reported in that vector index again.
29 //! This means that the thread-index can be safely re-used, starting on the next timestamp for the newly created
30 //! thread.
31 //!
32 //! The timestamps used in the data-race detector assign each sequence of non-atomic operations
33 //! followed by a single atomic or concurrent operation a single timestamp.
34 //! Write, Read, Write, ThreadJoin will be represented by a single timestamp value on a thread.
35 //! This is because extra increment operations between the operations in the sequence are not
36 //! required for accurate reporting of data-race values.
37 //!
38 //! As per the paper a threads timestamp is only incremented after a release operation is performed
39 //! so some atomic operations that only perform acquires do not increment the timestamp. Due to shared
40 //! code some atomic operations may increment the timestamp when not necessary but this has no effect
41 //! on the data-race detection code.
42 //!
43 //! FIXME:
44 //! currently we have our own local copy of the currently active thread index and names, this is due
45 //! in part to the inability to access the current location of threads.active_thread inside the AllocExtra
46 //! read, write and deallocate functions and should be cleaned up in the future.
47
48 use std::{
49     cell::{Cell, Ref, RefCell, RefMut},
50     fmt::Debug,
51     mem,
52 };
53
54 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
55 use rustc_index::vec::{Idx, IndexVec};
56 use rustc_middle::{mir, ty::layout::TyAndLayout};
57 use rustc_target::abi::Size;
58
59 use crate::*;
60
61 use super::weak_memory::EvalContextExt as _;
62
63 pub type AllocExtra = VClockAlloc;
64
65 /// Valid atomic read-write operations, alias of atomic::Ordering (not non-exhaustive).
66 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
67 pub enum AtomicRwOp {
68     Relaxed,
69     Acquire,
70     Release,
71     AcqRel,
72     SeqCst,
73 }
74
75 /// Valid atomic read operations, subset of atomic::Ordering.
76 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
77 pub enum AtomicReadOp {
78     Relaxed,
79     Acquire,
80     SeqCst,
81 }
82
83 /// Valid atomic write operations, subset of atomic::Ordering.
84 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
85 pub enum AtomicWriteOp {
86     Relaxed,
87     Release,
88     SeqCst,
89 }
90
91 /// Valid atomic fence operations, subset of atomic::Ordering.
92 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
93 pub enum AtomicFenceOp {
94     Acquire,
95     Release,
96     AcqRel,
97     SeqCst,
98 }
99
100 /// The current set of vector clocks describing the state
101 /// of a thread, contains the happens-before clock and
102 /// additional metadata to model atomic fence operations.
103 #[derive(Clone, Default, Debug)]
104 pub(super) struct ThreadClockSet {
105     /// The increasing clock representing timestamps
106     /// that happen-before this thread.
107     pub(super) clock: VClock,
108
109     /// The set of timestamps that will happen-before this
110     /// thread once it performs an acquire fence.
111     fence_acquire: VClock,
112
113     /// The last timestamp of happens-before relations that
114     /// have been released by this thread by a fence.
115     fence_release: VClock,
116
117     /// Timestamps of the last SC fence performed by each
118     /// thread, updated when this thread performs an SC fence
119     pub(super) fence_seqcst: VClock,
120
121     /// Timestamps of the last SC write performed by each
122     /// thread, updated when this thread performs an SC fence
123     pub(super) write_seqcst: VClock,
124
125     /// Timestamps of the last SC fence performed by each
126     /// thread, updated when this thread performs an SC read
127     pub(super) read_seqcst: VClock,
128 }
129
130 impl ThreadClockSet {
131     /// Apply the effects of a release fence to this
132     /// set of thread vector clocks.
133     #[inline]
134     fn apply_release_fence(&mut self) {
135         self.fence_release.clone_from(&self.clock);
136     }
137
138     /// Apply the effects of an acquire fence to this
139     /// set of thread vector clocks.
140     #[inline]
141     fn apply_acquire_fence(&mut self) {
142         self.clock.join(&self.fence_acquire);
143     }
144
145     /// Increment the happens-before clock at a
146     /// known index.
147     #[inline]
148     fn increment_clock(&mut self, index: VectorIdx) {
149         self.clock.increment_index(index);
150     }
151
152     /// Join the happens-before clock with that of
153     /// another thread, used to model thread join
154     /// operations.
155     fn join_with(&mut self, other: &ThreadClockSet) {
156         self.clock.join(&other.clock);
157     }
158 }
159
160 /// Error returned by finding a data race
161 /// should be elaborated upon.
162 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
163 pub struct DataRace;
164
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.
175     read_vector: VClock,
176
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,
182
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.
187     sync_vector: VClock,
188 }
189
190 /// Type of write operation: allocating memory
191 /// non-atomic writes and deallocating memory
192 /// are all treated as writes for the purpose
193 /// of the data-race detector.
194 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
195 enum WriteType {
196     /// Allocate memory.
197     Allocate,
198
199     /// Standard unsynchronized write.
200     Write,
201
202     /// Deallocate memory.
203     /// Note that when memory is deallocated first, later non-atomic accesses
204     /// will be reported as use-after-free, not as data races.
205     /// (Same for `Allocate` above.)
206     Deallocate,
207 }
208 impl WriteType {
209     fn get_descriptor(self) -> &'static str {
210         match self {
211             WriteType::Allocate => "Allocate",
212             WriteType::Write => "Write",
213             WriteType::Deallocate => "Deallocate",
214         }
215     }
216 }
217
218 /// Memory Cell vector clock metadata
219 /// for data-race detection.
220 #[derive(Clone, PartialEq, Eq, Debug)]
221 struct MemoryCellClocks {
222     /// The vector-clock timestamp of the last write
223     /// corresponding to the writing threads timestamp.
224     write: VTimestamp,
225
226     /// The identifier of the vector index, corresponding to a thread
227     /// that performed the last write operation.
228     write_index: VectorIdx,
229
230     /// The type of operation that the write index represents,
231     /// either newly allocated memory, a non-atomic write or
232     /// a deallocation of memory.
233     write_type: WriteType,
234
235     /// The vector-clock of the timestamp of the last read operation
236     /// performed by a thread since the last write operation occurred.
237     /// It is reset to zero on each write operation.
238     read: VClock,
239
240     /// Atomic acquire & release sequence tracking clocks.
241     /// For non-atomic memory in the common case this
242     /// value is set to None.
243     atomic_ops: Option<Box<AtomicMemoryCellClocks>>,
244 }
245
246 impl MemoryCellClocks {
247     /// Create a new set of clocks representing memory allocated
248     ///  at a given vector timestamp and index.
249     fn new(alloc: VTimestamp, alloc_index: VectorIdx) -> Self {
250         MemoryCellClocks {
251             read: VClock::default(),
252             write: alloc,
253             write_index: alloc_index,
254             write_type: WriteType::Allocate,
255             atomic_ops: None,
256         }
257     }
258
259     /// Load the internal atomic memory cells if they exist.
260     #[inline]
261     fn atomic(&self) -> Option<&AtomicMemoryCellClocks> {
262         match &self.atomic_ops {
263             Some(op) => Some(&*op),
264             None => None,
265         }
266     }
267
268     /// Load or create the internal atomic memory metadata
269     /// if it does not exist.
270     #[inline]
271     fn atomic_mut(&mut self) -> &mut AtomicMemoryCellClocks {
272         self.atomic_ops.get_or_insert_with(Default::default)
273     }
274
275     /// Update memory cell data-race tracking for atomic
276     /// load acquire semantics, is a no-op if this memory was
277     /// not used previously as atomic memory.
278     fn load_acquire(
279         &mut self,
280         clocks: &mut ThreadClockSet,
281         index: VectorIdx,
282     ) -> Result<(), DataRace> {
283         self.atomic_read_detect(clocks, index)?;
284         if let Some(atomic) = self.atomic() {
285             clocks.clock.join(&atomic.sync_vector);
286         }
287         Ok(())
288     }
289
290     /// Update memory cell data-race tracking for atomic
291     /// load relaxed semantics, is a no-op if this memory was
292     /// not used previously as atomic memory.
293     fn load_relaxed(
294         &mut self,
295         clocks: &mut ThreadClockSet,
296         index: VectorIdx,
297     ) -> Result<(), DataRace> {
298         self.atomic_read_detect(clocks, index)?;
299         if let Some(atomic) = self.atomic() {
300             clocks.fence_acquire.join(&atomic.sync_vector);
301         }
302         Ok(())
303     }
304
305     /// Update the memory cell data-race tracking for atomic
306     /// store release semantics.
307     fn store_release(&mut self, clocks: &ThreadClockSet, index: VectorIdx) -> Result<(), DataRace> {
308         self.atomic_write_detect(clocks, index)?;
309         let atomic = self.atomic_mut();
310         atomic.sync_vector.clone_from(&clocks.clock);
311         Ok(())
312     }
313
314     /// Update the memory cell data-race tracking for atomic
315     /// store relaxed semantics.
316     fn store_relaxed(&mut self, clocks: &ThreadClockSet, index: VectorIdx) -> Result<(), DataRace> {
317         self.atomic_write_detect(clocks, index)?;
318
319         // The handling of release sequences was changed in C++20 and so
320         // the code here is different to the paper since now all relaxed
321         // stores block release sequences. The exception for same-thread
322         // relaxed stores has been removed.
323         let atomic = self.atomic_mut();
324         atomic.sync_vector.clone_from(&clocks.fence_release);
325         Ok(())
326     }
327
328     /// Update the memory cell data-race tracking for atomic
329     /// store release semantics for RMW operations.
330     fn rmw_release(&mut self, clocks: &ThreadClockSet, index: VectorIdx) -> Result<(), DataRace> {
331         self.atomic_write_detect(clocks, index)?;
332         let atomic = self.atomic_mut();
333         atomic.sync_vector.join(&clocks.clock);
334         Ok(())
335     }
336
337     /// Update the memory cell data-race tracking for atomic
338     /// store relaxed semantics for RMW operations.
339     fn rmw_relaxed(&mut self, clocks: &ThreadClockSet, index: VectorIdx) -> Result<(), DataRace> {
340         self.atomic_write_detect(clocks, index)?;
341         let atomic = self.atomic_mut();
342         atomic.sync_vector.join(&clocks.fence_release);
343         Ok(())
344     }
345
346     /// Detect data-races with an atomic read, caused by a non-atomic write that does
347     /// not happen-before the atomic-read.
348     fn atomic_read_detect(
349         &mut self,
350         clocks: &ThreadClockSet,
351         index: VectorIdx,
352     ) -> Result<(), DataRace> {
353         log::trace!("Atomic read with vectors: {:#?} :: {:#?}", self, clocks);
354         if self.write <= clocks.clock[self.write_index] {
355             let atomic = self.atomic_mut();
356             atomic.read_vector.set_at_index(&clocks.clock, index);
357             Ok(())
358         } else {
359             Err(DataRace)
360         }
361     }
362
363     /// Detect data-races with an atomic write, either with a non-atomic read or with
364     /// a non-atomic write.
365     fn atomic_write_detect(
366         &mut self,
367         clocks: &ThreadClockSet,
368         index: VectorIdx,
369     ) -> Result<(), DataRace> {
370         log::trace!("Atomic write with vectors: {:#?} :: {:#?}", self, clocks);
371         if self.write <= clocks.clock[self.write_index] && self.read <= clocks.clock {
372             let atomic = self.atomic_mut();
373             atomic.write_vector.set_at_index(&clocks.clock, index);
374             Ok(())
375         } else {
376             Err(DataRace)
377         }
378     }
379
380     /// Detect races for non-atomic read operations at the current memory cell
381     /// returns true if a data-race is detected.
382     fn read_race_detect(
383         &mut self,
384         clocks: &ThreadClockSet,
385         index: VectorIdx,
386     ) -> Result<(), DataRace> {
387         log::trace!("Unsynchronized read with vectors: {:#?} :: {:#?}", self, clocks);
388         if self.write <= clocks.clock[self.write_index] {
389             let race_free = if let Some(atomic) = self.atomic() {
390                 atomic.write_vector <= clocks.clock
391             } else {
392                 true
393             };
394             if race_free {
395                 self.read.set_at_index(&clocks.clock, index);
396                 Ok(())
397             } else {
398                 Err(DataRace)
399             }
400         } else {
401             Err(DataRace)
402         }
403     }
404
405     /// Detect races for non-atomic write operations at the current memory cell
406     /// returns true if a data-race is detected.
407     fn write_race_detect(
408         &mut self,
409         clocks: &ThreadClockSet,
410         index: VectorIdx,
411         write_type: WriteType,
412     ) -> Result<(), DataRace> {
413         log::trace!("Unsynchronized write with vectors: {:#?} :: {:#?}", self, clocks);
414         if self.write <= clocks.clock[self.write_index] && self.read <= clocks.clock {
415             let race_free = if let Some(atomic) = self.atomic() {
416                 atomic.write_vector <= clocks.clock && atomic.read_vector <= clocks.clock
417             } else {
418                 true
419             };
420             if race_free {
421                 self.write = clocks.clock[index];
422                 self.write_index = index;
423                 self.write_type = write_type;
424                 self.read.set_zero_vector();
425                 Ok(())
426             } else {
427                 Err(DataRace)
428             }
429         } else {
430             Err(DataRace)
431         }
432     }
433 }
434
435 /// Evaluation context extensions.
436 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {}
437 pub trait EvalContextExt<'mir, 'tcx: 'mir>: MiriEvalContextExt<'mir, 'tcx> {
438     /// Temporarily allow data-races to occur. This should only be used in
439     /// one of these cases:
440     /// - One of the appropriate `validate_atomic` functions will be called to
441     /// to treat a memory access as atomic.
442     /// - The memory being accessed should be treated as internal state, that
443     /// cannot be accessed by the interpreted program.
444     /// - Execution of the interpreted program execution has halted.
445     #[inline]
446     fn allow_data_races_ref<R>(&self, op: impl FnOnce(&MiriEvalContext<'mir, 'tcx>) -> R) -> R {
447         let this = self.eval_context_ref();
448         let old = if let Some(data_race) = &this.machine.data_race {
449             data_race.multi_threaded.replace(false)
450         } else {
451             false
452         };
453         let result = op(this);
454         if let Some(data_race) = &this.machine.data_race {
455             data_race.multi_threaded.set(old);
456         }
457         result
458     }
459
460     /// Same as `allow_data_races_ref`, this temporarily disables any data-race detection and
461     /// so should only be used for atomic operations or internal state that the program cannot
462     /// access.
463     #[inline]
464     fn allow_data_races_mut<R>(
465         &mut self,
466         op: impl FnOnce(&mut MiriEvalContext<'mir, 'tcx>) -> R,
467     ) -> R {
468         let this = self.eval_context_mut();
469         let old = if let Some(data_race) = &this.machine.data_race {
470             data_race.multi_threaded.replace(false)
471         } else {
472             false
473         };
474         let result = op(this);
475         if let Some(data_race) = &this.machine.data_race {
476             data_race.multi_threaded.set(old);
477         }
478         result
479     }
480
481     /// Atomic variant of read_scalar_at_offset.
482     fn read_scalar_at_offset_atomic(
483         &self,
484         op: &OpTy<'tcx, Tag>,
485         offset: u64,
486         layout: TyAndLayout<'tcx>,
487         atomic: AtomicReadOp,
488     ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
489         let this = self.eval_context_ref();
490         let value_place = this.deref_operand_and_offset(op, offset, layout)?;
491         this.read_scalar_atomic(&value_place, atomic)
492     }
493
494     /// Atomic variant of write_scalar_at_offset.
495     fn write_scalar_at_offset_atomic(
496         &mut self,
497         op: &OpTy<'tcx, Tag>,
498         offset: u64,
499         value: impl Into<ScalarMaybeUninit<Tag>>,
500         layout: TyAndLayout<'tcx>,
501         atomic: AtomicWriteOp,
502     ) -> InterpResult<'tcx> {
503         let this = self.eval_context_mut();
504         let value_place = this.deref_operand_and_offset(op, offset, layout)?;
505         this.write_scalar_atomic(value.into(), &value_place, atomic)
506     }
507
508     /// Perform an atomic read operation at the memory location.
509     fn read_scalar_atomic(
510         &self,
511         place: &MPlaceTy<'tcx, Tag>,
512         atomic: AtomicReadOp,
513     ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
514         let this = self.eval_context_ref();
515         // This will read from the last store in the modification order of this location. In case
516         // weak memory emulation is enabled, this may not be the store we will pick to actually read from and return.
517         // This is fine with StackedBorrow and race checks because they don't concern metadata on
518         // the *value* (including the associated provenance if this is an AtomicPtr) at this location.
519         // Only metadata on the location itself is used.
520         let scalar = this.allow_data_races_ref(move |this| this.read_scalar(&place.into()))?;
521         this.buffered_atomic_read(place, atomic, scalar, || {
522             this.validate_atomic_load(place, atomic)
523         })
524     }
525
526     /// Perform an atomic write operation at the memory location.
527     fn write_scalar_atomic(
528         &mut self,
529         val: ScalarMaybeUninit<Tag>,
530         dest: &MPlaceTy<'tcx, Tag>,
531         atomic: AtomicWriteOp,
532     ) -> InterpResult<'tcx> {
533         let this = self.eval_context_mut();
534         this.allow_data_races_mut(move |this| this.write_scalar(val, &(*dest).into()))?;
535         this.validate_atomic_store(dest, atomic)?;
536         this.buffered_atomic_write(val, dest, atomic)
537     }
538
539     /// Perform an atomic operation on a memory location.
540     fn atomic_op_immediate(
541         &mut self,
542         place: &MPlaceTy<'tcx, Tag>,
543         rhs: &ImmTy<'tcx, Tag>,
544         op: mir::BinOp,
545         neg: bool,
546         atomic: AtomicRwOp,
547     ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
548         let this = self.eval_context_mut();
549
550         let old = this.allow_data_races_mut(|this| this.read_immediate(&place.into()))?;
551
552         // Atomics wrap around on overflow.
553         let val = this.binary_op(op, &old, rhs)?;
554         let val = if neg { this.unary_op(mir::UnOp::Not, &val)? } else { val };
555         this.allow_data_races_mut(|this| this.write_immediate(*val, &(*place).into()))?;
556
557         this.validate_atomic_rmw(place, atomic)?;
558
559         this.buffered_atomic_rmw(val.to_scalar_or_uninit(), place, atomic)?;
560         Ok(old)
561     }
562
563     /// Perform an atomic exchange with a memory place and a new
564     /// scalar value, the old value is returned.
565     fn atomic_exchange_scalar(
566         &mut self,
567         place: &MPlaceTy<'tcx, Tag>,
568         new: ScalarMaybeUninit<Tag>,
569         atomic: AtomicRwOp,
570     ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
571         let this = self.eval_context_mut();
572
573         let old = this.allow_data_races_mut(|this| this.read_scalar(&place.into()))?;
574         this.allow_data_races_mut(|this| this.write_scalar(new, &(*place).into()))?;
575
576         this.validate_atomic_rmw(place, atomic)?;
577
578         this.buffered_atomic_rmw(new, place, atomic)?;
579         Ok(old)
580     }
581
582     /// Perform an conditional atomic exchange with a memory place and a new
583     /// scalar value, the old value is returned.
584     fn atomic_min_max_scalar(
585         &mut self,
586         place: &MPlaceTy<'tcx, Tag>,
587         rhs: ImmTy<'tcx, Tag>,
588         min: bool,
589         atomic: AtomicRwOp,
590     ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
591         let this = self.eval_context_mut();
592
593         let old = this.allow_data_races_mut(|this| this.read_immediate(&place.into()))?;
594         let lt = this.binary_op(mir::BinOp::Lt, &old, &rhs)?.to_scalar()?.to_bool()?;
595
596         let new_val = if min {
597             if lt { &old } else { &rhs }
598         } else {
599             if lt { &rhs } else { &old }
600         };
601
602         this.allow_data_races_mut(|this| this.write_immediate(**new_val, &(*place).into()))?;
603
604         this.validate_atomic_rmw(place, atomic)?;
605
606         this.buffered_atomic_rmw(new_val.to_scalar_or_uninit(), place, atomic)?;
607
608         // Return the old value.
609         Ok(old)
610     }
611
612     /// Perform an atomic compare and exchange at a given memory location.
613     /// On success an atomic RMW operation is performed and on failure
614     /// only an atomic read occurs. If `can_fail_spuriously` is true,
615     /// then we treat it as a "compare_exchange_weak" operation, and
616     /// some portion of the time fail even when the values are actually
617     /// identical.
618     fn atomic_compare_exchange_scalar(
619         &mut self,
620         place: &MPlaceTy<'tcx, Tag>,
621         expect_old: &ImmTy<'tcx, Tag>,
622         new: ScalarMaybeUninit<Tag>,
623         success: AtomicRwOp,
624         fail: AtomicReadOp,
625         can_fail_spuriously: bool,
626     ) -> InterpResult<'tcx, Immediate<Tag>> {
627         use rand::Rng as _;
628         let this = self.eval_context_mut();
629
630         // Failure ordering cannot be stronger than success ordering, therefore first attempt
631         // to read with the failure ordering and if successful then try again with the success
632         // read ordering and write in the success case.
633         // Read as immediate for the sake of `binary_op()`
634         let old = this.allow_data_races_mut(|this| this.read_immediate(&(place.into())))?;
635         // `binary_op` will bail if either of them is not a scalar.
636         let eq = this.binary_op(mir::BinOp::Eq, &old, expect_old)?;
637         // If the operation would succeed, but is "weak", fail some portion
638         // of the time, based on `success_rate`.
639         let success_rate = 1.0 - this.machine.cmpxchg_weak_failure_rate;
640         let cmpxchg_success = eq.to_scalar()?.to_bool()?
641             && if can_fail_spuriously {
642                 this.machine.rng.get_mut().gen_bool(success_rate)
643             } else {
644                 true
645             };
646         let res = Immediate::ScalarPair(
647             old.to_scalar_or_uninit(),
648             Scalar::from_bool(cmpxchg_success).into(),
649         );
650
651         // Update ptr depending on comparison.
652         // if successful, perform a full rw-atomic validation
653         // otherwise treat this as an atomic load with the fail ordering.
654         if cmpxchg_success {
655             this.allow_data_races_mut(|this| this.write_scalar(new, &(*place).into()))?;
656             this.validate_atomic_rmw(place, success)?;
657             this.buffered_atomic_rmw(new, place, success)?;
658         } else {
659             this.validate_atomic_load(place, fail)?;
660             // A failed compare exchange is equivalent to a load, reading from the latest store
661             // in the modification order.
662             // Since `old` is only a value and not the store element, we need to separately
663             // find it in our store buffer and perform load_impl on it.
664             this.perform_read_on_buffered_latest(place, fail)?;
665         }
666
667         // Return the old value.
668         Ok(res)
669     }
670
671     /// Update the data-race detector for an atomic read occurring at the
672     /// associated memory-place and on the current thread.
673     fn validate_atomic_load(
674         &self,
675         place: &MPlaceTy<'tcx, Tag>,
676         atomic: AtomicReadOp,
677     ) -> InterpResult<'tcx> {
678         let this = self.eval_context_ref();
679         this.validate_atomic_op(
680             place,
681             atomic,
682             "Atomic Load",
683             move |memory, clocks, index, atomic| {
684                 if atomic == AtomicReadOp::Relaxed {
685                     memory.load_relaxed(&mut *clocks, index)
686                 } else {
687                     memory.load_acquire(&mut *clocks, index)
688                 }
689             },
690         )
691     }
692
693     /// Update the data-race detector for an atomic write occurring at the
694     /// associated memory-place and on the current thread.
695     fn validate_atomic_store(
696         &mut self,
697         place: &MPlaceTy<'tcx, Tag>,
698         atomic: AtomicWriteOp,
699     ) -> InterpResult<'tcx> {
700         let this = self.eval_context_mut();
701         this.validate_atomic_op(
702             place,
703             atomic,
704             "Atomic Store",
705             move |memory, clocks, index, atomic| {
706                 if atomic == AtomicWriteOp::Relaxed {
707                     memory.store_relaxed(clocks, index)
708                 } else {
709                     memory.store_release(clocks, index)
710                 }
711             },
712         )
713     }
714
715     /// Update the data-race detector for an atomic read-modify-write occurring
716     /// at the associated memory place and on the current thread.
717     fn validate_atomic_rmw(
718         &mut self,
719         place: &MPlaceTy<'tcx, Tag>,
720         atomic: AtomicRwOp,
721     ) -> InterpResult<'tcx> {
722         use AtomicRwOp::*;
723         let acquire = matches!(atomic, Acquire | AcqRel | SeqCst);
724         let release = matches!(atomic, Release | AcqRel | SeqCst);
725         let this = self.eval_context_mut();
726         this.validate_atomic_op(place, atomic, "Atomic RMW", move |memory, clocks, index, _| {
727             if acquire {
728                 memory.load_acquire(clocks, index)?;
729             } else {
730                 memory.load_relaxed(clocks, index)?;
731             }
732             if release {
733                 memory.rmw_release(clocks, index)
734             } else {
735                 memory.rmw_relaxed(clocks, index)
736             }
737         })
738     }
739
740     /// Update the data-race detector for an atomic fence on the current thread.
741     fn validate_atomic_fence(&mut self, atomic: AtomicFenceOp) -> InterpResult<'tcx> {
742         let this = self.eval_context_mut();
743         if let Some(data_race) = &mut this.machine.data_race {
744             data_race.maybe_perform_sync_operation(|index, mut clocks| {
745                 log::trace!("Atomic fence on {:?} with ordering {:?}", index, atomic);
746
747                 // Apply data-race detection for the current fences
748                 // this treats AcqRel and SeqCst as the same as an acquire
749                 // and release fence applied in the same timestamp.
750                 if atomic != AtomicFenceOp::Release {
751                     // Either Acquire | AcqRel | SeqCst
752                     clocks.apply_acquire_fence();
753                 }
754                 if atomic != AtomicFenceOp::Acquire {
755                     // Either Release | AcqRel | SeqCst
756                     clocks.apply_release_fence();
757                 }
758                 if atomic == AtomicFenceOp::SeqCst {
759                     data_race.last_sc_fence.borrow_mut().set_at_index(&clocks.clock, index);
760                     clocks.fence_seqcst.join(&data_race.last_sc_fence.borrow());
761                     clocks.write_seqcst.join(&data_race.last_sc_write.borrow());
762                 }
763
764                 // Increment timestamp in case of release semantics.
765                 Ok(atomic != AtomicFenceOp::Acquire)
766             })
767         } else {
768             Ok(())
769         }
770     }
771 }
772
773 /// Vector clock metadata for a logical memory allocation.
774 #[derive(Debug, Clone)]
775 pub struct VClockAlloc {
776     /// Assigning each byte a MemoryCellClocks.
777     alloc_ranges: RefCell<RangeMap<MemoryCellClocks>>,
778 }
779
780 impl VClockAlloc {
781     /// Create a new data-race detector for newly allocated memory.
782     pub fn new_allocation(
783         global: &GlobalState,
784         len: Size,
785         kind: MemoryKind<MiriMemoryKind>,
786     ) -> VClockAlloc {
787         let (alloc_timestamp, alloc_index) = match kind {
788             // User allocated and stack memory should track allocation.
789             MemoryKind::Machine(
790                 MiriMemoryKind::Rust | MiriMemoryKind::C | MiriMemoryKind::WinHeap,
791             )
792             | MemoryKind::Stack => {
793                 let (alloc_index, clocks) = global.current_thread_state();
794                 let alloc_timestamp = clocks.clock[alloc_index];
795                 (alloc_timestamp, alloc_index)
796             }
797             // Other global memory should trace races but be allocated at the 0 timestamp.
798             MemoryKind::Machine(
799                 MiriMemoryKind::Global
800                 | MiriMemoryKind::Machine
801                 | MiriMemoryKind::Runtime
802                 | MiriMemoryKind::ExternStatic
803                 | MiriMemoryKind::Tls,
804             )
805             | MemoryKind::CallerLocation => (0, VectorIdx::MAX_INDEX),
806         };
807         VClockAlloc {
808             alloc_ranges: RefCell::new(RangeMap::new(
809                 len,
810                 MemoryCellClocks::new(alloc_timestamp, alloc_index),
811             )),
812         }
813     }
814
815     // Find an index, if one exists where the value
816     // in `l` is greater than the value in `r`.
817     fn find_gt_index(l: &VClock, r: &VClock) -> Option<VectorIdx> {
818         log::trace!("Find index where not {:?} <= {:?}", l, r);
819         let l_slice = l.as_slice();
820         let r_slice = r.as_slice();
821         l_slice
822             .iter()
823             .zip(r_slice.iter())
824             .enumerate()
825             .find_map(|(idx, (&l, &r))| if l > r { Some(idx) } else { None })
826             .or_else(|| {
827                 if l_slice.len() > r_slice.len() {
828                     // By invariant, if l_slice is longer
829                     // then one element must be larger.
830                     // This just validates that this is true
831                     // and reports earlier elements first.
832                     let l_remainder_slice = &l_slice[r_slice.len()..];
833                     let idx = l_remainder_slice
834                         .iter()
835                         .enumerate()
836                         .find_map(|(idx, &r)| if r == 0 { None } else { Some(idx) })
837                         .expect("Invalid VClock Invariant");
838                     Some(idx + r_slice.len())
839                 } else {
840                     None
841                 }
842             })
843             .map(VectorIdx::new)
844     }
845
846     /// Report a data-race found in the program.
847     /// This finds the two racing threads and the type
848     /// of data-race that occurred. This will also
849     /// return info about the memory location the data-race
850     /// occurred in.
851     #[cold]
852     #[inline(never)]
853     fn report_data_race<'tcx>(
854         global: &GlobalState,
855         range: &MemoryCellClocks,
856         action: &str,
857         is_atomic: bool,
858         ptr_dbg: Pointer<AllocId>,
859     ) -> InterpResult<'tcx> {
860         let (current_index, current_clocks) = global.current_thread_state();
861         let write_clock;
862         let (other_action, other_thread, other_clock) = if range.write
863             > current_clocks.clock[range.write_index]
864         {
865             // Convert the write action into the vector clock it
866             // represents for diagnostic purposes.
867             write_clock = VClock::new_with_index(range.write_index, range.write);
868             (range.write_type.get_descriptor(), range.write_index, &write_clock)
869         } else if let Some(idx) = Self::find_gt_index(&range.read, &current_clocks.clock) {
870             ("Read", idx, &range.read)
871         } else if !is_atomic {
872             if let Some(atomic) = range.atomic() {
873                 if let Some(idx) = Self::find_gt_index(&atomic.write_vector, &current_clocks.clock)
874                 {
875                     ("Atomic Store", idx, &atomic.write_vector)
876                 } else if let Some(idx) =
877                     Self::find_gt_index(&atomic.read_vector, &current_clocks.clock)
878                 {
879                     ("Atomic Load", idx, &atomic.read_vector)
880                 } else {
881                     unreachable!(
882                         "Failed to report data-race for non-atomic operation: no race found"
883                     )
884                 }
885             } else {
886                 unreachable!(
887                     "Failed to report data-race for non-atomic operation: no atomic component"
888                 )
889             }
890         } else {
891             unreachable!("Failed to report data-race for atomic operation")
892         };
893
894         // Load elaborated thread information about the racing thread actions.
895         let current_thread_info = global.print_thread_metadata(current_index);
896         let other_thread_info = global.print_thread_metadata(other_thread);
897
898         // Throw the data-race detection.
899         throw_ub_format!(
900             "Data race detected between {} on {} and {} on {} at {:?} (current vector clock = {:?}, conflicting timestamp = {:?})",
901             action,
902             current_thread_info,
903             other_action,
904             other_thread_info,
905             ptr_dbg,
906             current_clocks.clock,
907             other_clock
908         )
909     }
910
911     /// Detect data-races for an unsynchronized read operation, will not perform
912     /// data-race detection if `multi-threaded` is false, either due to no threads
913     /// being created or if it is temporarily disabled during a racy read or write
914     /// operation for which data-race detection is handled separately, for example
915     /// atomic read operations.
916     pub fn read<'tcx>(
917         &self,
918         alloc_id: AllocId,
919         range: AllocRange,
920         global: &GlobalState,
921     ) -> InterpResult<'tcx> {
922         if global.multi_threaded.get() {
923             let (index, clocks) = global.current_thread_state();
924             let mut alloc_ranges = self.alloc_ranges.borrow_mut();
925             for (offset, range) in alloc_ranges.iter_mut(range.start, range.size) {
926                 if let Err(DataRace) = range.read_race_detect(&*clocks, index) {
927                     // Report data-race.
928                     return Self::report_data_race(
929                         global,
930                         range,
931                         "Read",
932                         false,
933                         Pointer::new(alloc_id, offset),
934                     );
935                 }
936             }
937             Ok(())
938         } else {
939             Ok(())
940         }
941     }
942
943     // Shared code for detecting data-races on unique access to a section of memory
944     fn unique_access<'tcx>(
945         &mut self,
946         alloc_id: AllocId,
947         range: AllocRange,
948         write_type: WriteType,
949         global: &mut GlobalState,
950     ) -> InterpResult<'tcx> {
951         if global.multi_threaded.get() {
952             let (index, clocks) = global.current_thread_state();
953             for (offset, range) in self.alloc_ranges.get_mut().iter_mut(range.start, range.size) {
954                 if let Err(DataRace) = range.write_race_detect(&*clocks, index, write_type) {
955                     // Report data-race
956                     return Self::report_data_race(
957                         global,
958                         range,
959                         write_type.get_descriptor(),
960                         false,
961                         Pointer::new(alloc_id, offset),
962                     );
963                 }
964             }
965             Ok(())
966         } else {
967             Ok(())
968         }
969     }
970
971     /// Detect data-races for an unsynchronized write operation, will not perform
972     /// data-race threads if `multi-threaded` is false, either due to no threads
973     /// being created or if it is temporarily disabled during a racy read or write
974     /// operation
975     pub fn write<'tcx>(
976         &mut self,
977         alloc_id: AllocId,
978         range: AllocRange,
979         global: &mut GlobalState,
980     ) -> InterpResult<'tcx> {
981         self.unique_access(alloc_id, range, WriteType::Write, global)
982     }
983
984     /// Detect data-races for an unsynchronized deallocate operation, will not perform
985     /// data-race threads if `multi-threaded` is false, either due to no threads
986     /// being created or if it is temporarily disabled during a racy read or write
987     /// operation
988     pub fn deallocate<'tcx>(
989         &mut self,
990         alloc_id: AllocId,
991         range: AllocRange,
992         global: &mut GlobalState,
993     ) -> InterpResult<'tcx> {
994         self.unique_access(alloc_id, range, WriteType::Deallocate, global)
995     }
996 }
997
998 impl<'mir, 'tcx: 'mir> EvalContextPrivExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {}
999 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: MiriEvalContextExt<'mir, 'tcx> {
1000     /// Generic atomic operation implementation
1001     fn validate_atomic_op<A: Debug + Copy>(
1002         &self,
1003         place: &MPlaceTy<'tcx, Tag>,
1004         atomic: A,
1005         description: &str,
1006         mut op: impl FnMut(
1007             &mut MemoryCellClocks,
1008             &mut ThreadClockSet,
1009             VectorIdx,
1010             A,
1011         ) -> Result<(), DataRace>,
1012     ) -> InterpResult<'tcx> {
1013         let this = self.eval_context_ref();
1014         if let Some(data_race) = &this.machine.data_race {
1015             if data_race.multi_threaded.get() {
1016                 let size = place.layout.size;
1017                 let (alloc_id, base_offset, _tag) = this.ptr_get_alloc_id(place.ptr)?;
1018                 // Load and log the atomic operation.
1019                 // Note that atomic loads are possible even from read-only allocations, so `get_alloc_extra_mut` is not an option.
1020                 let alloc_meta = &this.get_alloc_extra(alloc_id)?.data_race.as_ref().unwrap();
1021                 log::trace!(
1022                     "Atomic op({}) with ordering {:?} on {:?} (size={})",
1023                     description,
1024                     &atomic,
1025                     place.ptr,
1026                     size.bytes()
1027                 );
1028
1029                 // Perform the atomic operation.
1030                 data_race.maybe_perform_sync_operation(|index, mut clocks| {
1031                     for (offset, range) in
1032                         alloc_meta.alloc_ranges.borrow_mut().iter_mut(base_offset, size)
1033                     {
1034                         if let Err(DataRace) = op(range, &mut *clocks, index, atomic) {
1035                             mem::drop(clocks);
1036                             return VClockAlloc::report_data_race(
1037                                 data_race,
1038                                 range,
1039                                 description,
1040                                 true,
1041                                 Pointer::new(alloc_id, offset),
1042                             )
1043                             .map(|_| true);
1044                         }
1045                     }
1046
1047                     // This conservatively assumes all operations have release semantics
1048                     Ok(true)
1049                 })?;
1050
1051                 // Log changes to atomic memory.
1052                 if log::log_enabled!(log::Level::Trace) {
1053                     for (_offset, range) in alloc_meta.alloc_ranges.borrow().iter(base_offset, size)
1054                     {
1055                         log::trace!(
1056                             "Updated atomic memory({:?}, size={}) to {:#?}",
1057                             place.ptr,
1058                             size.bytes(),
1059                             range.atomic_ops
1060                         );
1061                     }
1062                 }
1063             }
1064         }
1065         Ok(())
1066     }
1067 }
1068
1069 /// Extra metadata associated with a thread.
1070 #[derive(Debug, Clone, Default)]
1071 struct ThreadExtraState {
1072     /// The current vector index in use by the
1073     /// thread currently, this is set to None
1074     /// after the vector index has been re-used
1075     /// and hence the value will never need to be
1076     /// read during data-race reporting.
1077     vector_index: Option<VectorIdx>,
1078
1079     /// The name of the thread, updated for better
1080     /// diagnostics when reporting detected data
1081     /// races.
1082     thread_name: Option<Box<str>>,
1083
1084     /// Thread termination vector clock, this
1085     /// is set on thread termination and is used
1086     /// for joining on threads since the vector_index
1087     /// may be re-used when the join operation occurs.
1088     termination_vector_clock: Option<VClock>,
1089 }
1090
1091 /// Global data-race detection state, contains the currently
1092 /// executing thread as well as the vector-clocks associated
1093 /// with each of the threads.
1094 // FIXME: it is probably better to have one large RefCell, than to have so many small ones.
1095 #[derive(Debug, Clone)]
1096 pub struct GlobalState {
1097     /// Set to true once the first additional
1098     /// thread has launched, due to the dependency
1099     /// between before and after a thread launch.
1100     /// Any data-races must be recorded after this
1101     /// so concurrent execution can ignore recording
1102     /// any data-races.
1103     multi_threaded: Cell<bool>,
1104
1105     /// Mapping of a vector index to a known set of thread
1106     /// clocks, this is not directly mapping from a thread id
1107     /// since it may refer to multiple threads.
1108     vector_clocks: RefCell<IndexVec<VectorIdx, ThreadClockSet>>,
1109
1110     /// Mapping of a given vector index to the current thread
1111     /// that the execution is representing, this may change
1112     /// if a vector index is re-assigned to a new thread.
1113     vector_info: RefCell<IndexVec<VectorIdx, ThreadId>>,
1114
1115     /// The mapping of a given thread to associated thread metadata.
1116     thread_info: RefCell<IndexVec<ThreadId, ThreadExtraState>>,
1117
1118     /// The current vector index being executed.
1119     current_index: Cell<VectorIdx>,
1120
1121     /// Potential vector indices that could be re-used on thread creation
1122     /// values are inserted here on after the thread has terminated and
1123     /// been joined with, and hence may potentially become free
1124     /// for use as the index for a new thread.
1125     /// Elements in this set may still require the vector index to
1126     /// report data-races, and can only be re-used after all
1127     /// active vector-clocks catch up with the threads timestamp.
1128     reuse_candidates: RefCell<FxHashSet<VectorIdx>>,
1129
1130     /// Counts the number of threads that are currently active
1131     /// if the number of active threads reduces to 1 and then
1132     /// a join operation occurs with the remaining main thread
1133     /// then multi-threaded execution may be disabled.
1134     active_thread_count: Cell<usize>,
1135
1136     /// This contains threads that have terminated, but not yet joined
1137     /// and so cannot become re-use candidates until a join operation
1138     /// occurs.
1139     /// The associated vector index will be moved into re-use candidates
1140     /// after the join operation occurs.
1141     terminated_threads: RefCell<FxHashMap<ThreadId, VectorIdx>>,
1142
1143     /// The timestamp of last SC fence performed by each thread
1144     last_sc_fence: RefCell<VClock>,
1145
1146     /// The timestamp of last SC write performed by each thread
1147     last_sc_write: RefCell<VClock>,
1148 }
1149
1150 impl GlobalState {
1151     /// Create a new global state, setup with just thread-id=0
1152     /// advanced to timestamp = 1.
1153     pub fn new() -> Self {
1154         let mut global_state = GlobalState {
1155             multi_threaded: Cell::new(false),
1156             vector_clocks: RefCell::new(IndexVec::new()),
1157             vector_info: RefCell::new(IndexVec::new()),
1158             thread_info: RefCell::new(IndexVec::new()),
1159             current_index: Cell::new(VectorIdx::new(0)),
1160             active_thread_count: Cell::new(1),
1161             reuse_candidates: RefCell::new(FxHashSet::default()),
1162             terminated_threads: RefCell::new(FxHashMap::default()),
1163             last_sc_fence: RefCell::new(VClock::default()),
1164             last_sc_write: RefCell::new(VClock::default()),
1165         };
1166
1167         // Setup the main-thread since it is not explicitly created:
1168         // uses vector index and thread-id 0, also the rust runtime gives
1169         // the main-thread a name of "main".
1170         let index = global_state.vector_clocks.get_mut().push(ThreadClockSet::default());
1171         global_state.vector_info.get_mut().push(ThreadId::new(0));
1172         global_state.thread_info.get_mut().push(ThreadExtraState {
1173             vector_index: Some(index),
1174             thread_name: Some("main".to_string().into_boxed_str()),
1175             termination_vector_clock: None,
1176         });
1177
1178         global_state
1179     }
1180
1181     // Try to find vector index values that can potentially be re-used
1182     // by a new thread instead of a new vector index being created.
1183     fn find_vector_index_reuse_candidate(&self) -> Option<VectorIdx> {
1184         let mut reuse = self.reuse_candidates.borrow_mut();
1185         let vector_clocks = self.vector_clocks.borrow();
1186         let vector_info = self.vector_info.borrow();
1187         let terminated_threads = self.terminated_threads.borrow();
1188         for &candidate in reuse.iter() {
1189             let target_timestamp = vector_clocks[candidate].clock[candidate];
1190             if vector_clocks.iter_enumerated().all(|(clock_idx, clock)| {
1191                 // The thread happens before the clock, and hence cannot report
1192                 // a data-race with this the candidate index.
1193                 let no_data_race = clock.clock[candidate] >= target_timestamp;
1194
1195                 // The vector represents a thread that has terminated and hence cannot
1196                 // report a data-race with the candidate index.
1197                 let thread_id = vector_info[clock_idx];
1198                 let vector_terminated =
1199                     reuse.contains(&clock_idx) || terminated_threads.contains_key(&thread_id);
1200
1201                 // The vector index cannot report a race with the candidate index
1202                 // and hence allows the candidate index to be re-used.
1203                 no_data_race || vector_terminated
1204             }) {
1205                 // All vector clocks for each vector index are equal to
1206                 // the target timestamp, and the thread is known to have
1207                 // terminated, therefore this vector clock index cannot
1208                 // report any more data-races.
1209                 assert!(reuse.remove(&candidate));
1210                 return Some(candidate);
1211             }
1212         }
1213         None
1214     }
1215
1216     // Hook for thread creation, enabled multi-threaded execution and marks
1217     // the current thread timestamp as happening-before the current thread.
1218     #[inline]
1219     pub fn thread_created(&mut self, thread: ThreadId) {
1220         let current_index = self.current_index();
1221
1222         // Increment the number of active threads.
1223         let active_threads = self.active_thread_count.get();
1224         self.active_thread_count.set(active_threads + 1);
1225
1226         // Enable multi-threaded execution, there are now two threads
1227         // so data-races are now possible.
1228         self.multi_threaded.set(true);
1229
1230         // Load and setup the associated thread metadata
1231         let mut thread_info = self.thread_info.borrow_mut();
1232         thread_info.ensure_contains_elem(thread, Default::default);
1233
1234         // Assign a vector index for the thread, attempting to re-use an old
1235         // vector index that can no longer report any data-races if possible.
1236         let created_index = if let Some(reuse_index) = self.find_vector_index_reuse_candidate() {
1237             // Now re-configure the re-use candidate, increment the clock
1238             // for the new sync use of the vector.
1239             let vector_clocks = self.vector_clocks.get_mut();
1240             vector_clocks[reuse_index].increment_clock(reuse_index);
1241
1242             // Locate the old thread the vector was associated with and update
1243             // it to represent the new thread instead.
1244             let vector_info = self.vector_info.get_mut();
1245             let old_thread = vector_info[reuse_index];
1246             vector_info[reuse_index] = thread;
1247
1248             // Mark the thread the vector index was associated with as no longer
1249             // representing a thread index.
1250             thread_info[old_thread].vector_index = None;
1251
1252             reuse_index
1253         } else {
1254             // No vector re-use candidates available, instead create
1255             // a new vector index.
1256             let vector_info = self.vector_info.get_mut();
1257             vector_info.push(thread)
1258         };
1259
1260         log::trace!("Creating thread = {:?} with vector index = {:?}", thread, created_index);
1261
1262         // Mark the chosen vector index as in use by the thread.
1263         thread_info[thread].vector_index = Some(created_index);
1264
1265         // Create a thread clock set if applicable.
1266         let vector_clocks = self.vector_clocks.get_mut();
1267         if created_index == vector_clocks.next_index() {
1268             vector_clocks.push(ThreadClockSet::default());
1269         }
1270
1271         // Now load the two clocks and configure the initial state.
1272         let (current, created) = vector_clocks.pick2_mut(current_index, created_index);
1273
1274         // Join the created with current, since the current threads
1275         // previous actions happen-before the created thread.
1276         created.join_with(current);
1277
1278         // Advance both threads after the synchronized operation.
1279         // Both operations are considered to have release semantics.
1280         current.increment_clock(current_index);
1281         created.increment_clock(created_index);
1282     }
1283
1284     /// Hook on a thread join to update the implicit happens-before relation
1285     /// between the joined thread and the current thread.
1286     #[inline]
1287     pub fn thread_joined(&mut self, current_thread: ThreadId, join_thread: ThreadId) {
1288         let clocks_vec = self.vector_clocks.get_mut();
1289         let thread_info = self.thread_info.get_mut();
1290
1291         // Load the vector clock of the current thread.
1292         let current_index = thread_info[current_thread]
1293             .vector_index
1294             .expect("Performed thread join on thread with no assigned vector");
1295         let current = &mut clocks_vec[current_index];
1296
1297         // Load the associated vector clock for the terminated thread.
1298         let join_clock = thread_info[join_thread]
1299             .termination_vector_clock
1300             .as_ref()
1301             .expect("Joined with thread but thread has not terminated");
1302
1303         // The join thread happens-before the current thread
1304         // so update the current vector clock.
1305         // Is not a release operation so the clock is not incremented.
1306         current.clock.join(join_clock);
1307
1308         // Check the number of active threads, if the value is 1
1309         // then test for potentially disabling multi-threaded execution.
1310         let active_threads = self.active_thread_count.get();
1311         if active_threads == 1 {
1312             // May potentially be able to disable multi-threaded execution.
1313             let current_clock = &clocks_vec[current_index];
1314             if clocks_vec
1315                 .iter_enumerated()
1316                 .all(|(idx, clocks)| clocks.clock[idx] <= current_clock.clock[idx])
1317             {
1318                 // All thread terminations happen-before the current clock
1319                 // therefore no data-races can be reported until a new thread
1320                 // is created, so disable multi-threaded execution.
1321                 self.multi_threaded.set(false);
1322             }
1323         }
1324
1325         // If the thread is marked as terminated but not joined
1326         // then move the thread to the re-use set.
1327         let termination = self.terminated_threads.get_mut();
1328         if let Some(index) = termination.remove(&join_thread) {
1329             let reuse = self.reuse_candidates.get_mut();
1330             reuse.insert(index);
1331         }
1332     }
1333
1334     /// On thread termination, the vector-clock may re-used
1335     /// in the future once all remaining thread-clocks catch
1336     /// up with the time index of the terminated thread.
1337     /// This assigns thread termination with a unique index
1338     /// which will be used to join the thread
1339     /// This should be called strictly before any calls to
1340     /// `thread_joined`.
1341     #[inline]
1342     pub fn thread_terminated(&mut self) {
1343         let current_index = self.current_index();
1344
1345         // Increment the clock to a unique termination timestamp.
1346         let vector_clocks = self.vector_clocks.get_mut();
1347         let current_clocks = &mut vector_clocks[current_index];
1348         current_clocks.increment_clock(current_index);
1349
1350         // Load the current thread id for the executing vector.
1351         let vector_info = self.vector_info.get_mut();
1352         let current_thread = vector_info[current_index];
1353
1354         // Load the current thread metadata, and move to a terminated
1355         // vector state. Setting up the vector clock all join operations
1356         // will use.
1357         let thread_info = self.thread_info.get_mut();
1358         let current = &mut thread_info[current_thread];
1359         current.termination_vector_clock = Some(current_clocks.clock.clone());
1360
1361         // Add this thread as a candidate for re-use after a thread join
1362         // occurs.
1363         let termination = self.terminated_threads.get_mut();
1364         termination.insert(current_thread, current_index);
1365
1366         // Reduce the number of active threads, now that a thread has
1367         // terminated.
1368         let mut active_threads = self.active_thread_count.get();
1369         active_threads -= 1;
1370         self.active_thread_count.set(active_threads);
1371     }
1372
1373     /// Hook for updating the local tracker of the currently
1374     /// enabled thread, should always be updated whenever
1375     /// `active_thread` in thread.rs is updated.
1376     #[inline]
1377     pub fn thread_set_active(&self, thread: ThreadId) {
1378         let thread_info = self.thread_info.borrow();
1379         let vector_idx = thread_info[thread]
1380             .vector_index
1381             .expect("Setting thread active with no assigned vector");
1382         self.current_index.set(vector_idx);
1383     }
1384
1385     /// Hook for updating the local tracker of the threads name
1386     /// this should always mirror the local value in thread.rs
1387     /// the thread name is used for improved diagnostics
1388     /// during a data-race.
1389     #[inline]
1390     pub fn thread_set_name(&mut self, thread: ThreadId, name: String) {
1391         let name = name.into_boxed_str();
1392         let thread_info = self.thread_info.get_mut();
1393         thread_info[thread].thread_name = Some(name);
1394     }
1395
1396     /// Attempt to perform a synchronized operation, this
1397     /// will perform no operation if multi-threading is
1398     /// not currently enabled.
1399     /// Otherwise it will increment the clock for the current
1400     /// vector before and after the operation for data-race
1401     /// detection between any happens-before edges the
1402     /// operation may create.
1403     fn maybe_perform_sync_operation<'tcx>(
1404         &self,
1405         op: impl FnOnce(VectorIdx, RefMut<'_, ThreadClockSet>) -> InterpResult<'tcx, bool>,
1406     ) -> InterpResult<'tcx> {
1407         if self.multi_threaded.get() {
1408             let (index, clocks) = self.current_thread_state_mut();
1409             if op(index, clocks)? {
1410                 let (_, mut clocks) = self.current_thread_state_mut();
1411                 clocks.increment_clock(index);
1412             }
1413         }
1414         Ok(())
1415     }
1416
1417     /// Internal utility to identify a thread stored internally
1418     /// returns the id and the name for better diagnostics.
1419     fn print_thread_metadata(&self, vector: VectorIdx) -> String {
1420         let thread = self.vector_info.borrow()[vector];
1421         let thread_name = &self.thread_info.borrow()[thread].thread_name;
1422         if let Some(name) = thread_name {
1423             let name: &str = name;
1424             format!("Thread(id = {:?}, name = {:?})", thread.to_u32(), &*name)
1425         } else {
1426             format!("Thread(id = {:?})", thread.to_u32())
1427         }
1428     }
1429
1430     /// Acquire a lock, express that the previous call of
1431     /// `validate_lock_release` must happen before this.
1432     /// As this is an acquire operation, the thread timestamp is not
1433     /// incremented.
1434     pub fn validate_lock_acquire(&self, lock: &VClock, thread: ThreadId) {
1435         let (_, mut clocks) = self.load_thread_state_mut(thread);
1436         clocks.clock.join(lock);
1437     }
1438
1439     /// Release a lock handle, express that this happens-before
1440     /// any subsequent calls to `validate_lock_acquire`.
1441     /// For normal locks this should be equivalent to `validate_lock_release_shared`
1442     /// since an acquire operation should have occurred before, however
1443     /// for futex & condvar operations this is not the case and this
1444     /// operation must be used.
1445     pub fn validate_lock_release(&self, lock: &mut VClock, thread: ThreadId) {
1446         let (index, mut clocks) = self.load_thread_state_mut(thread);
1447         lock.clone_from(&clocks.clock);
1448         clocks.increment_clock(index);
1449     }
1450
1451     /// Release a lock handle, express that this happens-before
1452     /// any subsequent calls to `validate_lock_acquire` as well
1453     /// as any previous calls to this function after any
1454     /// `validate_lock_release` calls.
1455     /// For normal locks this should be equivalent to `validate_lock_release`.
1456     /// This function only exists for joining over the set of concurrent readers
1457     /// in a read-write lock and should not be used for anything else.
1458     pub fn validate_lock_release_shared(&self, lock: &mut VClock, thread: ThreadId) {
1459         let (index, mut clocks) = self.load_thread_state_mut(thread);
1460         lock.join(&clocks.clock);
1461         clocks.increment_clock(index);
1462     }
1463
1464     /// Load the vector index used by the given thread as well as the set of vector clocks
1465     /// used by the thread.
1466     #[inline]
1467     fn load_thread_state_mut(&self, thread: ThreadId) -> (VectorIdx, RefMut<'_, ThreadClockSet>) {
1468         let index = self.thread_info.borrow()[thread]
1469             .vector_index
1470             .expect("Loading thread state for thread with no assigned vector");
1471         let ref_vector = self.vector_clocks.borrow_mut();
1472         let clocks = RefMut::map(ref_vector, |vec| &mut vec[index]);
1473         (index, clocks)
1474     }
1475
1476     /// Load the current vector clock in use and the current set of thread clocks
1477     /// in use for the vector.
1478     #[inline]
1479     pub(super) fn current_thread_state(&self) -> (VectorIdx, Ref<'_, ThreadClockSet>) {
1480         let index = self.current_index();
1481         let ref_vector = self.vector_clocks.borrow();
1482         let clocks = Ref::map(ref_vector, |vec| &vec[index]);
1483         (index, clocks)
1484     }
1485
1486     /// Load the current vector clock in use and the current set of thread clocks
1487     /// in use for the vector mutably for modification.
1488     #[inline]
1489     pub(super) fn current_thread_state_mut(&self) -> (VectorIdx, RefMut<'_, ThreadClockSet>) {
1490         let index = self.current_index();
1491         let ref_vector = self.vector_clocks.borrow_mut();
1492         let clocks = RefMut::map(ref_vector, |vec| &mut vec[index]);
1493         (index, clocks)
1494     }
1495
1496     /// Return the current thread, should be the same
1497     /// as the data-race active thread.
1498     #[inline]
1499     fn current_index(&self) -> VectorIdx {
1500         self.current_index.get()
1501     }
1502
1503     // SC ATOMIC STORE rule in the paper.
1504     pub(super) fn sc_write(&self) {
1505         let (index, clocks) = self.current_thread_state();
1506         self.last_sc_write.borrow_mut().set_at_index(&clocks.clock, index);
1507     }
1508
1509     // SC ATOMIC READ rule in the paper.
1510     pub(super) fn sc_read(&self) {
1511         let (.., mut clocks) = self.current_thread_state_mut();
1512         clocks.read_seqcst.join(&self.last_sc_fence.borrow());
1513     }
1514 }